Python3 os.popen 当我对 Nmap 进行 dcker 化时,它无法与 Nmap 一起工作

Python3 os.popen is not working with Nmap when I dckerize it

我有一个用于 nmap 工具的 HTTP Flask API,代码:

from flask import Flask, request, render_template, redirect, url_for
import os

rejected_characters = ';|\&'

app = Flask(__name__)

@app.route('/', methods=['POST'])
def index():
    if request.method == 'POST':
        args = request.get_json()["nmap_args"]
        for i in rejected_characters:
            if i in args:
                return render_template('scan.html', response="Invalid request")
        nmap_output = os.popen("nmap {}".format(args)).read()
        return render_template('scan.html', response=nmap_output)       
    else:
        respose = "Send a POST request to '/' with json content containing 'nmap_args' key\n"
        respose += "nmap_args will be the arguments passed to nmap command `nmap [nmap_args]`"
        return render_template('scan.html', respose=respose)

if __name__ == "__main__":
    app.run(host='0.0.0.0')

当我通过 运行 python3 app.py 打开服务器时一切正常,当我发送这样的请求时:

curl -X POST http://localhost:5000 --data '{"nmap_args": "-sC -sV localhost -p22"}' -H "Content-Type: application/json"

响应将在 nmap 完成扫描后返回。 响应将是这样的:

Starting Nmap 7.80 ( https://nmap.org ) at 2020-03-30 15:12 EEST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00023s latency).
Other addresses for localhost (not scanned): ::1

PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.9 (protocol 2.0)
| ssh-hostkey:
|   2048 87:75:d4:af:97:e6:bb:7b:e8:14:36:65:a1:ee:58:c1 (RSA)
|   256 a0:b6:03:50:84:45:6a:f2:d1:d6:66:ce:36:06:ce:75 (ECDSA)
|_  256 22:c4:e0:c2:d7:c1:7e:b6:0c:03:7e:e8:ef:eb:8f:c4 (ED25519)

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 1.13 seconds

问题是当我 docker 启动应用程序时,我立即收到响应,但没有 nmap 的完整结果。我刚收到 Starting Nmap 7.80 ( https://nmap.org ) at 2020-03-30 15:12 EEST.

docker 图片有什么问题,如何解决?

注意:我运行 docker 图像使用命令:docker run -p 5000:5000 nmap-api

问题是因为 os.popen(..),我不知道为什么它在 docker 图像中不起作用。

但是,我用这段代码替换了这一行 nmap_output = os.popen("nmap {}".format(args)).read()(使用 subprocess 而不是 os):

cmd = ["nmap"] + args.split(' ')
result = subprocess.check_output(cmd)
nmap_output = result.decode('utf-8')