/bin/sh:1:[:缺少]

2024-09-27 04:29:08 发布

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

我正在制作一个python脚本,它将自动检查计算机上是否安装了nmap,然后继续运行nmap。我遇到的一个问题是,当它运行时,它会返回/bin/sh: 1: [: missing ]并且我还想知道如何将终端的输出管道返回到我的程序中。假设我运行hostname -I如何复制输出并在脚本中为其分配一个变量名。谢谢,代码在下面

import os
import subprocess
def isInstalled(name):
    cmd = """ if ! [ -x "$#(command -v """ + name + """)" ]; then
      echo '0'
      exit 0
    fi"""
    ret = subprocess.check_output(cmd, shell=True).strip()
    if ret == b'0':
        return False
    return True

if isInstalled('nmap'):
print("Nmap is installed")

else:
    print("nmap is uninstalled since quite mode is active auto install will")

Tags: nameimport脚本cmdtruereturnifbin
2条回答
<> P>打印和其他打印之间存在空缺和空行。在

考虑到这一点:

Tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation.

将代码更改为:

if isInstalled('nmap'):
    print("Nmap is installed")
else:
    print("nmap is uninstalled since quite mode is active auto install will")

关于你的第二个问题,看看这个答案:https://stackoverflow.com/a/6657718/3589567

看起来您的默认shell是sh,但没有{a1}可用,所以请尝试在要编写的脚本中指定bash shebang #!/bin/bash

def isInstalled(name):
    cmd = """#!/bin/bash
    if ! [ -x "$#(command -v """ + name + """)" ]; then
      echo '0'
      exit 0
    fi"""
    ret = subprocess.check_output(cmd, shell=True).strip()
    if ret == b'0':
        return False
    return True

或者可以在bash中使用double bracketsfor if else语句:

^{pr2}$

相关问题 更多 >

    热门问题