Home  >  Article  >  Backend Development  >  Skillfully use python and libnmapd to extract Nmap scan results

Skillfully use python and libnmapd to extract Nmap scan results

高洛峰
高洛峰Original
2017-02-25 10:29:461674browse

Whenever I perform intranet penetration and face a large number of hosts and services, I am always used to using automated methods to extract information from nmap scan results. This facilitates automated detection of different types of services, such as path blasting on web services, testing keys or protocols used by SSL/TLS services, and other targeted testing.

I also often use IPthon or *nix shell in penetration testing, and these can be accessed through Python, whether used directly in scripts, used in REPL environment, or It is very useful to write the code to disk and then access it through shell commands.


Configuration
The first step in parsing nmap scan results is that you perform an nmap scan. I'm not going to go into too much detail here, but if you want to use the code from this article directly, you need to save the scan structure to an xml file (-oX or -oA) and perform service detection on the open port (-sV) and run related scripts (-sC).
The commands in this article assume that you are executing in a Python REPL environment such as IPython and the libnmap module is installed (can be installed using easy_install or pip).
Before you start, you need to set up the corresponding environment. First import the NmapParser module and read in your xml scan result file (the name in the example is "up_hosts_all_ports_fullscan.xml" located in the current working directory)

from libnmap.parser import NmapParser
nmap_report = NmapParser.parse_fromfile('up_hosts_all_ports_fullscan.xml')

The remainder of this article will contain a series of extracts of various useful information using one line of code. All examples assume that the nmap scan results are saved in a file as shown above. The following will give some basic sample codes. If you want to run them directly in IPython, please run the above code first, so that it will be output directly on the console for your viewing. I usually do this first so I can make sure the output data is as expected.
You can then choose a variable name and use "=" to assign data to the variable so that you can call it directly in subsequent code, or write it to disk for use by shell commands. If there is something you want to use multiple times, you can paste some code snippets into a Python script, or you want to add some more complex logic but this may make the REPL environment difficult to handle. I will explain how to quickly execute this in the last section. operate.

Port information
Hosts that open the specified port number
Displays all hosts that open the specified port number. Generate a list containing host addresses (string). The following takes port 443 as an example. You can modify it to the value you need.

 [ a.address for a in nmap_report.hosts if (a.get_open_ports()) and 443 in [b[0] for b in a.get_open_ports()] ]

Number of open ports

Displays the number of open ports for a series of hosts. Generate a list containing the number of ports (int) and sort it.

 sorted(set([ b[0] for a in nmap_report.hosts for b in a.get_open_ports()]), key=int)

The services corresponding to the open ports of the host are grouped by port numbers

Display the port numbers open of all hosts, grouped and sorted by port numbers. Generate a list containing multiple lists (that is, each element of the list is also a list), in which the first element of each member list is a port number (int), and the second element is a host IP address containing the open corresponding port ( string) list.

 [ [a, [ b.address for b in nmap_report.hosts for c in b.get_open_ports() if a==c[0] ] ] for a in sorted(set([ b[0] for a in nmap_report.hosts for b in a.get_open_ports()]),key=int) ]
SSL/TLS 和 HTTP/HTTPS

Hosts and ports using SSL

Displays all hosts and ports using SSL. This is done by looking to see if any service uses an "SSL" channel or if the associated script detects a pem certificate in the results. Generate a list containing a series of lists, each member list contains the host address (string) and port number (int).

 [ [a.address, b.port] for a in nmap_report.hosts for b in a.services if b.tunnel=='ssl' or "'pem'" in str(b.scripts_results) ]

The following content contains the same information as above, but instead of a list of lists, the join function is used to create a list containing "host:port number" (string).

 [ ':'.join([a.address, str(b.port)]) for a in nmap_report.hosts for b in a.services if b.tunnel=='ssl' or "'pem'" in str(b.scripts_results) ]

Contains the host and port of the web service

