[关闭]
@myles 2017-07-14T16:40:47.000000Z 字数 1340 阅读 1749

正则表达式之“[^\s]+”实现IP提取

python正则匹配


[^\s]+ 匹配非空字符

关于[^\s]+这个正则的常用场景:
例如:匹配提取主机IP

主机扫描结果如下,那我们如何利用上面这个正则匹配提取出在线主机IP呢?

  1. Nmap scan report for 192.168.31.1
  2. Host is up (0.0024s latency).
  3. Not shown: 994 closed ports
  4. PORT STATE SERVICE
  5. 53/tcp open domain
  6. 80/tcp open http
  7. 8192/tcp open sophos
  8. 8193/tcp open sophos
  9. 8383/tcp open m2mservices
  10. 8899/tcp open ospf-lite
  11. MAC Address: 28:6C:07:5B:4B:4B (Xiaomi Electronics,co.)
  12. Nmap scan report for 192.168.31.71
  13. Host is up (0.0030s latency).
  14. Not shown: 927 closed ports, 72 filtered ports
  15. PORT STATE SERVICE
  16. 62078/tcp open iphone-sync
  17. MAC Address: 90:60:F1:1C:3E:60 (Apple)
  18. Nmap scan report for 192.168.31.248
  19. Host is up (0.0029s latency).
  20. Not shown: 999 filtered ports
  21. PORT STATE SERVICE
  22. 3389/tcp open ms-wbt-server
  23. MAC Address: 64:D9:54:08:50:D9 (Taicang T&W Electronics)

正则匹配方法:

regex = re.compile(r'for\s([^\s]+)'

注:本正则表达中,我们用到了使用“()”来进行文本的捕获。

正则匹配脚本编辑:

  1. file = open('C:\\user\\admin\desktop\result.txt','r')
  2. read_file = file.read()
  3. regex = re.compile(r'for\s([^\s]+)')
  4. hostlist = regex.findall(read_file)
  5. for host in hostlist:
  6. print(host)

更新版本:

  1. #!/bin/env/python
  2. #encoding=utf-8
  3. import re
  4. import os
  5. # 获取扫描文件
  6. get_path= os.getcwd()
  7. filename = input("请输入您的扫描报告:")
  8. path = get_path+'/'+filename
  9. print(path)
  10. #读取文件
  11. file = open(path,'r')
  12. file_read = file.read()
  13. #正则提取"主机列表"
  14. regex = re.compile(r'for\s([^\s]+)')
  15. hostlist = regex.findall(file_read)
  16. #循环打印主机列表;
  17. for host in hostlist:
  18. print(host)

正则表达式30分钟入门教程:http://deerchao.net/tutorials/regex/regex.htm

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注