天天看點

Python程式設計:封裝paramiko子產品實作便捷的遠端登入

基于 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子產品遠端登入