import paramiko class Monitor(object): def __init__(self, server_ip, user, pwd): """ 初始化ssh客戶端 """ try: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.client = client print('------------開始連接服務器(%s)-----------' % server_ip) self.client.connect(server_ip, 22, username=user, password=pwd, timeout=4) print('------------認證成功!.....-----------') except Exception: print(f'連接遠程linux服務器(ip:{server_ip})發生異常!請檢查用戶名和密碼是否正確!') def link_server(self, cmd): """連接服務器發送命令""" try: stdin, stdout, stderr = self.client.exec_command(cmd) content = stdout.read().decode('gbk') return content except Exception as e: print('link_server-->返回命令發生異常,內容:', e) finally: self.client.close()