通过SSH连接到主机,然后通过ssh隧道连接到另一台主机

时间:2020-07-15 11:55:44

标签: python networking ssh paramiko tunnel

下面的代码(main.py)实现了通过SSH对主机的访问,并为127.0.0.1访问的IP创建了一条隧道:

Cannot find UI element.
    Exception with Action: {
      "Action Name":  "Scroll To Bottom content edge",
...

Error Trace: [
      {
        "Description":  "Interaction cannot continue because the desired element was not found.",
        "Error Domain":  "com.google.earlgrey.ElementInteractionErrorDomain",
        "Error Code":  "0",
        "File Name":  "GREYElementInteraction.m",
        "Function Name":  "-[GREYElementInteraction matchedElementsWithTimeout:error:]",
        "Line":  "124"
      }
    ]

我正在尝试访问特定的计算机,为此,出于网络原因,我必须首先访问计算机。

在Python中,我运行main.py在初始计算机上执行SSH,然后为另一台计算机创建隧道,并设法在其上执行远程命令。

import paramiko
from sshtunnel import SSHTunnelForwarder
from paramiko import SSHClient

class SSH:
    def __init__(self):
        self.ssh = SSHClient()
        self.ssh.load_system_host_keys()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(hostname='127.0.0.1',port='10022',username='root',password='root')

        def exec_cmd(self,cmd):
            stdin,stdout,stderr = self.ssh.exec_command(cmd)
            if stderr.channel.recv_exit_status() != 0:
                print (stderr.read())
            else:
                print (stdout.read())


server = SSHTunnelForwarder(
    '192.168.100.10',
    ssh_username="root",
    ssh_password="root",
    remote_bind_address=('127.0.0.1', 22),
    local_bind_address=('0.0.0.0', 10022)
)

server.start()

if __name__ == '__main__':
    ssh = SSH()
    stdin,stdout,stderr = ssh.ssh.exec_command("hostname")
    retorno = stdout.read()
    print (retorno)

server.stop()

Putty对拓扑的访问是:访问初始连接(您为其创建了网络规则的连接),然后对另一台计算机执行SSH命令,到达所需的计算机。

如上面的代码所述,我只能访问第一台主机。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

我进行了以下更改:

    server = SSHTunnelForwarder(
    '192.168.1.1',
    ssh_username="teste2",
    ssh_password="teste2",
    remote_bind_address=('<Destination HOST IP>', 22),
    local_bind_address=('127.0.0.1', 10022) # Here you leave the loopback ip
)