Matt
Matt

Reputation: 37

Python 3.X pulling too many ip addresses when trying to read file

I have a scan report from Nmap. I'm trying to get the information that only pertains to the certain IP address. I'm trying pull the IP address for this part of the code I will work on the next piece later. I think it has something to do with the \n character at the end of the IP address. I need the code to say I want this IP address and this IP address alone. Any help is greatly appreciated.

#Python3.X 
target_ip = "10.10.100.1"


fhand = open('ScanTest.txt','r')
for line in fhand:
    line = line.rstrip()
    if line.startswith('Nmap scan report for')and (target_ip):
        print(line)

My results end up being

Nmap scan report for 10.10.100.1
Nmap scan report for 10.10.100.2
Nmap scan report for 10.10.100.100
Nmap scan report for 10.10.100.101
Nmap scan report for 10.10.100.103
Nmap scan report for 10.10.100.102

Upvotes: 1

Views: 76

Answers (2)

gboffi
gboffi

Reputation: 25023

Your code matched too much because a non empty string is always True, so your code printed all the lines beginning with "Nmap...".

How can you write correctly the test after and ? You used the string method startswith, but there is also endswith...

I also took the liberty of moving the constant requested beginning out of the loop,

target_ip = "10.10.100.1"
begins = "Nmap scan report for"

fhand = open('ScanTest.txt','r')
for line in fhand:
    line = line.rstrip()
    if line.startswith(begins) and line.endswith(target_ip):
        print(line)

Judging from the output you have posted, the startswith and the endswith imply that the line is exactly equal to "Nmap scan report for 10.10.100.1"...

It could be more interesting to count how many fixed lines are present in the file (what follows is idiomatic Python to count the number of matches, it works because the arithmetic value of a non-match is 0 and of a match is 1)

 count = sum(line==target_line for line in fhand)

or maybe it's interesting to have also the position in the file

 count = 0
 for n, line in enumerate(fhand):
     if line==target_line:
         print("%8d %s"%(n, line))
         count = count+1
 print(n, "matches found.")

Upvotes: 1

Red Cricket
Red Cricket

Reputation: 10460

I think you need to change the line …

if line.startswith('Nmap scan report for')and (target_ip):

… to …

if line.startswith('Nmap scan report for') and (line.split(' ')[4] == target_ip):

Upvotes: 0

Related Questions