且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-09-05 10:21:55

基于 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模块远程登录