Python 如何从迭代中使用 subprocess.Popen 获取 运行 的变量输入

Python How to get variable input to run with subprocess.Popen from iteration

下面的代码使用 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 """.

看来您 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 需要 "elements" 的命令列表,但是您必须小心 "element" 的构成。我相信(现在无法测试)您必须解决两件事:

  • '-p'变为'-p', '80'(两个元素——一个开关和一个参数)
  • ' --script=', x变成了'--script=%s' % x(不是两个元素,这个应该只有一个——还有一个前导space太多了)