pythonsshparamiko

Second .connect with paramiko (ssh)


Form the main Linux OS (connected, working) I would like to run another ".connect".

Here is the code:

import paramiko
hostname =  "hostaname"
ip =        "1111.111.11.11"
username =  "user"
password =  "pass"
    
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname,username=username, password=password)

Now from the main I want to accesses another localhost:

hostname =  "localhost"
ip =        "222.222.2.2"
username =  "root"
password =  "root"
ssh.connect(hostname=hostname,username=username, password=password)

I get the following error:

NoValidConnectionsError: [Errno None] Unable to connect to port 22 on 222.222.2.2 or ::1

UPD: I found my answer in the following question: Nested SSH using Python Paramiko


Solution

  • UPD: I found my answer in the following question: Nested SSH using Python Paramiko

    Here is my full code and solution:

    import paramiko
    ip1_hostname =  "host-name-2024"
    
    ip1 =      "1111.111.11.11"
    ip2 =      "222.222.2.2"
    
    ip1_username =  "username"
    ip1_password =  "password"
    
    root_user =     "root"
    root_password = "root"
    
    ip1_machine = paramiko.SSHClient()
    ip1_machine.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ip1_machine.connect(hostname=ip1_hostname,username=ip1_username, password=ip1_password)
    
    std_in, std_out, std_err = ip1_machine.exec_command('ls')
    print(f"{std_out.read().decode().split()}")
    
    # based on https://stackoverflow.com/questions/35304525/nested-ssh-using-python-paramiko
    ip1_transport = ip1_machine.get_transport()
    dest_addr = (ip2, 22)     # "222.222.2.2"
    local_addr = (ip1, 22)   # "1111.111.11.11"
    ip2_channel = ip1_transport.open_channel("direct-tcpip", dest_addr, local_addr)
    
    ip2 = paramiko.SSHClient()
    ip2.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ip2.connect(ip2, username=root_user, password=root_password, sock=ip2_channel)
    std_in, std_out, std_err = ip2.exec_command('ls')
    print(f"{std_out.read().decode().split()}")