当我对Nmap进行dckerize时,Python3 os.popen不能与它一起工作

2024-04-23 14:48:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用于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

问题是,当我停靠应用程序时,我立即收到了响应,而没有收到nmap的全部结果。我刚刚收到Starting Nmap 7.80 ( https://nmap.org ) at 2020-03-30 15:12 EEST

docker映像有什么问题,如何解决

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


Tags: jsonapplocalhostflaskforscanifrequest
1条回答
网友
1楼 · 发布于 2024-04-23 14:48:15

问题是因为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')

相关问题 更多 >