ssh 通过跳板机连接到远程服务器
import paramiko from sshtunnel import SSHTunnelForwarder import threading def readData(shell): while True: data = shell.recv(2048) if not data: print("quit now") break data = data.decode() print(data, end = "") def main(): port104 = 22 port105 = 22 localport = 10022 with SSHTunnelForwarder(ssh_address_or_host=('192.168.1.104', port104), ssh_username="104usr", ssh_password="104pwd", remote_bind_address=("192.168.1.105", port105), local_bind_address=('127.0.0.1', localport)) as tunnel: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(tunnel.local_bind_host, tunnel.local_bind_port, username = "105usr", password = "105pwd") shell = client.invoke_shell() thread = threading.Thread(target=readData, args=(shell,)) thread.start() shell.sendall("pwd\n") shell.sendall("ifconfig\n") shell.sendall("exit\n") thread.join() client.close() if __name__ == '__main__': main()
上面的代码通过, 192.168.1.104 连接到 192.168.1.105
其中 192.168.1.104 是跳板机 ip, 192.168.1.105 是我们需要连接的服务器. 某些情况下, 我们无法直接连接到服务器, 而有其它主机可以连接到该服务器时就可以发挥作用了.