-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathssh_proxy.py
More file actions
97 lines (70 loc) · 1.93 KB
/
ssh_proxy.py
File metadata and controls
97 lines (70 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# -*- coding:utf-8 -*-
import os
class SshProxyServer():
'''
A simple ssh proxy server.
'''
def __init__(self, **kwargs):
self.local_addr = kwargs['local_addr']
self.local_port = kwargs['local_port']
self.remote_host = kwargs['host']
self.remote_port = kwargs['remote_port']
self.remote_user = kwargs['user']
self.childpid = 0
def getArgs(self):
'''
return the ssh cmd arguments as a string.
'''
return ('ssh', '-TfN', '-D %d' % self.local_port,
'-p %d' % self.remote_port,
'%s@%s' % (self.remote_user, self.remote_host))
def daemond(self):
'''
make current process to become daemond.
'''
pid = os.fork()
if pid == -1 or pid > 0:
exit(0)
else:
os.setsid()
def spawnChild(self):
'''
create a new child process when child process exit.
'''
npid = os.fork()
if npid == -1:
exit(0)
elif npid == 0:
#new child process
self.start()
else:
#parent process
self.childpid = npid
def start(self):
'''
run the real command in the child process.
'''
os.execvp('ssh', self.getArgs())
def run(self):
'''
start running ssh proxy server.
'''
self.daemond()
self.spawnChild()
while True:
wpid, status = os.waitpid(self.childpid, 0)
if wpid == self.childpid and os.WIFEXITED(status):
# child process exit
self.spawnChild()
def main():
settings = {
'local_addr': '',
'local_port': 8888,
'remote_port': 22122,
'user': 'justdoit',
'host': 'shareyou.net.cn'
}
s = SshProxyServer(**settings)
s.run()
if __name__ == '__main__':
main()