让我们看看如何使用 python 从文件中提取 ip 地址。
算法 :
- 为正则表达式导入 re 模块。
- 使用 open() 函数打开文件。
- 读取文件中的所有行并将它们存储在列表中。
- 声明 ip 地址的模式。正则表达式模式是:
r'(d{1,3}.d{1,3}.d{1,3}.d{1,3})'
- 对于列表中的每个元素,使用 search() 函数搜索模式,将 ip 地址存储在列表中。
- 显示包含 ip 地址的列表。
要处理的文件是 test.txt :
test.txt
代码
# importing the module import re # opening and reading the file with open('f:/test.txt', encoding='utf-8') as fh: fstring = fh.readlines() # declaring the regex pattern for ip addresses pattern = re.compile(r'(d{1,3}.d{1,3}.d{1,3}.d{1,3})') # initializing the list object lst = [] # extracting the ip addresses for line in fstring: match = pattern.search(line) if match is not none: lst.append(match[0]) else: lst.append(none) # displaying the extracted ip addresses print(lst)
输出 :
上面的 python 程序显示文件中存在的任何类型的 ip 地址。我们还可以显示有效的ip 地址。
有效 ip 地址的规则:
- 数字应在 0-255 范围内
- 它应该由 4 个以“.”分隔的单元格组成。
有效 ip 地址的正则表达式是:
((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(25[0-5] |2[0-4][0-9]|[01]?[0-9][0-9]?)
用于有效 ip 的正则表达式说明:
由于我们不能在正则表达式中使用 0-255 范围,我们将其分为 3 组:
- 25[0-5] – 表示从 250 到 255 的数字
- 2[0-4][0-9] – 表示从 200 到 249 的数字
- [01]?[0-9][0-9]?- 表示从 0 到 199 的数字
要处理的文件是 test2.txt :
000.0000.00.00 192.168.1.1 912.465.123.123 192.168.4.164 69.168.4.226 32.89.31.164 67.168.3.227
代码:
# importing the module import re # opening and reading the file with open('test2.txt', encoding='utf-8') as fh: string = fh.readlines() # declaring the regex pattern for ip addresses pattern = re.compile('''((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)''') # initializing the list objects valid = [] invalid = [] # extracting the ip addresses for line in string: line = line.rstrip() result = pattern.search(line) # valid ip addresses if result: valid.append(line) # invalid ip addresses else: invalid.append(line) # displaying the ip addresses print("valid ips") print(valid) print("invalid ips") print(invalid)
输出 :
"c:program filespython39python.exe" c:/users/administrator/pycharmprojects/pythonproject8/extractip2.py
valid ips
['192.168.1.1', '192.168.4.164', '69.168.4.226', '32.89.31.164', '67.168.3.227']
invalid ips
['000.0000.00.00', '912.465.123.123']
进程已结束,退出代码为 0
补充:python提取一段字符串中的ip地址
代码如下:
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import re import os ip_str = os.popen('cat /root/bin/ips').read() iplist = re.findall( r'[0-9]+(?:.[0-9]+){3}',ip_str) print(iplist)
有时候从上游收到的ip地址很多是夹杂其他字符的,比如逗号,分号,中文字符,英文字符等等,需要提取纯粹的ip地址,可以使用这种方式。已经默认给出的字符串包含的都是正确的ip地址。如果想在确认ip地址是否合法,可以对列表iplist进行遍历,剔除不合法的ip元素。
总结
到此这篇关于使用python从文件中提取ip地址的文章就介绍到这了,更多相关python提取ip地址内容请搜索<猴子技术宅>以前的文章或继续浏览下面的相关文章希望大家以后多多支持<猴子技术宅>!
需要了解更多python教程分享教你使用Python从文件中提取IP地址,都可以关注python教程分享栏目—猴子技术宅(www.ssfiction.com)
本文来自网络收集,不代表猴子技术宅立场,如涉及侵权请点击右边联系管理员删除。
如若转载,请注明出处:https://www.ssfiction.com/pythons/1187935.html