当有跳板机,paramiko 依然可以正常使用
#!/usr/bin/env python3import osimport paramiko# exec_command(cmd)
# 文件传输
class connect_ssh:def __init__(self):jump_ip = "10.110.19.*"  # 跳板机jump_user = "***"jump_password = "***"remote_ip = '172.20.10.*'  # 目的服务器remote_username = "***"remote_passwd = "****"# 创建一个实例化jumpbox_ssh = paramiko.SSHClient()# 自动添加策略,保存远端主机的主机名和密钥信息,如果不添加,那么不在本地knows_hosts文件中记录的主机将无法连接,默认拒接jumpbox_ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())# 连接跳板机jumpbox_ssh.connect(hostname=jump_ip, username=jump_user, password=jump_password)# 创建一个中间连接的通道jumpbox_transport = jumpbox_ssh.get_transport()src_addr = (jump_ip, 22)dest_addr = (remote_ip, 22)jumpbox_channel = jumpbox_transport.open_channel(kind="direct-tcpip", dest_addr=dest_addr, src_addr=src_addr, )# 去连接远端服务器target_ssh = paramiko.SSHClient()target_ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())target_ssh.connect(hostname=remote_ip, username=remote_username, password=remote_passwd,sock=jumpbox_channel)# 创建一个SFTP客户端通道trans = target_ssh.get_transport()sftp = paramiko.SFTPClient.from_transport(trans)self.target_ssh = target_sshself.sftp = sftpdef execute(self, cmd):    stdin, stdout, stderr = self.target_ssh.exec_command(cmd)print(stdout.read())return stdout.read()def upload_file(self, local_path, remote_path):    self.sftp.put(localpath=local_path, remotepath=remote_path)print("** Upload file succeefully! **")def download_file(self, remote_path, local_path):self.sftp.get(remotepath=remote_path, localpath=local_path)print("** download file succeefully! **")def close(self, cmd):    self.target_ssh.close()self.jumpbox_ssh.close()self.sftp.close()print("Closed!")if __name__ == '__main__':server = connect_ssh()server.execute("pwd\n")print("done")