我正在编写一个Python脚本,用于检查特定IP/端口的活动连接数。为此,我使用os.system('my_command')来获取输出。os.system返回我传递给它的命令的退出状态(0表示命令无错误返回)。 如何将os.system抛出到STDOUT的值存储在变量中?以便稍后在函数中可以使用该变量进行计数。 类似subprocess、os.popen等模块可以帮助。有人能提供建议吗?
我正在编写一个Python脚本,用于检查特定IP/端口的活动连接数。为此,我使用os.system('my_command')来获取输出。os.system返回我传递给它的命令的退出状态(0表示命令无错误返回)。 如何将os.system抛出到STDOUT的值存储在变量中?以便稍后在函数中可以使用该变量进行计数。 类似subprocess、os.popen等模块可以帮助。有人能提供建议吗?
a=os.popen("your command").read()
新的结果存储在变量a
中 :)
import subprocess
p = subprocess.Popen('my_command', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, error = p.communicate()
print 'The output was', out, 'and the error was', error
。 - agfresult = subprocess.Popen('''sh -c "netstat -plant | awk \'{print $4}\' | grep %s:%s | wc -l' %(ip,port)"''')
编辑:或者像@Jakob-Bowyer在下面建议的那样,尝试使用 shell=True
。这是必需的,因为您不仅要运行一个命令,而是要使用 shell 的管道 |
功能。 - agfresult = subprocess.Popen(["netstat -plant | awk \'{print $4}\' | grep %s:%s | wc -l' %(ip,port)"], stdout=subprocess.PIPE, stderr= subprocess.PIPE)
我正在从用户接受原始输入的IP和端口。 - Ashutosh Narayanimport subprocess
p = subprocess.Popen('my_command', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, error = p.communicate()
netstat -plant | awk '{print $4}' | grep %s:%s | wc -l
你可以使用Python来进行分割、过滤和计数:
process = subprocess.Popen(['netstat', '-plant'], stdout=subprocess.PIPE)
num_matches = 0
host_and_port = "%s:%s" % (ip, port)
for line in process.stdout:
parts = line.split()
if parts[3] == host_and_port: # or host_and_port in parts[3]
num_matches += 1
print num_matches