shantanuo
shantanuo

Reputation: 32294

connect to third server using script

I can do ssh from one server to another using this:

# ssh [email protected] 

The following code is doing the same in pythonic way:

import paraminko

#paramiko.util.log_to_file('ssh.log') # sets up logging

client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect('1.2.4.148')
stdin, stdout, stderr = client.exec_command('ls -l')

But if I need to connect to third server from the second server, I can do this:

# ssh -t [email protected] ssh [email protected]

How is this done in python? My current server (250) has password less keys saved with 148 server for easy access. But connection to 149 from 148 will need password if that matters.

Upvotes: 0

Views: 1113

Answers (1)

shantanuo
shantanuo

Reputation: 32294

This python function will connect to middle_server first and then to last_server. It will execute the command "mycommand" on last_server and return it's output.

def myconnect():
    middle_server='1.2.3.4'
    middle_port=3232
    middle_user='shantanu'
    middle_key_filename='/root/.ssh/id_rsa.pub'
    last_server='6.7.8.9'
    last_port=1224
    last_user='root'
    last_password='xxxxx'
    mycommand='pwd'

    import paramiko
    proxy_client = paramiko.SSHClient()
    proxy_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    proxy_client.connect(middle_server, port=middle_port, username=middle_user,  key_filename=middle_key_filename)
    transport = proxy_client.get_transport()
    dest_addr = (last_server, last_port)
    local_addr = ('127.0.0.1', 1234)
    channel = transport.open_channel("direct-tcpip", dest_addr, local_addr)
    remote_client = paramiko.SSHClient()
    remote_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        remote_client.connect('localhost', port=last_port, username=last_user, password=last_password, sock=channel)
        (sshin1, sshout1, ssherr1) = remote_client.exec_command(mycommand)
        print sshout1.read()
    except:
        print "error"
    return 0

Upvotes: 3

Related Questions