Skip to content

Commit 4d86af9

Browse files
author
Adam Williams
committed
initial commit
1 parent c0aa9ce commit 4d86af9

File tree

3 files changed

+101
-0
lines changed

3 files changed

+101
-0
lines changed

config.ini

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[SSH Host]
2+
Host=foo
3+
User=foo

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pexpect

ssh-proxy.py

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
#!/usr/bin/env python3
2+
3+
import os
4+
import sys
5+
import getpass
6+
import pexpect
7+
import time
8+
import signal
9+
import configparser
10+
11+
config = configparser.ConfigParser()
12+
config.read('config.ini')
13+
14+
user = config.get('SSH Host', 'User')
15+
host = config.get('SSH Host', 'Host')
16+
17+
ssh_command = 'ssh -C2qTnN -D 8080 -f %s@%s' % (user, host)
18+
19+
def printer(message):
20+
print('%s' % message)
21+
22+
def run_command(arg):
23+
if '--start' == arg:
24+
start()
25+
elif '--stop' == arg:
26+
stop()
27+
elif '--restart' == arg:
28+
restart()
29+
elif '--status' == arg:
30+
status()
31+
else:
32+
print('USAGE: %s [--start,--stop,--restart, --status]' % sys.argv[0])
33+
34+
def get_pids():
35+
ps = pexpect.run('ps -ax')
36+
pids = []
37+
38+
for line in ps.splitlines():
39+
if str(line).find(ssh_command) > 0:
40+
line_split = str(line).split(' ')
41+
pids.append(line_split[0][2:])
42+
43+
if len(pids) > 0:
44+
return pids
45+
46+
return False
47+
48+
def start():
49+
if not (get_pids()):
50+
printer('SSH Proxy starting...')
51+
password = getpass.getpass(prompt='SSH password for %s: ' % user)
52+
53+
try:
54+
ssh_tunnel = pexpect.spawn (ssh_command % globals())
55+
ssh_tunnel.expect ('password:')
56+
time.sleep (0.1)
57+
ssh_tunnel.sendline (password)
58+
time.sleep (0.1)
59+
ssh_tunnel.expect (pexpect.EOF)
60+
61+
except Exception as e:
62+
print('Error: Unable to create tunnel. Try running the command manually for details:')
63+
printer(ssh_command)
64+
else:
65+
printer('SSH Proxy is already running')
66+
67+
def stop():
68+
printer('SSH Proxy stopping...')
69+
pids = get_pids()
70+
if pids:
71+
for pid in pids:
72+
os.kill(int(pid), signal.SIGTERM)
73+
74+
if get_pids():
75+
printer('Error: Unable to stop SSH Proxy. Please try again')
76+
77+
def restart():
78+
stop()
79+
start()
80+
pass
81+
82+
def status():
83+
if get_pids():
84+
printer('SSH Proxy is currently connected, via %s' % host)
85+
else:
86+
printer('SSH Proxy is not connected')
87+
pass
88+
89+
90+
try:
91+
if len(sys.argv) == 2:
92+
command = run_command(sys.argv[1])
93+
else:
94+
command = run_command('--help')
95+
except KeyboardInterrupt:
96+
print('')
97+
exit(1)

0 commit comments

Comments
 (0)