0

I am writing a python Script to view "netstat" command output periodically and save it to a file. In case any port changes are there between different outputs of netstat.Print those lines to another file and save.

Sample output of netstat command:

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 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

my script is like this: I am able to print the netstat command periodical to a file.

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

Krishna
  • 45
  • 2
  • 6
  • 4
    What have you tried? This site is to ask for help. You might be looking for a site like freelancer.com – iLoveTux Oct 09 '15 at 10:42

1 Answers1

0

I am not sure what different outputs of netstat mean in your question. 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:

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

out_line will be a list with each line of netstat output as an entry in the list. Now you can loop over this out_list. Each iteration will process one line of the netstat output



    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

Sharad
  • 1,867
  • 14
  • 33