1#!/usr/bin/env python
2
3"""This starts an SSH tunnel to a given host. If the SSH process ever dies then
4this script will detect that and restart it. I use this under Cygwin to keep
5open encrypted tunnels to port 25 (SMTP), port 143 (IMAP4), and port 110
6(POP3). I set my mail client to talk to localhost and I keep this script
7running in the background.
8
9Note that this is a rather stupid script at the moment because it just looks to
10see if any ssh process is running. It should really make sure that our specific
11ssh process is running. The problem is that ssh is missing a very useful
12feature. It has no way to report the process id of the background daemon that
13it creates with the -f command. This would be a really useful script if I could
14figure a way around this problem. """
15
16import pexpect
17import getpass
18import time
19
20# SMTP:25 IMAP4:143 POP3:110
21tunnel_command = 'ssh -C -N -f -L 25:127.0.0.1:25 -L 143:127.0.0.1:143 -L 110:127.0.0.1:110 %(user)@%(host)'
22host = raw_input('Hostname: ')
23user = raw_input('Username: ')
24X = getpass.getpass('Password: ')
25
26def get_process_info ():
27
28    # This seems to work on both Linux and BSD, but should otherwise be considered highly UNportable.
29
30    ps = pexpect.run ('ps ax -O ppid')
31    pass
32def start_tunnel ():
33    try:
34        ssh_tunnel = pexpect.spawn (tunnel_command % globals())
35        ssh_tunnel.expect ('password:')
36        time.sleep (0.1)
37        ssh_tunnel.sendline (X)
38        time.sleep (60) # Cygwin is slow to update process status.
39        ssh_tunnel.expect (pexpect.EOF)
40
41    except Exception, e:
42        print str(e)
43
44def main ():
45
46    while True:
47        ps = pexpect.spawn ('ps')
48        time.sleep (1)
49        index = ps.expect (['/usr/bin/ssh', pexpect.EOF, pexpect.TIMEOUT])
50        if index == 2:
51            print 'TIMEOUT in ps command...'
52            print str(ps)
53            time.sleep (13)
54        if index == 1:
55            print time.asctime(),
56            print 'restarting tunnel'
57            start_tunnel ()
58            time.sleep (11)
59	        print 'tunnel OK'
60        else:
61            # print 'tunnel OK'
62            time.sleep (7)
63
64if __name__ == '__main__':
65    main ()
66
67# This was for older SSH versions that didn't have -f option
68#tunnel_command = 'ssh -C -n -L 25:%(host)s:25 -L 110:%(host)s:110 %(user)s@%(host)s -f nothing.sh'
69#nothing_script = """#!/bin/sh
70#while true; do sleep 53; done
71#"""
72
73