import paramiko class SshEngine: """ ssh连接对象 本对象提供了密钥连接、密码连接、命令执行、关闭连接 """ ip = '' port = 22 username = '' timeout = 0 ssh = None def __init__(self, ip, username, port=22, timeout=30): """ 初始化ssh对象 :param ip: str 主机IP :param username: str 登录用户名 :param port: int ssh端口 :param timeout: int 连接超时 """ self.ip = ip self.username = username self.port = port self.timeout = timeout ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh = ssh def conn_by_key(self, key): """ 密钥连接 :param key: str rsa密钥路径 :return: ssh连接对象 """ rsa_key = paramiko.RSAKey.from_private_key_file(key) self.ssh.connect(hostname=self.ip, port=self.port, username=self.username, pkey=rsa_key, timeout=self.timeout) if self.ssh: return self.ssh else: self.close() raise Exception("密钥连接失败.") def conn_by_pwd(self, pwd): """ 密码连接 :param pwd: str 登录密码 :return: ssh连接对象 """ self.ssh.connect(hostname=self.ip, port=self.port, username=self.username, password=pwd) if self.ssh: return self.ssh else: self.close() raise Exception("密码连接失败.") def exec_command(self, command): """ 命令控制 :param command: str 命令 :return: dict 命令执行的返回结果 """ if command: #stdin, stdout, stderr = self.ssh.exec_command(command) #return stdout shell = self.ssh.invoke_shell() shell.settimeout(1) shell.send(command) print("----the command is ",command) recv = shell.recv(20480).decode(encoding='UTF-8') #recv = shell.recv(512).decode() #recv=shell.recv() # str_data = "" # while True: # try: # recv = shell.recv(20480).decode(encoding='UTF-8') # if recv: # print("11111111111") # # str_data.append(recv) # #if "=" in recv: # # print(" == in recv ",recv) # # return recv # # print(str_data) # # else: # continue # except: # print("the except is recv:",str_data) # return recv #command = input(">>>") + "\n" #shell.send(command) print("-----------------redv----------") return recv else: self.close() raise Exception("命令不能为空字符串.") def close(self): """ 关闭当前连接 :return: """ if self.ssh: self.ssh.close() else: raise Exception("ssh关闭失败,当前对象并没有ssh连接.")
python ssh
最新推荐文章于 2024-07-11 10:15:46 发布
这个Python类实现了SSH连接的功能,包括通过密钥和密码方式连接远程服务器,执行命令并获取返回结果,以及关闭SSH连接。类中包含了`conn_by_key`和`conn_by_pwd`方法分别用于密钥和密码认证,`exec_command`方法用于执行命令并打印输出,最后`close`方法用于关闭连接。
摘要由CSDN通过智能技术生成