Displays all web services and their corresponding port numbers and protocols (http or https). This produces a list of multiple lists, where each member list contains a protocol (string), address (string), and port number (int). But there are some problems here. When nmap reports websites that use https, sometimes it will show that the service is "https", and sometimes it will show as "http" using the "ssl" channel, so I adjusted the data format for uniformity. output.

 [ [(b.service + b.tunnel).replace('sl',''), a.address, b.port] for a in nmap_report.hosts for b in a.services if b.open() and b.service.startswith('http') ]

The same information is still here, but the url (string) is added to the original list containing protocol, host and port number.

 [ (b.service + b.tunnel).replace('sl','') + '://' + a.address + ':' + str(b.port) + '/' for a in nmap_report.hosts for b in a.services if b.open() and b.service.startswith('http') ]

Other service information
Unknown services

Displays all services that nmap cannot recognize. Generates a list containing multiple lists, where each member list contains the address (string), the port number (int), and the port fingerprint scanned by nmap (string). This information is generated mainly to facilitate subsequent manual review of those specific services and will not participate in any automated process.

 [ [ a.address, b.port, b.servicefp ] for a in nmap_report.hosts for b in a.services if (b.service =='unknown' or b.servicefp) and b.port in [c[0] for c in a.get_open_ports()] ]

Nmap identified software
Displays all software identified by nmap scans. Generate a list sorted alphabetically by product.

 sorted(set([ b.banner for a in nmap_report.hosts for b in a.services if 'product' in b.banner]))

软件对应的主机和端口号,按产品分组
显示扫描出软件对应的主机和端口,按产品分组。生成一个包含多个列表的列表,其中每个成员列表的第一个元素为软件的名称(string),随后是另一个列表包含地址(string)和端口号(int)。

 [ [ a, [ [b.address, c.port] for b in nmap_report.hosts for c in b.services if c.banner==a] ] for a in sorted(set([ b.banner for a in nmap_report.hosts for b in a.services if 'product' in b.banner])) ]

同上相同的信息,只是输出略有不同。同样还是生成一个包含多个列表的列表,成员列表的第一个元素还是软件的名称(string),但第二个是一个包含 “主机:端口号” 的列表。

 [ [ a, [ ':'.join([b.address, str(c.port)]) for b in nmap_report.hosts for c in b.services if c.banner==a] ] for a in sorted(set([ b.banner for a in nmap_report.hosts for b in a.services if 'product' in b.banner])) ]

搜索指定关键词相关的主机和端口
显示所有与给定关键词相关联的主机和端口,从 nmap 扫描结果的原始文本中查找包含产品名称、服务名称等等。下面以 “Oracle” 为例。生成一个包含多个列表的列表,其中每个成员列表包含主机地址(string)和端口号(int)。

 [ [a.address, b.port] for a in nmap_report.hosts for b in a.services if b.open() and 'Oracle' in str(b.get_dict()) + str(b.scripts_results) ]

同上一样的方法,只是将存储的信息修改后一律使用小写进行搜索(下面示例为小写的 “oracle”),输出格式还是跟上面一样。

 [ [a.address, b.port] for a in nmap_report.hosts for b in a.services if b.open() and 'oracle' in (str(b.get_dict()) + str(b.scripts_results)).lower() ]

 
其他的事情

相同的证书名称
显示找到的 SSL 证书和使用 nmap 脚本解析后得到证书名称相同的部分。这样在当你从一个 IP 地址开始扫描且反向 DNS 失效的时候,可以帮助确定系统的主机名。生成一个包含多个列表的列表,其中每个成员列表包含 IP 地址(string)和提取出的主机名(string)。 

 [ [a.address, c['elements']['subject']['commonName'] ] for a in nmap_report.hosts for b in a.services for c in b.scripts_results if c.has_key('elements') and c['elements'].has_key('subject') ]

处理以上结果的方法

