Python如何从迭代中获取与subprocess.Popen一起运行的变量输入

时间:2017-12-18 14:50:43

标签: python subprocess nmap

下面的代码使用http脚本遍历列表。然后应该将变量输入x变量。输出打印到文件。但是文件产生的输出声明script=",尝试了其他变体,但总是有错误。

with open("nmap_http_output.txt", "w") as f: 
    for x in scripts:   # iterate over http scripts
            print(x)  # for debugging purposes - this prints
            print(ip) # for debugging purposes - this prints
            nmap_http_ps = subprocess.Popen(['nmap', '-p80', ' --script=', x, ip], stdout=f, stderr=subprocess.STDOUT)
            output = nmap_http_ps.communicate()
            print(output)

输出是:

Nmap done: 1 IP address (1 host up) scanned in 0.30 seconds
Starting Nmap 7.60 ( https://nmap.org ) at 2017-12-18 08:51 CST
Failed to resolve " --script=".
Failed to resolve """.
Unable to split netmask from target expression: "/usr/share/nmap/scripts/http-auth-finder.nse"
Failed to resolve """.

1 个答案:

答案 0 :(得分:0)

看起来你的Popen参数错误了。

with open("nmap_http_output.txt", "w") as f: 
    for x in scripts:   # iterate over http scripts
        print(x)  # for debugging purposes - this prints
        print(ip) # for debugging purposes - this prints
        nmap_http_ps = subprocess.Popen(
            ['nmap', '-p', '80', ' --script=%s' % x, ip], stdout=f, stderr=subprocess.STDOUT
            )
        output = nmap_http_ps.communicate()
        print(output)

Popen需要一个命令的“元素”列表,但是你必须要注意构成“元素”的内容。我相信(现在无法测试)你必须解决两件事:

  • '-p'变为'-p', '80'(两个元素 - 开关和参数)
  • ' --script=', x变为'--script=%s' % x(而不是两个元素,这应该只是一个 - 并且还有一个领先的空间太多)