Python3.X在尝试读取文件时拉取了过多的ip地址

Python3.X在尝试读取文件时拉取了过多的ip地址,python,python-3.x,nmap,Python,Python 3.x,Nmap,我有一份来自Nmap的扫描报告。我正在尝试获取仅与特定IP地址相关的信息。我正在尝试提取这部分代码的IP地址,稍后我将处理下一部分。我认为这与IP地址末尾的\n字符有关。我需要的代码说,我想要这个IP地址和这个IP地址单独。非常感谢您的帮助 #Python3.X target_ip = "10.10.100.1" fhand = open('ScanTest.txt','r') for line in fhand: line = line.rstrip() if line.

我有一份来自Nmap的扫描报告。我正在尝试获取仅与特定IP地址相关的信息。我正在尝试提取这部分代码的IP地址,稍后我将处理下一部分。我认为这与IP地址末尾的
\n
字符有关。我需要的代码说,我想要这个IP地址和这个IP地址单独。非常感谢您的帮助

#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)
我的结果是

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

我想你需要改变路线

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

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

您的代码匹配太多,因为非空字符串总是
True
,所以您的代码打印了所有以
“Nmap…”
开头的行

如何在
之后正确编写测试?您使用了字符串方法
startswith
,但也有
endswith

我还自由地将常量从循环中移出

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)

从您发布的输出判断,
startswith
endswith
表示该行正好等于
“10.10.100.1的Nmap扫描报告”

计算文件中存在的固定行数可能更有趣(下面是计算匹配数的惯用Python,因为不匹配的算术值是
0
,匹配的算术值是
1

或者在文件中也有这个位置也很有趣

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

[python-3.x]和[nmap]标记都是多余的。
 count = 0
 for n, line in enumerate(fhand):
     if line==target_line:
         print("%8d %s"%(n, line))
         count = count+1
 print(n, "matches found.")