3838*Warning* - Note that commands, with or without a shell, are actually run on the system running this server. Destructive commands will affect the system as permissions of user running the server allow. **Use at your own risk**.
3939"""
4040
41+ from gipc import start_process
42+ from multiprocessing import Process
4143import sys
4244if 'threading' in sys .modules :
4345 del sys .modules ['threading' ]
4446from gevent import monkey
4547monkey .patch_all ()
46- from multiprocessing import Process
4748import os
4849import gevent
4950from gevent import socket
5354import logging
5455import paramiko
5556import time
57+ import gevent .subprocess
58+ import gevent .hub
59+
5660from .stub_sftp import StubSFTPServer
5761from .tunnel import Tunneler
58- import gevent .subprocess
5962
6063logger = logging .getLogger ("embedded_server" )
6164paramiko_logger = logging .getLogger ('paramiko.transport' )
@@ -86,16 +89,16 @@ def __init__(self, host_key, fail_auth=False,
8689 ssh_exception = False ,
8790 socket = None ,
8891 port = 0 ,
89- listen_ip = '127.0.0.1' ,
92+ host = '127.0.0.1' ,
9093 timeout = None ):
9194 if not socket :
92- self .socket = make_socket (listen_ip , port )
95+ self .socket = make_socket (host , port )
9396 if not self .socket :
9497 msg = "Could not establish listening connection on %s:%s"
95- logger .error (msg , listen_ip , port )
96- raise Exception (msg , listen_ip , port )
97- self .listen_ip = listen_ip
98- self .listen_port = self .socket .getsockname ()[1 ]
98+ logger .error (msg , host , port )
99+ raise Exception (msg , host , port )
100+ self .host = host
101+ self .port = self .socket .getsockname ()[1 ]
99102 self .event = Event ()
100103 self .fail_auth = fail_auth
101104 self .ssh_exception = ssh_exception
@@ -105,15 +108,20 @@ def __init__(self, host_key, fail_auth=False,
105108
106109 def start_listening (self ):
107110 try :
111+ gevent .sleep (0 )
108112 self .socket .listen (100 )
109- logger .info ('Listening for connection on %s:%s..' , self .listen_ip ,
110- self .listen_port )
113+ logger .info ('Listening for connection on %s:%s..' , self .host ,
114+ self .port )
111115 except Exception as e :
112116 logger .error ('*** Listen failed: %s' % (str (e ),))
113117 traceback .print_exc ()
114118 raise
119+ gevent .sleep ()
115120 conn , addr = self .socket .accept ()
121+ gevent .sleep (.2 )
116122 logger .info ('Got connection..' )
123+ # import ipdb; ipdb.set_trace()
124+ gevent .sleep (.2 )
117125 if self .timeout :
118126 logger .debug ("SSH server sleeping for %s then raising socket.timeout" ,
119127 self .timeout )
@@ -123,21 +131,26 @@ def start_listening(self):
123131 self .transport .add_server_key (self .host_key )
124132 self .transport .set_subsystem_handler ('sftp' , paramiko .SFTPServer ,
125133 StubSFTPServer )
134+ gevent .sleep ()
126135 try :
127136 self .transport .start_server (server = self )
128137 except paramiko .SSHException as e :
129138 logger .exception ('SSH negotiation failed' )
130139 raise
140+ gevent .sleep (0 )
131141
132142 def run (self ):
133143 while True :
134144 try :
135145 self .start_listening ()
146+ gevent .sleep (0 )
136147 except Exception :
137148 logger .exception ("Error occured starting server" )
138149 continue
150+ gevent .sleep (0 )
139151 try :
140152 self .accept_connections ()
153+ gevent .sleep (0 )
141154 except Exception as e :
142155 logger .error ('*** Caught exception: %s: %s' % (str (e .__class__ ), str (e ),))
143156 traceback .print_exc ()
@@ -152,8 +165,10 @@ def accept_connections(self):
152165 gevent .sleep (0 )
153166 channel = self .transport .accept (20 )
154167 if not channel :
155- logger .error ("Could not establish channel" )
156- return
168+ logger .error ("Could not establish channel on %s:%s" ,
169+ self .host , self .port )
170+ gevent .sleep (0 )
171+ continue
157172 while self .transport .is_active ():
158173 logger .debug ("Transport active, waiting.." )
159174 gevent .sleep (1 )
@@ -190,21 +205,28 @@ def check_channel_pty_request(self, channel, term, width, height, pixelwidth,
190205 return True
191206
192207 def check_channel_direct_tcpip_request (self , chanid , origin , destination ):
208+ # import ipdb; ipdb.set_trace()
193209 logger .debug ("Proxy connection %s -> %s requested" , origin , destination ,)
194210 extra = {'username' : self .transport .get_username ()}
195211 logger .debug ("Starting proxy connection %s -> %s" ,
196212 origin , destination , extra = extra )
213+ self .event .set ()
197214 try :
198- tunnel = Tunneler (destination , self .transport , chanid )
215+ gevent .sleep (.2 )
216+ tunnel = Process (target = Tunneler , args = (destination , self .transport , chanid ,))
217+ tunnel .daemon = True
199218 tunnel .start ()
219+ gevent .sleep (.2 )
200220 except Exception as ex :
201221 logger .error ("Error creating proxy connection to %s - %s" ,
202222 destination , ex ,)
203223 return paramiko .OPEN_FAILED_CONNECT_FAILED
224+ gevent .sleep (2 )
204225 return paramiko .OPEN_SUCCEEDED
205226
206227 def check_channel_forward_agent_request (self , channel ):
207228 logger .debug ("Forward agent key request for channel %s" % (channel ,))
229+ gevent .sleep (0 )
208230 return True
209231
210232 def check_channel_exec_request (self , channel , cmd ,
@@ -217,6 +239,7 @@ def check_channel_exec_request(self, channel, cmd,
217239 stdin = gevent .subprocess .PIPE ,
218240 shell = True , env = _env )
219241 gevent .spawn (self ._read_response , channel , process )
242+ gevent .sleep (0 )
220243 return True
221244
222245 def _read_response (self , channel , process ):
@@ -230,6 +253,7 @@ def _read_response(self, channel, process):
230253 # Let clients consume output from channel before closing
231254 gevent .sleep (.1 )
232255 channel .close ()
256+ gevent .sleep (0 )
233257
234258def make_socket (listen_ip , port = 0 ):
235259 """Make socket on given address and available port chosen by OS"""
@@ -246,21 +270,33 @@ def make_socket(listen_ip, port=0):
246270def start_server (listen_ip , fail_auth = False , ssh_exception = False ,
247271 timeout = None ,
248272 listen_port = 0 ):
249- server = Server (host_key , listen_ip = listen_ip , port = listen_port ,
273+ # gevent.reinit()
274+ gevent .hub .reinit ()
275+ # h.destroy(destroy_loop=True)
276+ # h = gevent.hub.Hub()
277+ # h.NOT_ERROR = (Exception,)
278+ # gevent.hub.set_hub(h)
279+ server = Server (host_key , host = listen_ip , port = listen_port ,
250280 fail_auth = fail_auth , ssh_exception = ssh_exception ,
251281 timeout = timeout )
252282 try :
253283 server .run ()
254284 except KeyboardInterrupt :
255285 sys .exit (0 )
286+ # listen_process = Process(target=server.run)
287+ # listen_process.start()
288+ # listen_process.join()
256289
257290def start_server_process (listen_ip , fail_auth = False , ssh_exception = False ,
258291 timeout = None , listen_port = 0 ):
292+ gevent .reinit ()
259293 server = Process (target = start_server , args = (listen_ip ,),
260294 kwargs = {
261295 'listen_port' : listen_port ,
262296 'fail_auth' : fail_auth ,
263297 'ssh_exception' : ssh_exception ,
264298 'timeout' : timeout ,
265299 })
300+ server .start ()
301+ gevent .sleep (.2 )
266302 return server
0 commit comments