Python3.4 -Nmap需要root权限

时间:2015-08-26 01:42:13

标签: python-3.x privileges nmap

在Mac Os 10.10.5上运行 运行此脚本以扫描网络上的主机:

import nmap
nm = nmap.PortScanner()
nm.scan('192.168.5.1/24', arguments='-O')
for h in nm.all_hosts():
    if 'mac' in nm[h]['addresses']:
        print(nm[h]['addresses'], nm[h]['vendor'])

运行时打印:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/nmap/nmap.py", line 290, in analyse_nmap_xml_scan
    dom = ET.fromstring(self._nmap_last_output)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/xml/etree/ElementTree.py", line 1326, in XML
    return parser.close()
  File "<string>", line None
xml.etree.ElementTree.ParseError: no element found: line 1, column 0

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/*/Documents/*.py", line 3, in <module>
    nm.scan('192.168.0.0/24', arguments='-O')
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/nmap/nmap.py", line 235, in scan
    nmap_err_keep_trace = nmap_err_keep_trace)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/nmap/nmap.py", line 293, in analyse_nmap_xml_scan
    raise PortScannerError(nmap_err)
nmap.nmap.PortScannerError: 'TCP/IP fingerprinting (for OS scan) requires root privileges.\nQUITTING!\n'

我尝试进入该目录并在终端中运行此命令: sudo python * .py

({'mac': '02:62:31:41:6D:84', 'ipv4': '192.168.5.1'}, {})

有关从python IDLE运行脚本的任何建议吗?

2 个答案:

答案 0 :(得分:0)

以root身份运行IDLE可能会有效,但这可能不是一个好主意。 sudo idle

选项1(推荐):

将需要提升权限的代码放在使用sudo运行的python文件中。我假设您想要使用结果,因此您可以让脚本将结果保存到文件中,然后在IDLE中读取该文件。

以下代码适用于python 2.7和3.4

import nmap
import json

nm = nmap.PortScanner()
nm.scan('192.168.5.1/24',arguments='-O') #Note that I tested with -sP to save time
output = []
with open('output.txt', 'a') as outfile:
  for h in nm.all_hosts():
    if 'mac' in nm[h]['addresses']:
      item = nm[h]['addresses']
      if nm[h]['vendor'].values():
        item['vendor'] = list(nm[h]['vendor'].values())[0]
      output.append(item)
  json.dump(output, outfile)

运行sudo python nmaproot.py 由于文件是由root编写的,因此您需要将所有权更改回自己。 sudo chown -r myusername output.txt

在IDLE:

import json
input = open('output.txt','r'):
json_data = json.load(input)
json_data[0] # first host

选项2(根本不推荐):

使用subprocess以root身份使用提升的代码运行文件并返回输出。它有点混乱,要求你硬编码你的密码......但这是可能的。

from subprocess import Popen, PIPE
cmd = ['sudo', '-S', 'python', 'nmaproot.py']
sudopass = 'mypassword'
p = Popen(cmd, stdin=PIPE, stderr=PIPE,universal_newlines=True, stdout=PIPE)
output = p.communicate(sudopass + '\n')

我不确定如何以root身份运行python代码的给定部分,而不将其保存到文件并单独运行。我建议你选择选项1,因为选项2不是很好(但很难搞清楚)。

答案 1 :(得分:0)

复制空闲桌面快捷方式,然后将其命名为rootidle,然后更改属性。转到桌面条目并在/ usr / bin / idle3之前添加gksu。然后加载并运行程序