【问题标题】:Capturing netcat shell command output in Python [duplicate]在 Python 中捕获 netcat shell 命令输出 [重复]
【发布时间】:2014-04-18 15:02:55
【问题描述】:

我想从我的python脚本执行netcat命令,所以我使用'subprocess.Popen',但问题是这个命令的输出直接打印在may shell控制台中,我想把他放在一个变量中,所以我可以在打印之前做一些修改。

res = subprocess.Popen("nc -v 192.168.1.1 25", stdout=subprocess.PIPE, stderr=None, shell=True)
#output = res.communicate()
#output = str(output)
#print output

【问题讨论】:

标签: python linux shell subprocess


【解决方案1】:

如果您想让自己在 Python 中轻松调用 shell 命令,请使用 sh 库。

在 sh 中这将是:

  from sh import nc
  output = nc("-v", "192.168.1.1", "25")  # output is string of the command output

一如既往,installing Python libraries are recommended to do with virtualenv

【讨论】:

    【解决方案2】:

    我用它来捕获系统命令的输出,注意它只会得到最后一行。根据需要修改最后一行以获得更多:

    def GetOutput(command):
        lastline = os.popen(command).readlines()
        result = lastline[0].rstrip()
        return result
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 2015-02-05
      • 2022-01-14
      相关资源
      最近更新 更多