source: CMTManagement/utils/ssh_tunnel.py @ 421

Last change on this file since 421 was 421, checked in by garonne, 17 years ago
File size: 1.6 KB
Line 
1#!/usr/bin/env python
2"""This starts an SSH tunnel to a given host.
3If the SSH process ever dies then this script will detect that and restart it.
4I use this under Cygwin to keep open encrypted tunnels to
5port 110 (POP3) and port 25 (SMTP). I set my mail client to talk to
6localhost and I keep this script running in the background.
7"""
8import pexpect
9import getpass
10import time
11
12#tunnel_command = 'ssh -C -N  -L 25:%(host)s:25 -L 110:%(host)s:110 %(user)s@%(host)s'
13tunnel_command = 'ssh -C -n -L 25:%(host)s:25 -L 110:%(host)s:110 %(user)s@%(host)s -f nothing.sh'
14nothing_script = """#!/bin/sh
15while true; do sleep 53; done
16"""
17host = raw_input('Hostname: ')
18user = raw_input('Username: ')
19X = getpass.getpass('Password: ')
20
21def 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
34def 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
53if __name__ == '__main__':
54    main ()
55
56
Note: See TracBrowser for help on using the repository browser.