python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python提取IP地址

教你使用Python从文件中提取IP地址

作者:allway2

Python提供了高效的高级数据结构,还能简单有效地面向对象编程,下面这篇文章主要给大家介绍了关于如何使用Python从文件中提取IP地址的相关资料,需要的朋友可以参考下

让我们看看如何使用 Python 从文件中提取 IP 地址。

算法 :  

r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'

要处理的文件是 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 地址的规则: 

有效 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 组:

要处理的文件是 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 Files\Python39\python.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地址内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文