@myles
2017-07-14T08:40:47.000000Z
字数 1340
阅读 1785
python正则匹配
关于
[^\s]+
这个正则的常用场景:
例如:匹配提取主机IP
主机扫描结果如下,那我们如何利用上面这个正则匹配提取出在线主机IP呢?
Nmap scan report for 192.168.31.1
Host is up (0.0024s latency).
Not shown: 994 closed ports
PORT STATE SERVICE
53/tcp open domain
80/tcp open http
8192/tcp open sophos
8193/tcp open sophos
8383/tcp open m2mservices
8899/tcp open ospf-lite
MAC Address: 28:6C:07:5B:4B:4B (Xiaomi Electronics,co.)
Nmap scan report for 192.168.31.71
Host is up (0.0030s latency).
Not shown: 927 closed ports, 72 filtered ports
PORT STATE SERVICE
62078/tcp open iphone-sync
MAC Address: 90:60:F1:1C:3E:60 (Apple)
Nmap scan report for 192.168.31.248
Host is up (0.0029s latency).
Not shown: 999 filtered ports
PORT STATE SERVICE
3389/tcp open ms-wbt-server
MAC Address: 64:D9:54:08:50:D9 (Taicang T&W Electronics)
正则匹配方法:
regex = re.compile(r'for\s([^\s]+)'
注:本正则表达中,我们用到了使用“()”来进行文本的捕获。
正则匹配脚本编辑:
file = open('C:\\user\\admin\desktop\result.txt','r')
read_file = file.read()
regex = re.compile(r'for\s([^\s]+)')
hostlist = regex.findall(read_file)
for host in hostlist:
print(host)
更新版本:
#!/bin/env/python
#encoding=utf-8
import re
import os
# 获取扫描文件
get_path= os.getcwd()
filename = input("请输入您的扫描报告:")
path = get_path+'/'+filename
print(path)
#读取文件
file = open(path,'r')
file_read = file.read()
#正则提取"主机列表"
regex = re.compile(r'for\s([^\s]+)')
hostlist = regex.findall(file_read)
#循环打印主机列表;
for host in hostlist:
print(host)
正则表达式30分钟入门教程:http://deerchao.net/tutorials/regex/regex.htm