Get the output of cmd in real time using Python

Reprinted from: http://www.ifindbug.com/doc/id-44974/name-Get the output of cmd in real time using Python.html


Recently, I found a problem. The console program written by a guy is not robust enough. When monitoring SOCKET, it is easy to crash, causing the program to crash as a whole. Unfortunately, he has not found a solution to the problem and has been unable to solve it, but this is another monitoring program. It is still more important, and we must find a way to solve it.

(This is going to kill my rhythm....) Since I don't know the language he uses, I can only think of ways outside the program.

 

Environment description:

1. When the target program is executed, it will monitor port 8080, TCP, and output the client's IP address through the console after each client connection.

2. The monitoring is not done at one time, but is always monitored, and the program will not exit

3. In order to monitor the needs, it is best to sort and organize the connected IPs.

The PS system is based on the windows platform.

 

I thought of doing a monitoring program, it is better to be simple, so I thought of Python.

My expected logic is as follows. Use python to detect whether the target program has crashed. If the bid is won, the target program will be started and monitored. After each output, python will perform a data operation and then loop.

The first step is to solve the problem of capturing the output.

copy code
# this method is used for monitoring

import time
import subprocess
import locale
import codecs

mylist = []
ps = subprocess.Popen('netstat -a', stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
while True:
    data = ps.stdout.readline()
    if data == b'':
        if ps.poll() is not None:
            break
    else:
        mylist.append(data.decode(codecs.lookup(locale.getpreferredencoding()).name))
        newlist = []
        for i in mylist:
            if i.find('192.168') > 0:
                newlist.append(i)
        newlist.sort()
        print('Sum of requests from LAN:', len(newlist))
copy code

 

I used netstat -a to replace the program that needs continuous output, execute the program, and found that the program is different from what I imagined. It is indeed real-time to obtain data, but it always feels a little discordant, no matter, continue.

The second step is to solve the problem of the monitoring program

The program may still be dead, and a very critical point is to monitor the port, so just check the port. Three ways:

1. Find the API for port detection

2. Connect to the target port once, and it will be alive if it is connected

3. netstat

The first method needs to find out if there is any related API, the second method is easy to cause problems to the normal operation of the target program, and the third method is used without even thinking about it. Here you need to use the redirection function of cmd

copy code
# this method is used for monitoring

import time
import subprocess
import locale
import codecs


def getstdout(p):
    mylist = []
    while True:
        data = p.stdout.readline()
        if data == b'':
            if p.poll() is not None:
                break
        else:
            mylist.append(data.decode(codecs.lookup(locale.getpreferredencoding()).name))
    return mylist

while True:
    ps = subprocess.Popen('netstat -an | findstr "8080"', stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
    resultlist = getstdout(ps)
    if len(resultlist) >= 1:
        pass
    else:
        print(time.strftime("%Y-%m-%d %H:%M:%S"))
        subprocess.Popen( ' taskkill.exe /f /im node.exe ' , shell= False) 
     # Prevent the action from moving too fast and kill the newly created program time.sleep(
3) subprocess.Popen('start node D:\\app.js', shell=True) time.sleep(10)
copy code

netstat -an gets the current port listening status, "|" redirects the output of netstat to the findstr function

netstat -an | findstr "8080" Find the address line with port 8080, if there is, it means it is alive, otherwise it is hung up.


Related: Get the output of cmd in real time using Python