[英]subprocess runs command up to first pipe, then stops
If i run this command on its own: 如果我自己运行此命令:
nmap -PN -p 22 --open -oG - 10.15.86.0/24 | awk '$NF~/ssh/{print$2}' > sshopen.txt
I receive my desired output of: 我收到期望的输出:
10.15.86.4
10.15.86.5
10.15.86.9
10.15.86.11
etc...
All the hosts on my network with an open ssh port. 网络上所有具有开放ssh端口的主机。 However, when i try to run the same command within a Python subprocess, it seems to skip the awk. 但是,当我尝试在Python子进程中运行相同的命令时,似乎跳过了awk。 Python below: 下面的Python:
import subprocess
subnet = raw_input("Enter subnet to scan: ")
command1 = "nmap -PN -p 22 --open -oG - 10.15.86.0/24 | awk '$NF~/ssh /{print$2}' > sshopen.txt".split()
#command = ["nmap", "-PN", "-p", "22", "--open", "-oG", "-", subnet, "|", "awk", "'$NF~/ssh/{print $2}'", ">", "sshopen.txt"]
nmap = subprocess.Popen(command1, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
nmap_info, out = nmap.communicate()
print nmap_info
You'll notice the commented 'command', as i've tried as 'command' and 'command1'. 您会注意到注释的“命令”,就像我尝试过的“命令”和“命令1”一样。 Both return output of: 两者都返回输出:
Host: 10.15.86.4 () Status: Up
Host: 10.15.86.4 () Ports: 22/open/tcp//ssh///
Host: 10.15.86.5 () Status: Up
Host: 10.15.86.5 () Ports: 22/open/tcp//ssh///
etc...
It outputs as though there is no pipe awk (nmap -PN -p 22 --open -oG - 10.15.86.0/24) rather than (nmap -PN -p 22 --open -oG - 10.15.86.0/24 | awk '$NF~/ssh/{print$2}' > sshopen.txt). 它输出好像没有管道awk(nmap -PN -p 22 --open -oG-10.15.86.0/24)而不是(nmap -PN -p 22 --open -oG-10.15.86.0/24 | awk '$ NF〜/ ssh / {print $ 2}'> sshopen.txt)。 Why is it not applying the awk within the script? 为什么不在脚本中应用awk?
Thanks 谢谢
Try 尝试
p1 = Popen(["nmap", "-PN", "-p", "22", "--open", "-oG", "-", subnet], stdout=PIPE)
p2 = Popen(["awk", "$NF~/ssh/{print$2}"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()
output = p2.communicate()[0]
or 要么
check_output(command, shell=True)
This is from python's official subprocess doc . 这来自python的官方子流程doc 。
There are some security considerations with shell=True
though. 尽管shell=True
有一些安全方面的考虑 。
Unlike some other popen functions, this implementation will never implicitly call a system shell. 与某些其他popen函数不同,此实现绝不会隐式调用系统外壳程序。 This means that all characters, including shell metacharacters, can safely be passed to child processes. 这意味着所有字符(包括外壳元字符)都可以安全地传递给子进程。 If the shell is invoked explicitly, via shell=True, it is the application's responsibility to ensure that all whitespace and metacharacters are quoted appropriately to avoid shell injection vulnerabilities. 如果通过shell = True显式调用了shell,则应用程序有责任确保正确引用所有空格和元字符,以避免shell注入漏洞。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.