Python 3.X在尝试读取文件时提取了太多的IP地址

马特

我有Nmap的扫描报告。我正在尝试获取仅与特定IP地址有关的信息。我正在尝试为该部分代码提取IP地址,稍后将在下一部分中使用。我认为这与\nIP地址末尾字符有关。我需要代码说我只想要这个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
博菲

您的代码匹配太多,因为总是有一个非空的字符串True,因此您的代码打印了所有"Nmap..."

之后如何正确编写测试and您使用了string方法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)

从您发布的输出来看,startswithendswith暗示该行完全等于"Nmap scan report for 10.10.100.1“ ...”。

这可能是更有趣多少固定线路都出现在文件中(接踵而来的是地道的Python来计算匹配的数量,它的工作原理,因为不匹配的算术值0和匹配的是1

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Python3 Argparse尝试读取文件并计算字母

尝试打开文件以在Python 3中读取时获取FileNotFoundError

python3:从编译模式中提取IP地址

尝试读取使用Python数组模块创建的数据文件时出现问题

python pandas:尝试读取txt文件,但显示为NaN

Python尝试读取json文件并打印特定信息

在python 3中解析日志文件中的IP地址

Python(3.x)-读取文件时打开文件并删除引号

从Python 3.x的列表中提取IP和端口

尝试使用 makedirs python 3 复制文件时出现 FileExistsError

在Python 3中逐行读取文件时捕获UnicodeDecodeError异常

Python 3-从动态网页提取IP地址和端口号

IP地址字符串提取在Python3中不起作用

python 3 import导入太多

为什么在尝试读取不存在的s3键时出现不同的错误

尝试读取与 python 文件位于同一目录中的文件但收到 FileNotFoundError

我在尝试读取本地JSON文件的python文件中收到MissingSchema错误

尝试使用Python 3解析XML文件

Python 3.x Tkinter串行读取

使用Python 3读取JSON文件

python3:从url读取json文件

使用Python 3读取CSV文件

python 3 - 读取和写入在线文件

在python3中读取txt文件

我正在尝试读取文本文件并将其转换为字典列表 Python

无法在 Python 3 中从 S3 读取 PNG 文件?

尝试在Anaconda上安装pygame时将Python 3.x降级为Python 2.7

Python 3,按顺序获取IP地址和Ping的文本文件

Python - 从导入的文件中读取时循环打印太多次