Python 3.3.5
Debian 3.12
One thing I found weird is using the-the following code is, the input I entered isn ' t displayed, even after I terminate th E script. However I found a-accidently which is to set stdin as Devnull.
1 Try:2stdout = Subprocess.check_output (["Airodump-ng","Mon0"], stdin=subprocess. Devnull, timeout = 5)3 #stdout = Subprocess.check_output (["Sleep", "ten"], timeout = self.timeout)4 exceptsubprocess. Timeoutexpired:5 Pass6 7A = input ("Test a test")
In order to figure it out, first I looked into the code of Subprocess.check_output, in which I found it handles the Timeou Texpired exception by using Kill. As shown below:
1With Popen (*popenargs, stdout=pipe, * *Kwargs) as process:2 Try:3Output, Unused_err = Process.communicate (Inputdata, timeout=Timeout)4 excepttimeoutexpired:5 Process.kill ()6Output, Unused_err =process.communicate ()7 RaiseTimeoutexpired (Process.args, timeout, output=output)8 except:9 Process.kill ()Ten process.wait () One Raise ARetcode =Process.poll () - ifRetcode: - RaiseCalledprocesserror (Retcode, Process.args, Output=output)
And the Kill method would send SIGKILL to the process, and this signal goes straight to the kernal without notifying this p Rocess, which means the process never gets the opportunity to catch the signal and act on it. As for SIGTERM, the application can determine about it wants to does once a SIGTERM is received. While the most applications would clean up their resources and stop.
While executing in Airodump-ng, it first modifies the attributes of terminal to disable the display of the input using Mygetch function. Then it read input from stdin using GetChar, as long as there is no input, the thread running Mygetch is blocked, which re Sults in the modified attributes of terminal (does not echo chars of input).
1 intMygetch () {2 structTermios Oldt,3 Newt;4 intch;5Tcgetattr (Stdin_fileno, &Oldt);6Newt =Oldt;7Newt.c_lflag &= ~ (Icanon |ECHO);8Tcsetattr (Stdin_fileno, Tcsanow, &newt);9CH =GetChar ();TenTcsetattr (Stdin_fileno, Tcsanow, &Oldt); One returnch; A}
Therefore if we set stdin as Devnull, the GetChar function could return immediately, it won ' t cause any problems.
Remember the signals I mentioned above? SIGTERM and SIGKILL, when I walked through the source code of Airodump-ng, I found there are a handler for SIGTERM, as show N below:
1 if (Signum = SIGINT | | Signum ==< Span style= "color: #000000;" > SIGTERM) 2 { 3 Reset_term (); 4 alarm (1 5 g.do_exit = 1; 6 signal (SIGALRM, sighandler); 7 dprintf (Stdout_fileno, \n ); 8 }
Reset_term () would restore the modified terminal attributes through Tcsetattr () function.
So there comes another solution, we can send SIGTERM to make the application restore attributes of the terminal.
1 p = subprocess. Popen (["airodump-ng""mon0"])2try :3 p.wait (timeout = 5)4except subprocess. Timeoutexpired:5 p.terminate ()
Solutions to terminal problems encountered and using Python to execute "airodump-ng"