首页 > 解决方案 > 如何使用各种可选参数打开

问题描述

我有一个需要在 python 中运行并获取输出的过程。如何运行它,以便用户可以指定可以在进程上运行的可选参数。到目前为止,这就是我的功能。


    async def analyze_target(self, target, batchSize, delay, maxdepth, maxurls, maxwait, recursive, useragent, htmlmaxcols, htmlmaxrows):

        cmd = "wappalyzer"
        if batchSize != "":
            cmd = cmd + " --batch-size=" + batchSize

        if delay != "":
            cmd = cmd + " --delay=" + delay

        if maxdepth != "":
            cmd = cmd + " --max-depth=" + maxdepth

        if maxurls != "":
            cmd = cmd + " --max-urls=" + maxurls

        if maxwait != "":
            cmd = cmd + " --max-wait=" + maxwait

        if recursive == True:
            cmd = cmd + " --recursive"

        if useragent != "":
            cmd = cmd + " --user-agent=" + useragent

        if htmlmaxcols != "":
            cmd = cmd + " --html-max-cols=" + htmlmaxcols

        if htmlmaxrows != "":
            cmd = cmd + " --html-max-rows=" + htmlmaxrows

        cmd = cmd + " " + target
        
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
        
        tmp = p.stdout.read()

        self.logger.info(tmp)

        p_status = p.wait()

        """
        Returns log of what was wappalyzed
        """
        message = f"target {target} has been wappalyzed with output {tmp}"

        # This logs to the docker logs
        self.logger.info(message)
        return tmp

标签: pythonargumentspopen

解决方案


不要构建字符串。只需构建一个包含命令名称及其参数作为单独元素的列表。

async def analyze_target(self, target, batchSize, delay, maxdepth, maxurls, maxwait, recursive, useragent, htmlmaxcols, htmlmaxrows):

    cmd = ["wappalyzer"]
    if batchSize != "":
        cmd.append("--batch-size=" + batchSize)

    if delay != "":
        cmd.append("--delay=" + delay)

    if maxdepth != "":
        cmd.append("--max-depth=" + maxdepth)

    if maxurls != "":
        cmd.append("--max-urls=" + maxurls)

    if maxwait != "":
        cmd.append("--max-wait=" + maxwait)

    if recursive:
        cmd.append("--recursive")

    if useragent != "":
        cmd.append("--user-agent=" + useragent)

    if htmlmaxcols != "":
        cmd.append("--html-max-cols=" + htmlmaxcols)

    if htmlmaxrows != "":
        cmd.append("--html-max-rows=" + htmlmaxrows)

    cmd.append(target)
    
    # Drop the shell=True, so that command is executed
    # directly, without shell involvement
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    
    ...

推荐阅读