简体   繁体   English

Python脚本定期查看“ netstat”命令并在不同输出中打印任何更改?

[英]Python Script to view “netstat” command periodically and print any changes in different outputs?

I am writing a python Script to view "netstat" command output periodically and save it to a file. 我正在编写一个Python脚本来定期查看“ netstat”命令的输出并将其保存到文件中。 In case any port changes are there between different outputs of netstat.Print those lines to another file and save. 如果netstat的不同输出之间存在端口更改,请将这些行打印到另一个文件并保存。

Sample output of netstat command: netstat命令的样本输出:

tcp 0 77 100.73.96.7:56855 31.13.79.246:https LISTEN tcp 0 77 100.73.96.7:56855 31.13.79.246:https LISTEN
tcp 0 32 100.73.96.7:46551 68.232.44.121:https LISTEN tcp 0 32 100.73.96.7:46551 68.232.44.121:https监听

tcp 0 1 100.73.96.7:60538 198.252.206.16:http LISTEN tcp 0 1 100.73.96.7:60538 198.252.206.16:http LISTEN
tcp 0 77 100.73.96.7:51728 103.31.6.32:https LISTEN tcp 0 77 100.73.96.7:51728 103.31.6.32:https LISTEN

my script is like this : I am able to print the netstat command periodical to a file. 我的脚本是这样的 :我能够将netstat命令定期打印到文件中。

import subprocess
import time,threading

def myfun():
    p = subprocess.Popen(["netstat", "-at"], stdout=subprocess.PIPE)
    out = p.stdout.read()
    print out
    myfile = open("myfile","a")
    myfile.write(out)
    myfile.close()
    print(time.ctime())
    threading.Timer(10,myfun).start()
myfun()

How to proceed further. 如何进一步进行。 Anybody help 任何人的帮助

I am not sure what different outputs of netstat mean in your question. 我不确定netstat的不同输出在您的问题中意味着什么。 It may mean different output in each run or different output across periodic runs. 这可能意味着每次运行中会有不同的输出,或者周期运行中可能会有不同的输出。 Whatever it is you can modify as per requirement. 无论是什么,您都可以根据要求进行修改。

First step would be to split the output line by line and then word by word. 第一步是逐行分割输出,然后逐字分割。 Use Python Split Method: 使用Python分割方法:

`out_line = out.split("\n")`

out_line will be a list with each line of netstat output as an entry in the list. out_line将是一个列表,其中netstat输出的每一行都作为列表中的一个条目。 Now you can loop over this out_list. 现在,您可以遍历此out_list。 Each iteration will process one line of the netstat output 每次迭代将处理netstat输出的一行



    for line in out_line:
        line_list = line.split()
        WRITE YOUR PROGRAM HERE

After splitting each line to words, you may choose to store them as list of lists such that the inner list contain words and each complete inner list makes up a line. 将每一行拆分为单词后,您可以选择将它们存储为列表列表,以使内部列表包含单词,并且每个完整的内部列表组成一行。 Something like this: 像这样:

[
    [tcp, 0, 77, 100.73.96.7:56855, 31.13.79.246:https, LISTEN],
    [tcp, 0, 32, 100.73.96.7:46551, 68.232.44.121:https, LISTEN]
    ]

compare the index which refers to the port number and write to another file if they are different. 比较引用端口号的索引,如果不同则写入另一个文件。 I believe that part is trivial 我相信那部分是微不足道的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM