Rev | Line | |
---|
[421] | 1 | #!/usr/bin/env python |
---|
| 2 | """This starts an SSH tunnel to a given host. |
---|
| 3 | If the SSH process ever dies then this script will detect that and restart it. |
---|
| 4 | I use this under Cygwin to keep open encrypted tunnels to |
---|
| 5 | port 110 (POP3) and port 25 (SMTP). I set my mail client to talk to |
---|
| 6 | localhost and I keep this script running in the background. |
---|
| 7 | """ |
---|
| 8 | import pexpect |
---|
| 9 | import getpass |
---|
| 10 | import time |
---|
| 11 | |
---|
| 12 | #tunnel_command = 'ssh -C -N -L 25:%(host)s:25 -L 110:%(host)s:110 %(user)s@%(host)s' |
---|
| 13 | tunnel_command = 'ssh -C -n -L 25:%(host)s:25 -L 110:%(host)s:110 %(user)s@%(host)s -f nothing.sh' |
---|
| 14 | nothing_script = """#!/bin/sh |
---|
| 15 | while true; do sleep 53; done |
---|
| 16 | """ |
---|
| 17 | host = raw_input('Hostname: ') |
---|
| 18 | user = raw_input('Username: ') |
---|
| 19 | X = getpass.getpass('Password: ') |
---|
| 20 | |
---|
| 21 | def start_tunnel (): |
---|
| 22 | ssh_tunnel = pexpect.spawn (tunnel_command % globals()) |
---|
| 23 | try: |
---|
| 24 | ssh_tunnel.expect ('password:') |
---|
| 25 | except Exception, e: |
---|
| 26 | print str(e) |
---|
| 27 | print ssh_tunnel.before |
---|
| 28 | print ssh_tunnel.after |
---|
| 29 | time.sleep (0.1) |
---|
| 30 | ssh_tunnel.sendline (X) |
---|
| 31 | time.sleep (60) # Cygwin is slow to update process status. |
---|
| 32 | ssh_tunnel.expect (pexpect.EOF) |
---|
| 33 | |
---|
| 34 | def main (): |
---|
| 35 | while 1: |
---|
| 36 | ps = pexpect.spawn ('ps') |
---|
| 37 | time.sleep (1) |
---|
| 38 | index = ps.expect (['/usr/bin/ssh', pexpect.EOF, pexpect.TIMEOUT]) |
---|
| 39 | if index == 2: |
---|
| 40 | print 'TIMEOUT in ps command...' |
---|
| 41 | print ps.before |
---|
| 42 | print ps.after |
---|
| 43 | if index == 1: |
---|
| 44 | print time.asctime(), |
---|
| 45 | print 'restarting tunnel' |
---|
| 46 | start_tunnel () |
---|
| 47 | time.sleep (60) |
---|
| 48 | print 'tunnel OK' |
---|
| 49 | else: |
---|
| 50 | # print 'tunnel OK' |
---|
| 51 | time.sleep (60) |
---|
| 52 | |
---|
| 53 | if __name__ == '__main__': |
---|
| 54 | main () |
---|
| 55 | |
---|
| 56 | |
---|
Note: See
TracBrowser
for help on using the repository browser.