#!/usr/bin/python3 # _*_coding: utf-8_*_ import paramiko class OP_test(): def __init__(self, hostname, username='root', password=None, port=22): self.username = username self.hostname = hostname self.password = password self.port = port self.Tran = paramiko.Transport((self.hostname, self.port)) self.Tran.connect(username=self.username, password=self.password) def ssh(self, cmd): try: self.ssh_obj = paramiko.SSHClient() self.ssh_obj._transport = self.Tran __stdin, stdout, stderr = self.ssh_obj.exec_command(cmd) if stdout.read(): return str(stdout.read(), encoding='utf-8') else: return str(stderr.read(), encoding='utf-8') except Exception as e: print(e) finally: self.Tran.close() def sftp(self, src, dst, mode='get'): try: self.sftp_obj = paramiko.SFTPClient.from_transport(self.Tran) if mode == 'get': self.sftp_obj.get(dst, src) return True elif mode == 'put': self.sftp_obj.put(src, dst) return True except Exception as e: print(e) finally: self.Tran.close() ssh_test = OP_test(hostname='10.20.154.108', username='root', password='123123', port=22) print(ssh_test.ssh('ls /tt')) #result = ssh_test.sftp('/Users/mingwang/Desktop/test.py','/tmp/test.py.77',mode='put') #result = ssh_test.sftp('/etc','Users/mingwang/Desktop/test',mode='get')