Python编程:封装paramiko模块实现便捷的远程登录

版权声明:本文为博主原创文章,欢迎转载,请注明出处 https://blog.csdn.net/mouday/article/details/88363307

基于 paramiko 的使用,将其做简单封装,便于使用

# -*- coding: utf-8 -*-

import paramiko


class SSHClient(object):
    def __init__(self, hostname, username, password):
        self.hostname = hostname
        self.username = username
        self.password = password
        self.ssh = None
        self._connect()

    def __del__(self):
        self.ssh.close()

    def _connect(self):
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(hostname=self.hostname, username=self.username, password=self.password)

    def execute_command(self, command):
        stdin, stdout, stderr = self.ssh.exec_command(command)
        stdout = stdout.read().decode("utf-8")
        stderr = stderr.read().decode("utf-8")
        return stdout, stderr


# 使用示例
def main():
    cmd = "pwd"

    client = SSHClient(hostname, username, password)
    stdout, stderr = client.execute_command(cmd)
    print(stdout, stderr)


if __name__ == '__main__':
    main()

参考:
Python编程:paramiko模块远程登录

没有更多推荐了,返回首页