正向前面所说,上述的例子,当你直接粘贴进 IPython REPL 时只是将输出打印在屏幕上。这的确不错,因为这样你可以随时查看到自己感兴趣的信息,但你可能还会想做更多的事情。之所以去生成上述信息,一大好处就在于你可以根据结果轻松执行一些自动化的操作。
如果你已经很熟悉 Python,应当可以很容易完成这些工作,那么你可以跳过这一节。但如果你不熟悉,那么本节会讲述一些很基本的知识,告诉你如何使用上述的代码段。

保存到磁盘
如果你想将上述代码段的输出结果保存到磁盘上的文本文件中,你需要将输出的列表转换为适当的字符串格式(具体取决于你的需求),然后在将这个字符串写入文件。在 Python 中,你可以使用 join 函数来整合这些列表并将其写入文件,这里只是一个示例。
我们想要从生成的列表中提取出支持 SSL 的主机和端口,并将它们保存到一个新的文件中,这样可以在 bash 中使用循环来完成并使用命令行工具来进行测试。
我通常会在 IPython 中使用一行代码来完成这些,虽然一行代码会比较方便,但这里为了方便阅读和理解,我会将代码拆分出来说。
让我们来解析之前生成了一个包含 “主机:端口” 的列表,请注意我们使用了 str 函数将端口号从整数类型装换为了字符类型,这样使得它也能够使用 join 函数与其他字符串拼接在一起。

 [ ':'.join([a.address, str(b.port)]) for a in nmap_report.hosts for b in a.services if b.tunnel=='ssl' or "'pem'" in str(b.scripts_results) ]

让我们来给上面这段代码的结果分配名为 “ssl_services” 变量,以方便后续的调用。

 ssl_services = [ ':'.join([a.address, str(b.port)]) for a in nmap_report.hosts for b in a.services if b.tunnel=='ssl' or "'pem'" in str(b.scripts_results) ]

现在,让我们来使用 join 函数将列表的每一个元素拼接起来并使用 (‘\n') 进行换行,然后给它分配一个名为 “ssl_services_text” 的变量。

 ssl_services_text = '\n'.join(ssl_services)

随后,我们就可以在当前工作目录下创建一个名为 “ssl_services_file.txt” 的新文建,并将 “ssl_services_text” 变量的内容写入其中。

 open('ssl_services_file.txt','w').write(ssl_services_text)

就这么简单,后续你可以根据自己的需要来使用文件内容了。

使用其他 Python 代码
也许你还会想用其他的 Python 代码来完成上述工作?同样很简单,下面就是另一个示例,这里我们遍历每一个 nmap 识别出的 web 服务及其网页的请求结果。
下面会生成一个包含 URLs 的列表,我们分配一个名为 “urls” 的变量给它。

 urls = [ (b.service + b.tunnel).replace('sl','') + '://' + a.address + ':' + str(b.port) + '/' for a in nmap_report.hosts for b in a.services if b.open() and b.service.startswith('http') ]

下一步,我们先进行一些准备工作,导入 requests 模块,然后设置一个简单的 getAndSave 函数进行 web 请求并将返回结果保存到磁盘上,文件名按 url 自动生成。你可能会注意到下面代码中,在 get 请求中使用了 “verify=False” 选项,这会在发送请求时忽略证书验证的错误,这个选项经常在测试内部机器时使用,因为内部机器基本不会有可信的证书颁发机构颁发的 SSL 证书。 

 import requests
def getAndSave(url):
r = requests.get(url, verify=False)
open('_'.join(url.split('/')[2:]).replace(':',''),'wb').write(r.text.encode('utf8'))

现在,让我们增加一些代码来遍历每一个 url,请求每个站点的 robots.txt 文件,并将其保存到本地以供后续使用。 

 for a in urls:
getAndSave(a + 'robots.txt')

这样就会将每一个站点的 robots.txt 文件爬取到当前工作目录下。这只是一个很简单的例子。

总结

希望你在阅读完本文后,可以自己灵活的使用 Python 解析 nmap 扫描结果。

更多巧用python和libnmapd,提取Nmap扫描结果相关文章请关注PHP中文网!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn