Nested SSH session with Paramiko

后端 未结 5 982
眼角桃花
眼角桃花 2020-11-27 03:42

I\'m rewriting a Bash script I wrote into Python. The crux of that script was

ssh -t first.com \"ssh second.com very_remote_command\"

I\'m

5条回答
  •  隐瞒了意图╮
    2020-11-27 04:13

    I managed to find a solution, but it requires a little manual work. If anyone have a better solution, please tell me.

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect('first.com', username='luser', password='secret')
    
    chan = ssh.invoke_shell()
    
    # Ssh and wait for the password prompt.
    chan.send('ssh second.com\n')
    buff = ''
    while not buff.endswith('\'s password: '):
        resp = chan.recv(9999)
        buff += resp
    
    # Send the password and wait for a prompt.
    chan.send('secret\n')
    buff = ''
    while not buff.endswith('some-prompt$ '):
        resp = chan.recv(9999)
        buff += resp
    
    # Execute whatever command and wait for a prompt again.
    chan.send('ls\n')
    buff = ''
    while not buff.endswith('some-prompt$ '):
        resp = chan.recv(9999)
        buff += resp
    
    # Now buff has the data I need.
    print 'buff', buff
    
    ssh.close()
    

    The thing to note is that instead of this

    t = ssh.get_transport()
    chan = t.open_session()
    chan.get_pty()
    

    ...you want this

    chan = ssh.invoke_shell()
    

    It reminds me of when I tried to write a TradeWars script when I was a kid and gave up coding for ten years. :)

提交回复
热议问题