Python 子进程 nmap 输出与终端命令不同

Python subprocess nmap output different from terminal command

我正在尝试在 linux 中使用 nmap 命令的输出(shell 输出):

sudo nmap -sn 192.168.1.0/24
------
Nmap scan report for 192.168.1.98
Host is up (0.094s latency).
MAC Address: B8:27:EB:CE:0A:9F (Raspberry Pi Foundation)

在 python 脚本中通过子进程:

import subprocess
p = subprocess.Popen(["nmap", "-sn", "192.168.1.0/24"], stdout=subprocess.PIPE)
output, err = p.communicate()
print ("*** Running nmap -sn 192.168.1.0/24 ***\n", output)

除了我需要 shell 输出有而子进程没有的 MAC 行之外,它工作得很好。

子进程输出:

\nNmap scan report for 192.168.1.98\nHost is up (0.015s latency).\n

我正在研究通过 MAC/Name 获取 IP 的想法,但如果没有那条线,我不知道该怎么做...

您不需要 运行 nmap 作为 python 中的子进程,您可以只安装 nmap 库并导入它。

pip install python-nmap

然后编写代码:

import json
import nmap

np = nmap.PortScanner()

target = '192.168.1.0/24'

# Scan the subnet 
results = np.scan(hosts=target, arguments='-sn')

# Clean the data nmap returns
results = results['scan']
output = {}
for result in results:
    output[result] = {}
    # Add the MAC addr to the IP
    try:
        output[result]['mac']       = results[result]['addresses']['mac']
    except:
        output[result]['mac']       = 'No MAC address avalible'
    # Add the vendor to the IP
    try:
        output[result]['vendor']    = list(results[result]['vendor'].values())[0]
    except:
        output[result]['vendor']    = 'No vendor info avalible'

print(json.dumps(output,indent=2))

当你 运行 你的代码时,你必须 运行 它作为 sudo 否则你不会得到 MAC 地址。

输出应如下所示

{
  "192.168.1.1": {
    "mac": "16:91:82:xx:xx:xx",
    "vendor": "No vendor info avalible"
  },
  "192.168.1.10": {
    "mac": "44:39:C4:xx:xx:xx",
    "vendor": "Universal Global Scientific Industrial"
  },
  "192.168.1.50": {
    "mac": "No MAC address avalible",
    "vendor": "No vendor info avalible"
  }
}

希望对您有所帮助:-)