Attempting to do remote login over SSH connection using python script

617 Views Asked by At

I am trying to log in to a remote server after setting up an SSH connection. I can get the SSH Tunnel to work, but from there I'm stumped on how to log in.

I am currently using Python's sshtunnel extension, which successfully connects me to the place I need. Now I need to be able to log in which I would usually do through a terminal with the command "ssh remotepc-ssh" (I have all the information stored in a /.ssh/config file)

I have already tried paramiko but it continuously gives me errors or won't load in the end. I also tried pysftp which is what I show in the code below but when I try to get the my known_hosts it tells me that it isn't finding any known ones, and when I try to set hosts to None, the system won't connect.

from sshtunnel import SSHTunnelForwarder
#import paramiko
import pprint
import pysftp

# create SSH tunnel

SERVER_HOST = "hostname"
SERVER_PASS = "********"

LOGIN_HOST = "loginUsername"
LOGIN_PASS = "*********" 


server = SSHTunnelForwarder(
    SERVER_HOST,
    ssh_password = SERVER_PASS,
    remote_bind_address=('127.0.0.1', 8080)
)

try:
    server.start()

    print("Connected to SSH Tunnel with local bind port %s" %server.local_bind_port)

    ###################################
    # BROKEN PART BELOW

    # establish remote connection
    try:

        print("\nEstablishing connection to %s" %LOGIN_HOST)

        cnopts = pysftp.CnOpts()
        cnopts.hostkeys.load = ("known_hosts")
        with pysftp.Connection(LOGIN_HOST, password = LOGIN_PASS, cnopts = cnopts) as sftp:
             print("CONNECTED")

    except:
        print("Unable to connect")
        pass

    ##################################

    server.stop()
    print("\nServer stopped. Goodbye")

except:
    print("Could not connect")
    pass
1

There are 1 best solutions below

0
Michal On

I've just came by and solved the same issue, so let me share my working example:

with SSHTunnelForwarder(
    ("SSH_HOST",22),
    ssh_username="SSH_USERNAME",
    ssh_pkey="SSH_KEY",
    remote_bind_address=("SFTP_HOST", 22),
) as tunnel:
    # do some operations with client session
    with pysftp.Connection(host='127.0.0.1', port=server.local_bind_port, username="SFTP_USERNAME",
                           private_key="SFTP_KEY", cnopts=cnopts) as sftp:
        print("Connection succesfully stablished ... ")
        print(sftp.listdir('public'))
print('FINISH!')