Use Python to get cmd output in real time, and python to get cmd in real time

Source: Internet
Author: User

Use Python to get cmd output in real time, and python to get cmd in real time

A problem was found recently. The console program written by a hacker was not robust enough to easily collapse when listening to the SOCKET. As a result, the entire program crashed, but he did not find a solution to the problem, it cannot be solved all the time, but this is a monitoring program, it is still important, and you must find a solution.

(This is the pace of getting rid of me...) because I am not familiar with the language he uses, I can only find a way out of the program.

 

Environment Description:

1. When the target program is executed, it listens to port 8080 and TCP, and outputs the IP address of the client through the console after each client connection.

2. The Listener is not completed at a time, but is always listened and the program will not exit

3. For monitoring purposes, it is best to sort and sort the connected IP addresses.

The P.S. system is based on the windows platform.

 

It was easier to think of a monitoring program, so I thought of Python.

I expected the logic to be as follows: Check whether the target program has crashed through python. If the target program is successfully won the bid, start the target program and perform monitoring. After each output, python performs a data operation and sorting, then loop.

Step 1: first solve the output capture problem.
# this method is used for monitoringimport timeimport subprocessimport localeimport codecsmylist = []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))

 

I used netstat-a to replace the program that requires continuous output, run the program, and find that the program is not the same as imagined. It is indeed real-time data acquisition, but it is always a bit out of harmony, no, continue.

Step 2: solve the problem of monitoring programs

The program is still dead. The key is listening to the port. You only need to check the port. Three methods:

1. Find the port detection API

2. connect to the target port once. If yes, the port is active.

3. netstat

The first method needs to look for relevant APIs. The second method is easy to cause problems to the normal operation of the Target Program. The third method can be used without thinking about it. Here we need to use the cmd redirection function.

# This method is used for monitoringimport timeimport subprocessimport localeimport codecsdef 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 mylistwhile 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 getting too fast and killing the new program. sleep (3) subprocess. popen ('start node D: \ app. js', shell = True) time. sleep (10)

Netstat-an gets the current port listener. "|" redirects the netstat output to the findstr function.

Netstat-an | findstr "8080" searches for the address line with port 8080. If yes, it indicates that the row is alive. Otherwise, it means the row is suspended.

 

The last step is integration.
# this method is used for monitoringimport timeimport subprocessimport localeimport codecsdef 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 mylistwhile 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)        time.sleep(3)        pss = subprocess.Popen('start cmd.exe /k node app.js', stdin=subprocess.PIPE,                               stdout=subprocess.PIPE, shell=True)        alist = getstdout(pss)        newlist = []        for i in alist:            if i.find('192.168') > 0:                newlist.append(i)        newlist.sort()        print('Sum of requests from LAN:', len(newlist))    time.sleep(10)

Then, if a problem occurs, the program will not detect it regularly, but will only be stuck on readline.

Various problems found that the process. stdout. readline () is a synchronization method, and no results are returned. Is there any Asynchronous Method?

Fnctl is used. windows does not support it. pass

Asyncio? I haven't seen it clearly for a long time...

After a long time, I used c # to solve the problem at the last moment ....

For more information about the reference code, see examples.

 

I finally solved this problem, but I still feel uncomfortable. I have been thinking about how to solve the problem of asynchronous readline () for a long time. Suddenly I think of multithreading as a powerful tool. I just need to open a thread and wait without returning it. The problem will not be solved.

# This method is used for monitoringimport timeimport subprocessimport localeimport codecsimport threadingalist = [] def getstdout (p, asy): if asy: alist. clear () mylist = [] while True: data = p. stdout. readline () if data = B '': if p. poll () is not None: break else: if asy: alist. append (data. decode (codecs. lookup (locale. getpreferredencoding ()). name) else: mylist. append (data. decode (codecs. lookup (locale. getpreferredencoding ()). name) return mylistwhile True: ps = subprocess. popen ('netstat-an | findstr "8080" ', stdin = subprocess. PIPE, stdout = subprocess. PIPE, shell = True) resultlist = getstdout (ps, False) if len (resultlist)> = 1: newlist = [] for I in alist: if I. find ('2017. 168 ')> 0: newlist. append (I) newlist. sort () print ('sum of requests from LAN: ', len (newlist) else: print (time. strftime ("% Y-% m-% d % H: % M: % S") subprocess.Popen('taskkill.exe/f/im node.exe ', shell = False) time. sleep (3) pss = subprocess. popen ('start cmd.exe/k node app. js', stdin = subprocess. PIPE, stdout = subprocess. PIPE, shell = True) th = threading. thread (target = getstdout, args = [pss, True]) th. start () time. sleep (10)View Code

 

Summary

Sometimes a simple solution can implement the same function. Compared with the implementation of python and C #, C # Is More event-oriented and python should have a good solution, continue to explore...

P.S. note that the cmd output is a string of the B ''type in the UNICODE system. codecs is recommended for transcoding that is not clear about the default encoding of your system. lookup (locale. getpreferredencoding ()). name, rashly using UTF-8.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.