在Python中捕获netcat shell命令输出

时间:2014-03-13 17:16:53

标签: python linux shell subprocess

我想从我的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

2 个答案:

答案 0 :(得分:0)

如果你想在Python中使用sh库轻松调用shell命令。

在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

答案 1 :(得分:0)

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

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