connect to third server using script
Question: I can do ssh from one server to another using this:

    
    
    # ssh root@1.2.4.148 
    

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 root@1.2.4.148 ssh root@1.2.4.149
    

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.


Answer: 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
    

