[Tutor] Search text file, perform action if a given item
found in file
Kent Johnson
kent_johnson at skillsoft.com
Thu Sep 9 14:24:21 CEST 2004
Eric,
First, I suggest you read the output of popen directly, you don't have to
pipe it to a temp file. If you read it by lines, then you can process each
line looking for the data you want.
For example:
>>> import os
>>> o=os.popen('netstat -an')
>>> for l in o:
... print l,
...
Active Connections
Proto Local Address Foreign Address State
TCP 0.0.0.0:25 0.0.0.0:0 LISTENING
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING
TCP 0.0.0.0:445 0.0.0.0:0 LISTENING
TCP 0.0.0.0:1052 0.0.0.0:0 LISTENING
etc...
>>> o.close()
Next you probably want to split() the line to divide it into fields. Then
you can look at the specific fields. You might be able to use endswith() or
find() to search for the port; in my example endswith(':25') for example
would find the line with port 25. The details depend on what your data
looks like.
Give this a try and let us know how far you get. Also it would be helpful
to see an example of the output of netstat on your computer, it is
different on Windows and MacOSX.
Kent
At 04:59 AM 9/9/2004 -0400, Eric wrote:
>Eric wrote:
>
>>This is my first project that I am starting to work on, and what I want
>>to create is a program
>>that will alert me by sounding the system bell (beep) when a connection is
>>established to a selected TCP, or UDP port. It may not be the most
>>usefull thing, but the
>>learning experience is what I'm after with all
>>_______________________________________________
>>Tutor maillist - Tutor at python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
>
>Sent that email on accident without completing it..
>
>
>Anyway so far I have come up with this..
>
>
>
>import os
>
>PORT = int(raw_input("What tcp/udp should I watch for?: "))
>
>os.popen('netstat -an>log.txt')
>
>LogFile = file('log.txt', 'r')
>logcontents = LogFile.read()
>inFile.close()
>print logcontents
>
>
>
>
>So far so good. The "print logcontents" will print the output from the
>netstat command. My question is this.
>I'm trying to figure out a way to search "logcontents" for the "PORT"
>variable then perfrom a action if it finds
>a match.
>
>Thanks
>
>_______________________________________________
>Tutor maillist - Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list