Search code examples
pythonsshpexpect

python pexpect does not launch my ssh tunnel


i have got this script (called tunnel):

(ip server replaced with ssh_server_ip)

ssh -ND 5545 -p 443 -vvv user@ssh_server_ip

I try to run it through python pexpect.

import pexpect 
import time

p = pexpect.run('./tunnel')
#does not work with spawn
#p = pexpect.spawn('./tunnel') 
p.expect('password: ')
time.sleep(2)
p.sendline('pswd')

when I run the script, there is a connection with the server, but it does not last long (few seconds)

ssh        8872    root    3u  IPv4 510801      0t0  TCP 192.168.1.36:46328->ssh_server_ip:https (ESTABLISHED)

if the ssh tunnel is fully established, I should have the following:

ssh        8130    root    3u  IPv4 503864      0t0  TCP 192.168.1.36:46326->ssh_server_ip:https (ESTABLISHED)
ssh        8130    root    4u  IPv6 505215      0t0  TCP [::1]:5545 (LISTEN)
ssh        8130    root    5u  IPv4 505216      0t0  TCP 127.0.0.1:5545 (LISTEN)

shall I use the bash expect instead of python pexpect?

thanx folks!


Solution

  • You need to write like this:

    p.sendline('password')
    p.expect(pexpect.EOF)
    

    Otherwise the Python script will exit immediately after sending the password which in turn will kill the ssh command.