@myles
        
        2017-07-14T08:40:47.000000Z
        字数 1340
        阅读 1883
    python正则匹配
关于
[^\s]+这个正则的常用场景:
例如:匹配提取主机IP
主机扫描结果如下,那我们如何利用上面这个正则匹配提取出在线主机IP呢?
Nmap scan report for 192.168.31.1Host is up (0.0024s latency).Not shown: 994 closed portsPORT STATE SERVICE53/tcp open domain80/tcp open http8192/tcp open sophos8193/tcp open sophos8383/tcp open m2mservices8899/tcp open ospf-liteMAC Address: 28:6C:07:5B:4B:4B (Xiaomi Electronics,co.)Nmap scan report for 192.168.31.71Host is up (0.0030s latency).Not shown: 927 closed ports, 72 filtered portsPORT STATE SERVICE62078/tcp open iphone-syncMAC Address: 90:60:F1:1C:3E:60 (Apple)Nmap scan report for 192.168.31.248Host is up (0.0029s latency).Not shown: 999 filtered portsPORT STATE SERVICE3389/tcp open ms-wbt-serverMAC 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-8import reimport os# 获取扫描文件get_path= os.getcwd()filename = input("请输入您的扫描报告:")path = get_path+'/'+filenameprint(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