v2-4f769c69bd38d05693de5548789373ab_1440w.jpg

# -*- 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


#usage
def main():
    cmd = "pwd"

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


if __name__ == '__main__':
    main()

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

Captcha Code