gpt4 book ai didi

python - 将 Nmap 子进程中的数据直接存储到列表中

转载 作者:太空宇宙 更新时间:2023-11-03 17:10:57 25 4
gpt4 key购买 nike

我有以下方法可以通过运行 nmap 子进程获取 IP 列表:

import subprocess
import os

def get_hosts(ips, exclude_file, outfile):
# Run the NMAP for given IPs
output = subprocess.Popen(['nmap', ips, '-sn', '-T4', '-oG', 'temp.txt', '--excludefile', exclude_file], shell=False, stdout=subprocess.PIPE)
# Open temp file
file = open('temp.txt', 'r')
# Get IP addresses
ip_list = []
for line in file:
a = line.split(" ")
# Bypass first and last line
if a[1] == 'Nmap':
pass
else:
ip_list.append(a[1])
# Close file
file.close()
# Remove temp file
os.remove('temp.txt')
return ip_list

ips = get_hosts('10.0.0.0/8', 'exclude.txt', 'output.txt')
print (ips)

我希望能够将它们存储在列表中,而不必创建临时文件并将其删除。这可能吗?我对 python 还很陌生,所以任何东西都会有所帮助。

最佳答案

来自nmap文档:

Output

...

Nmap makes output available in five different formats. The default is called interactive output,. and it is sent to standard output (stdout).. There is also normal output,. which is similar to interactive except that it displays less runtime information and warnings since it is expected to be analyzed after the scan completes rather than interactively.

...

While interactive output is the default and has no associated command-line options, the other four format options use the same syntax. They take one argument, which is the filename that results should be stored in.

所以我认为,不要将 nmap 进程的输出保存到 temp.txt 文件中,而是默认将其发送到 stdout ,这样:

>>> output = subprocess.Popen(['nmap', ips, '-sn', '-T4'], shell=False, stdout=subprocess.PIPE)

然后要检查结果,请使用 Popen.communicate :

>>> output.communicate()

Popen.communicate(input=None)

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

communicate() returns a tuple (stdoutdata, stderrdata).

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

Note

The data read is buffered in memory, so do not use this method if the data size is large or unlimited.

输出类似于:

>>> output.communicate()
('\nStarting Nmap 6.40 ( http://nmap.org ) at 2015-12-05 00:58 GST\nNmap scan report for 10.0.2.3\nHost is up (0.011s latency).\nNmap scan report for 10.0.2.15\nHost is up (0.000059s latency).\n', None)

这是一个(stdout,stderr)的元组,然后只需取出该元组的第一个元素并通过解析检索您想要的IP,例如使用regex .

关于python - 将 Nmap 子进程中的数据直接存储到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34096593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com