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()
        if "logout" in data:
            break
        print(data, end = "")


def main():
    with SSHTunnelForwarder(ssh_address_or_host=('192.168.1.104', 22), ssh_username="104user", ssh_password="104pwd",
                            remote_bind_address=("192.168.1.105", 22), local_bind_address=('127.0.0.1', 10022)) as tunnel:
        print("111", tunnel.local_bind_address, tunnel.local_bind_port)
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        print("222")
        client.connect('127.0.0.1', tunnel.local_bind_port, username = "105user", password = "105pwd")
        print("333")
        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()

 

上面的代码通过, 192.168.1.104 连接到 192.168.1.105

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