def list (self): if self.ppds: return self.ppds signal.alarm (60) p = subprocess.Popen ([self.exe, "list"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: (stdout, stderr) = p.communicate () signal.alarm (0) except TimedOut: posix.kill (p.pid, signal.SIGKILL) raise if stderr: print(stderr, file=sys.stderr) ppds = [] lines = stdout.split ('\n') for line in lines: l = shlex.split (line) if len (l) < 1: continue ppds.append (l[0]) self.ppds = ppds return ppds
def test_set_wakeup_fd(self): import signal, posix, fcntl def myhandler(signum, frame): pass signal.signal(signal.SIGUSR1, myhandler) # def cannot_read(): try: posix.read(fd_read, 1) except OSError: pass else: raise AssertionError, "os.read(fd_read, 1) succeeded?" # fd_read, fd_write = posix.pipe() flags = fcntl.fcntl(fd_write, fcntl.F_GETFL, 0) flags = flags | posix.O_NONBLOCK fcntl.fcntl(fd_write, fcntl.F_SETFL, flags) flags = fcntl.fcntl(fd_read, fcntl.F_GETFL, 0) flags = flags | posix.O_NONBLOCK fcntl.fcntl(fd_read, fcntl.F_SETFL, flags) # old_wakeup = signal.set_wakeup_fd(fd_write) try: cannot_read() posix.kill(posix.getpid(), signal.SIGUSR1) res = posix.read(fd_read, 1) assert res == '\x00' cannot_read() finally: old_wakeup = signal.set_wakeup_fd(old_wakeup) # signal.signal(signal.SIGUSR1, signal.SIG_DFL)
def __init__(self, manager, pid, record, old_debugger=None, is_thread=False): """ Create a new tracing thread :param manager: overall tracing management instance :param pid: Process to trace :param record: Action recording instance :param old_debugger: Old debugger the process might be attached to at the moment :param is_thread: True if the pid is a thread else False """ super().__init__() self.manager = manager # Save tracing record self.record = record self.record.runtime_log(RuntimeActionRecord.TYPE_STARTED) self._debugger_options = FunctionCallOptions(replace_socketcall=False) self.is_thread = is_thread self.process = psutil.Process(pid) self.debugger = None self.traced_item = None self.stopped = False # Check if the process is attached to the debugger if old_debugger is not None and old_debugger.dict.get( self.process.pid): old_debugger.dict.get(self.process.pid).detach() posix.kill(self.process.pid, signal.SIGSTOP)
def kill (self, signal=9): import posix if self.running: posix.kill(self.pid, signal) return self.finish() else: return 0
def start(self): # Configure the tracing instance if not self.config: self.tracer.runtime_tracing = False self.tracer.file_access_tracing = False self.tracer.syscall_tracing = False else: self.tracer.runtime_tracing = self.config.get('enabled', False) file_access_tracing = self.config.get('file_access', 'none') if file_access_tracing != 'none': self.tracer.file_access_tracing = ( file_access_tracing == 'short') self.tracer.file_access_detailed_tracing = ( file_access_tracing == 'full') else: self.tracer.file_access_tracing = False syscall_tracing = self.config.get('syscall', 'none') if syscall_tracing != 'none': self.tracer.syscall_tracing = (syscall_tracing == 'short') self.tracer.syscall_argument_tracing = ( syscall_tracing == 'full') else: self.tracer.set_file_access_tracing_enabled = False # Start the tracing process (if tracing is requested) if self.tracer.runtime_tracing or self.tracer.file_access_tracing or self.tracer.syscall_tracing: self.tracer.start() else: posix.kill(self.process, signal.SIGCONT)
def list(self): if self.ppds: return self.ppds signal.alarm(60) p = subprocess.Popen([self.exe, "list"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: (stdout, stderr) = p.communicate() signal.alarm(0) except TimedOut: posix.kill(p.pid, signal.SIGKILL) raise if stderr: print >> sys.stderr, stderr ppds = [] lines = stdout.split('\n') for line in lines: l = shlex.split(line) if len(l) < 1: continue ppds.append(l[0]) self.ppds = ppds return ppds
def start(self): """ Start the process tracing :return: True if a new tracing action was executed or False if tracing is already running """ if self.is_running(): return False self._debugger_threads = {} self._process_records = {} # Spawn the debugger thread for the start process if self.process.status() != psutil.STATUS_STOPPED: posix.kill(self.process.pid, signal.SIGSTOP) self.trace_create_thread(self.process.pid) # Start debugger for all existing process children processes = [self.process] + self.process.children(recursive=True) for p in processes: # Don't double start tracing of a process if p.pid not in self._debugger_threads.keys(): self.trace_create_thread(p.pid) # Start tracing of process threads for t in p.threads(): if t.id not in self._debugger_threads.keys(): self.trace_create_thread(t.id, is_thread=True) # Mark running self._running = True return True
def ioloop1(s, otheraddr): # # Watch out! data is in bytes, but the port counts in samples, # which are two bytes each (for 16-bit samples). # Luckily, we use mono, else it would be worse (2 samples/frame...) # SAMPSPERBUF = 500 BYTESPERSAMP = 2 # AL.SAMPLE_16 BUFSIZE = BYTESPERSAMP * SAMPSPERBUF QSIZE = 4 * SAMPSPERBUF # config = al.newconfig() config.setqueuesize(QSIZE) config.setwidth(AL.SAMPLE_16) config.setchannels(AL.MONO) # pid = posix.fork() if pid: # Parent -- speaker/headphones handler log('parent started') spkr = al.openport('spkr', 'w', config) while 1: data = s.recv(BUFSIZE) if len(data) == 0: # EOF packet log('parent got empty packet; killing child') posix.kill(pid, 15) return # Discard whole packet if we are too much behind if spkr.getfillable() > len(data) / BYTESPERSAMP: if len(debug) >= 2: log('parent Q full; dropping packet') spkr.writesamps(data) else: # Child -- microphone handler log('child started') try: try: mike = al.openport('mike', 'r', config) # Sleep a while to let the other side get started time.sleep(1) # Drain the queue before starting to read data = mike.readsamps(mike.getfilled()) # Loop, sending packets from the mike to the net while 1: data = mike.readsamps(SAMPSPERBUF) s.sendto(data, otheraddr) except KeyboardInterrupt: log('child got interrupt; exiting') posix._exit(0) except error: log('child got error; exiting') posix._exit(1) finally: log('child got unexpected error; leaving w/ traceback')
def ioloop1(s, otheraddr): # # Watch out! data is in bytes, but the port counts in samples, # which are two bytes each (for 16-bit samples). # Luckily, we use mono, else it would be worse (2 samples/frame...) # SAMPSPERBUF = 500 BYTESPERSAMP = 2 # AL.SAMPLE_16 BUFSIZE = BYTESPERSAMP*SAMPSPERBUF QSIZE = 4*SAMPSPERBUF # config = al.newconfig() config.setqueuesize(QSIZE) config.setwidth(AL.SAMPLE_16) config.setchannels(AL.MONO) # pid = posix.fork() if pid: # Parent -- speaker/headphones handler log('parent started') spkr = al.openport('spkr', 'w', config) while 1: data = s.recv(BUFSIZE) if len(data) == 0: # EOF packet log('parent got empty packet; killing child') posix.kill(pid, 15) return # Discard whole packet if we are too much behind if spkr.getfillable() > len(data) / BYTESPERSAMP: if len(debug) >= 2: log('parent Q full; dropping packet') spkr.writesamps(data) else: # Child -- microphone handler log('child started') try: try: mike = al.openport('mike', 'r', config) # Sleep a while to let the other side get started time.sleep(1) # Drain the queue before starting to read data = mike.readsamps(mike.getfilled()) # Loop, sending packets from the mike to the net while 1: data = mike.readsamps(SAMPSPERBUF) s.sendto(data, otheraddr) except KeyboardInterrupt: log('child got interrupt; exiting') posix._exit(0) except error: log('child got error; exiting') posix._exit(1) finally: log('child got unexpected error; leaving w/ traceback')
def stop(self): """Stops the slapd server, and waits for it to terminate""" if self._proc is not None: self._log.debug("stopping slapd") if hasattr(self._proc, 'terminate'): self._proc.terminate() else: import posix import signal posix.kill(self._proc.pid, signal.SIGTERM) self.wait()
def stop(self): """Stops the slapd server, and waits for it to terminate""" if self._proc is not None: self._log.debug("stopping slapd") if hasattr(self._proc, 'terminate'): self._proc.terminate() else: import posix, signal posix.kill(self._proc.pid, signal.SIGHUP) #time.sleep(1) #posix.kill(self._proc.pid, signal.SIGTERM) #posix.kill(self._proc.pid, signal.SIGKILL) self.wait()
def send_cancel(self, ev): if not self.running: return "break" #print "ctrl-c" #print ev.char, ev.keycode, ev.keysym posix.kill(self.pid, signal.SIGINT) #self.stdin.write(chr(3)) #self.stdin.write('\n') #self.stdin.flush() self.temphistory = self.history[:] self.temphistory.append("") self.currentline = "" self.historypos = 1 self.cursor_pos = 0 self.input_modified = False self.output_modified = False self.tab_pressed = False
def stop(self): """Stops the slapd server, and waits for it to terminate""" if self._proc is not None: self._log.debug("stopping slapd") if hasattr(self._proc, 'terminate'): self._proc.terminate() else: import posix import signal posix.kill(self._proc.pid, signal.SIGHUP) # time.sleep(1) # posix.kill(self._proc.pid, signal.SIGTERM) # posix.kill(self._proc.pid, signal.SIGKILL) self.wait() if self._tmpdir is not None: import shutil shutil.rmtree(self._tmpdir) self._tmpdir = None
def test_sigmask(self): import _signal as signal, posix signum1 = signal.SIGUSR1 signum2 = signal.SIGUSR2 def handler(signum, frame): pass signal.signal(signum1, handler) signal.signal(signum2, handler) signal.pthread_sigmask(signal.SIG_BLOCK, (signum1, signum2)) posix.kill(posix.getpid(), signum1) posix.kill(posix.getpid(), signum2) assert signal.sigpending() == set((signum1, signum2)) # Unblocking the 2 signals calls the C signal handler twice signal.pthread_sigmask(signal.SIG_UNBLOCK, (signum1, signum2)) assert signal.sigpending() == set()
def cat(self, name): try: return self.files[name] except KeyError: signal.alarm(10) p = subprocess.Popen([self.exe, "cat", name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: (stdout, stderr) = p.communicate() signal.alarm(0) except TimedOut: posix.kill(p.pid, signal.SIGKILL) raise if stderr: print >> sys.stderr, stderr self.files[name] = stdout return stdout
def cat (self, name): try: return self.files[name] except KeyError: signal.alarm (10) p = subprocess.Popen ([self.exe, "cat", name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: (stdout, stderr) = p.communicate () signal.alarm (0) except TimedOut: posix.kill (p.pid, signal.SIGKILL) raise if stderr: print(stderr, file=sys.stderr) self.files[name] = stdout return stdout
def test_set_wakeup_fd(self): try: import _signal as signal, posix, fcntl except ImportError: skip('cannot import posix or fcntl') def myhandler(signum, frame): pass signal.signal(signal.SIGINT, myhandler) # def cannot_read(): try: posix.read(fd_read, 1) except OSError: pass else: raise AssertionError("os.read(fd_read, 1) succeeded?") # fd_read, fd_write = posix.pipe() flags = fcntl.fcntl(fd_write, fcntl.F_GETFL, 0) flags = flags | posix.O_NONBLOCK fcntl.fcntl(fd_write, fcntl.F_SETFL, flags) flags = fcntl.fcntl(fd_read, fcntl.F_GETFL, 0) flags = flags | posix.O_NONBLOCK fcntl.fcntl(fd_read, fcntl.F_SETFL, flags) # old_wakeup = signal.set_wakeup_fd(fd_write) try: cannot_read() posix.kill(posix.getpid(), signal.SIGINT) res = posix.read(fd_read, 1) assert res == bytes([signal.SIGINT]) cannot_read() finally: old_wakeup = signal.set_wakeup_fd(old_wakeup) # signal.signal(signal.SIGINT, signal.SIG_DFL)
def test_usr1(self): import types, posix signal = self.signal # the signal module to test received = [] def myhandler(signum, frame): assert isinstance(frame, types.FrameType) received.append(signum) signal.signal(signal.SIGUSR1, myhandler) posix.kill(posix.getpid(), signal.SIGUSR1) # the signal should be delivered to the handler immediately assert received == [signal.SIGUSR1] del received[:] posix.kill(posix.getpid(), signal.SIGUSR1) # the signal should be delivered to the handler immediately assert received == [signal.SIGUSR1] del received[:] signal.signal(signal.SIGUSR1, signal.SIG_IGN) posix.kill(posix.getpid(), signal.SIGUSR1) for i in range(10000): # wait a bit - signal should not arrive if received: break assert received == [] signal.signal(signal.SIGUSR1, signal.SIG_DFL)
def operate(self, **kwargs): self.runningThreads += 1 r, w = os.pipe() pid = os.fork() if pid: # PARENT os.close(w) tmpParam = kwargs[self.parameter] r = os.fdopen(r, "rb") try: tmpResult = cPickle.load(r) except: try: posix.kill(pid, -1) # Kill the child except: pass if self.verbose: self.write("An error occured in job " + str(pid)) # Tell the reader self.jobs.append(kwargs[self.parameter]) # Append the job to be done later self.runningThreads -= 1 # Tell your master that you've one it self.sigPause.set() return os.waitpid(pid, 0) else: # CHILD posix.nice(self.nice) os.close(r) w = os.fdopen(w, "wb") cPickle.dump(self.function(**kwargs), w, 2) w.close() sys.exit(0) self.writeLock.acquire() self.operate_return(tmpParam, tmpResult) self.runningThreads -= 1 self.sigPause.set() self.writeLock.release()
def operate(self,**kwargs): self.runningThreads+=1 r, w = os.pipe() pid = os.fork() if pid: # PARENT os.close(w) tmpParam = kwargs[self.parameter] r = os.fdopen(r, 'rb') try: tmpResult = cPickle.load(r) except: try: posix.kill(pid, -1) # Kill the child except: pass if self.verbose: self.write("An error occured in job "+str(pid)) # Tell the reader self.jobs.append(kwargs[self.parameter]) # Append the job to be done later self.runningThreads -= 1 # Tell your master that you've one it self.sigPause.set() return os.waitpid(pid, 0) else: # CHILD posix.nice(self.nice) os.close(r) w = os.fdopen(w, 'wb') cPickle.dump(self.function(**kwargs), w, 2) w.close() sys.exit(0) self.writeLock.acquire() self.operate_return(tmpParam, tmpResult) self.runningThreads -= 1 self.sigPause.set() self.writeLock.release()
def run(self): """ Trace the given process or thread for one syscall """ finished = False self.record.log("Attaching debugger") try: self.debugger = PtraceDebugger() self.debugger.traceFork() self.debugger.traceExec() self.debugger.traceClone() self.traced_item = self.debugger.addProcess( self.process.pid, False, is_thread=self.is_thread) self.record.log("PTrace debugger attached successfully") TracingThread._trace_continue(self.traced_item) except Exception as e: self.record.log( "PTrace debugger attachment failed with reason: {}".format(e)) finished = True # Trace process until finished while not finished and not self.stopped: finished = self._trace(self.traced_item, self.record) if self.traced_item: self.traced_item.detach() # Keep in mind that the process maybe already gone try: if self.process.status() == psutil.STATUS_STOPPED: posix.kill(self.process.pid, signal.SIGCONT) except psutil.NoSuchProcess: pass self.record.log("Tracee appears to have ended and thread will finish")
# if pid == 0: # child -- read stdin, write socket while 1: line = sys.stdin.readline() s.send(line) else: # parent -- read socket, write stdout iac = 0 # Interpret next char as command opt = '' # Interpret next char as option while 1: data = s.recv(BUFSIZE) if not data: # EOF; kill child and exit sys.stderr.write( '(Closed by remote host)\n') posix.kill(pid, 9) sys.exit(1) cleandata = '' for c in data: if opt: print ord(c) s.send(opt + c) opt = '' elif iac: iac = 0 if c == IAC: cleandata = cleandata + c elif c in (DO, DONT): if c == DO: print '(DO)', else: print '(DONT)', opt = IAC + WONT
# intercom -- use mike and headset to *talk* to a person on another host.
def master_sig_handler_stop_server(signum, frame): print("Signal {} received, server will be stopped".format(signum)) posix.kill(0, signal.SIGINT) posix.wait() sys.exit(0)
def __init__(self, process, stop=False, recording_mode=TRACING_RECORD_MODE_MEMORY, log_filename=None, log_callback=None): """ Create a new tracing instance This will bind to the given process and enable process observation using the capabilities of ptrace :param process: psutil.Process instance or pid of the process to trace :param stop: Specify true to send SIGSTOP to the process to temporary halt it :param recording_mode: Mask to configure how recorded events should be saved :param log_filename: If the recording_mode contains TRACING_RECORD_MODE_FILE you must specify a filename where you want to write the log data to - writing to the file will be thread save :param log_callback: If the recording_mode contains TRACING_RECORD_MODE_CALLBACK you must specify a function to invoke for every log entry """ if type(process) == int: self.process = psutil.Process(process) elif type(process) == psutil.Process: self.process = process else: raise AttributeError( "The specified process needs to be a valid PID or psutil.Process instance" ) if stop: posix.kill(self.process.pid, signal.SIGSTOP) # Initialize debugger self._debugger_threads = None # Recorded process data self._process_records = None # Filters that may be used to trace only a subset of caught syscalls # If this parameters are valid iterables traced syscalls will be checked if they # are in the given filter list. If not they won't get recorded self.syscall_filter = None self.file_access_filter = [ "open", "stat", "lstat", "access", "connect", "chdir", "rename", "mkdir", "rmdir", "creat", "link", "unlink", "symlink", "readlink", "chmod", "chown", "lchown", "utime" "mknod", "statfs", "chroot", "pivot_root" ] self.syscall_filter_exclude = None self.file_access_filter_exclude = None # We start in Process runtime tracing mode only self._mode = TRACING_MODE_RUNTIME_TRACING self._running = False self._recording_mode = recording_mode self._log_filename = log_filename self._log_callback = log_callback if self._recording_mode & TRACING_RECORD_MODE_FILE and not self._log_filename: raise AttributeError( "File recording requested but no log file specified") if self._recording_mode & TRACING_RECORD_MODE_CALLBACK and not self._log_callback: raise AttributeError( "Callback invocation recording requested but no callback method specified" )
def main(): host = sys.argv[1] try: hostaddr = gethostbyname(host) except error: sys.stderr.write(sys.argv[1] + ': bad host name\n') sys.exit(2) # if len(sys.argv) > 2: servname = sys.argv[2] else: servname = 'telnet' # if '0' <= servname[:1] <= '9': port = eval(servname) else: try: port = getservbyname(servname, 'tcp') except error: sys.stderr.write(servname + ': bad tcp service name\n') sys.exit(2) # s = socket(AF_INET, SOCK_STREAM) # try: s.connect((host, port)) except error as msg: sys.stderr.write('connect failed: ' + repr(msg) + '\n') sys.exit(1) # pid = posix.fork() # if pid == 0: # child -- read stdin, write socket while 1: line = sys.stdin.readline() s.send(line) else: # parent -- read socket, write stdout iac = 0 # Interpret next char as command opt = '' # Interpret next char as option while 1: data = s.recv(BUFSIZE) if not data: # EOF; kill child and exit sys.stderr.write('(Closed by remote host)\n') posix.kill(pid, 9) sys.exit(1) cleandata = '' for c in data: if opt: print(ord(c)) s.send(opt + c) opt = '' elif iac: iac = 0 if c == IAC: cleandata = cleandata + c elif c in (DO, DONT): if c == DO: print('(DO)', end=' ') else: print('(DONT)', end=' ') opt = IAC + WONT elif c in (WILL, WONT): if c == WILL: print('(WILL)', end=' ') else: print('(WONT)', end=' ') opt = IAC + DONT else: print('(command)', ord(c)) elif c == IAC: iac = 1 print('(IAC)', end=' ') else: cleandata = cleandata + c sys.stdout.write(cleandata) sys.stdout.flush()
def main(): host = sys.argv[1] try: hostaddr = gethostbyname(host) except error: sys.stderr.write(sys.argv[1] + ': bad host name\n') sys.exit(2) # if len(sys.argv) > 2: servname = sys.argv[2] else: servname = 'telnet' # if '0' <= servname[:1] <= '9': port = eval(servname) else: try: port = getservbyname(servname, 'tcp') except error: sys.stderr.write(servname + ': bad tcp service name\n') sys.exit(2) # s = socket(AF_INET, SOCK_STREAM) # try: s.connect((host, port)) except error as msg: sys.stderr.write('connect failed: ' + repr(msg) + '\n') sys.exit(1) # pid = posix.fork() # if pid == 0: # child -- read stdin, write socket while 1: line = sys.stdin.readline() s.send(line) else: # parent -- read socket, write stdout iac = 0 # Interpret next char as command opt = '' # Interpret next char as option while 1: data = s.recv(BUFSIZE) if not data: # EOF; kill child and exit sys.stderr.write( '(Closed by remote host)\n') posix.kill(pid, 9) sys.exit(1) cleandata = '' for c in data: if opt: print(ord(c)) s.send(opt + c) opt = '' elif iac: iac = 0 if c == IAC: cleandata = cleandata + c elif c in (DO, DONT): if c == DO: print('(DO)', end=' ') else: print('(DONT)', end=' ') opt = IAC + WONT elif c in (WILL, WONT): if c == WILL: print('(WILL)', end=' ') else: print('(WONT)', end=' ') opt = IAC + DONT else: print('(command)', ord(c)) elif c == IAC: iac = 1 print('(IAC)', end=' ') else: cleandata = cleandata + c sys.stdout.write(cleandata) sys.stdout.flush()
def handle (self): # Init server data variable (for while()) server_input=client_input="DEADBEEF" # Get FD from listener client_fd=self.request # Open socket to serving machine and connect server_fd=socket(AF_INET,SOCK_STREAM) server_fd.connect (foreign_host,foreign_port) # Now, we fork and handle data in both directions CPID=fork() # Where are we? if (CPID<0): # oops, somehting went wrong print "Could not fork." return(0) if (CPID==0): # This is the child, get parent pid PPID=getppid() # infinite loop with break condition # XXX this is not elegant all while(1): # read 1024 bytes from FD server_input=server_fd.recv(1024) # if we couldn't read, back out if not server_input: break; # write data to client client_fd.send(server_input) # If we were disconnected, kill away the parent kill (PPID, SIGTERM); else: # This is the parent, child PID is CPID # infinite loop with break condition # XXX this is not elegant while (1): # Fetch signals and back out if kid is dead if (not waitpid(CPID,WNOHANG)): break; # Read from client FD client_input=client_fd.recv(1024) # Back out if we couldn't read anything if not client_input: break; # Write data to server server_fd.send(client_input) # Get rid of the kid kill (CPID, SIGTERM); # This actually should be a "can't happen", # but I am not sure # Close remaining FDs client_fd.close() server_fd.close()
def Method1(): global code user_id = getUserID(input('# Type your user login ID : ')) for entry in posix.listdir('/proc/'): if entry.isnumeric() == True: if posix.stat('/proc/' + entry).st_uid == user_id: code = 'Continue' break if code == 'Continue': print('# Any process belonged to typed user is found.') while True: option = input( '# Do you want to send signal to these processes for closing? (Y/N) : ' ) if option in ['Y', 'N']: break if option == 'N': code = 'Cancelled' return else: print('# Retriving processes list...') pids = [] for entry in posix.listdir('/proc/'): if entry.isnumeric() == True: if posix.stat('/proc/' + entry).st_uid == user_id: pids.append(int(entry)) print('# Quitting processes...') if posix.getuid() != user_id and posix.getuid() != 0: print( '# Error : Don\'t have enough permission. Make sure to run this troubleshooter as root.' ) code = 'RequiredRoot' return for pid in pids: posix.kill(pid, 15) input( 'Waiting for processes to be closed properly (Recommended at 20 seconds). When ready then press enter.' ) print('# Retriving processes list...') pids = [] for entry in posix.listdir('/proc/'): if entry.isnumeric() == True: if posix.stat('/proc/' + entry).st_uid == user_id: pids.append(int(entry)) if pids: while True: option = input( '# There are processes not quitted by the signal. Do you want to force killing it? (Y/N) : ' ) if option in ['Y', 'N']: break if option == 'N': code = 'Cancelled' return print('# Killing processes...') for pid in pids: posix.kill(pid, 9) code = 'Complete' return else: print('# No any process belonged to typed user is found.') code = 'NoSolution' return
if pid == 0: # child -- read stdin, write socket while 1: line = sys.stdin.readline() s.send(line) else: # parent -- read socket, write stdout iac = 0 # Interpret next char as command opt = '' # Interpret next char as option while 1: data = s.recv(BUFSIZE) if not data: # EOF; kill child and exit sys.stderr.write('(Closed by remote host)\n') posix.kill(pid, 9) sys.exit(1) cleandata = '' for c in data: if opt: print ord(c) s.send(opt + c) opt = '' elif iac: iac = 0 if c == IAC: cleandata = cleandata + c elif c in (DO, DONT): if c == DO: print '(DO)', else: print '(DONT)', opt = IAC + WONT
#! /usr/bin/env python # Minimal interface to the Internet telnet protocol. # # It refuses all telnet options and does not recognize any of the other # telnet commands, but can still be used to connect in line-by-line mode. # It's also useful to play with a number of other services, # like time, finger, smtp and even ftp. # # Usage: telnet host [port] # # The port may be a service name or a decimal port number; # it defaults to 'telnet'. import sys, posix, time from socket import * BUFSIZE = 1024 # Telnet protocol characters IAC = chr(255) # Interpret as command DONT = chr(254) DO = chr(253) WONT = chr(252) WILL = chr(251) def main(): host = sys.argv[1] try: hostaddr = gethostbyname(host) except error: sys.stderr.write(sys.argv[1] + ': bad host name\n') sys.exit(2) #