Python Forum
ssh tunnel connection dropped with Python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Networking (https://python-forum.io/forum-12.html)
+--- Thread: ssh tunnel connection dropped with Python (/thread-34109.html)



ssh tunnel connection dropped with Python - achille - Jun-27-2021

under linux bash, I build ssh tunnel this way:
ssh -ND 5545 -vvv -p 443 user@server

Output:
[...] user@server's password: [...] debug1: pledge: network
From there, I know my tunnel is established. If no verbose mode used, 'netstat -tl' command confirms the tunnel has been established. I can perfectly automatize this with bash expect utility (skiping the fingerprint acknowledgement when first time connection)

Now I am trying to do the same thing in python:
import pexpect, sys

def ssh_con(host,user,password):
   child = pexpect.spawn("ssh -ND 5545 -vvv -p 443 %s@%s" % (user,host))
   i = child.expect([pexpect.TIMEOUT, 'password: '])
   if i == 0: #timeout
      print( "ssh connection timeout")
      sys.exit(1)
   if i == 1:
      print("ssh connection ok, sending password...")
      child.sendline(password)
      i = child.expect([pexpect.TIMEOUT, 'pledge: network'])
      if i==0:
         print("password timeout issue")
         sys.exit(1)
   elif i==1:
        print("tunnel sould be up and running now")

def main():       
  host = '<server_ip>'
  user = '<username>'
  password = '<password>'

  child = ssh_con( host, user, password)

if __name__ == '__main__':
   main()
All goes fine, until the script reaches the end ('tunnel sould be up and running now'), where it exits / hangs up instead of keeping the tunnel up and running.


Thanx folks !