python中使用os.system方法时如何保存输出?

Python中使用os.system()方法可以运行shell命令,那如何把命令运行的输出保存到指定python变量呢?比如运行os.system('ps -x')来查看系统进程,我想提取该命令的输出内容到指定python变量中,该怎么办呢?

喜欢这个问题 | 分享 | 新建回答

回答

BlackA

Apr 23, 2019
2 赞

可以使用 subprocess 模块,subprocess 模块包含一个函数 Popen(),该函数在一个新的进程中启动一个子程序,第一个参数就是子程序的名字,在这里就是要执行的命令,关键字参数 shell = True 表示在shell中执行,还可以设置关键字参数 stdout、stderr、stdin 的值为 subprocess.PIPE 来使用管道与子进程交互。

这个函数会返回一个 subprocess.Popen 对象,可以用该对象的 communicate() 方法来得到命令执行的结果元组,这个元组的第一个项为命令的标准输出(第二项为 stderr),还有一点要注意的是这个结果是用本地系统的编码方式进行编码的(Windows下默认是GBK),可以通过 decode 函数将结果进行解码:

import subprocess
def run_command(cmd):
    result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    m_stdout, m_stderr = result.communicate()
	
    return m_stdout.decode("GBK")




你还可以参考下面这篇博文,使用 python实现木马病毒中的反向Shell:https://zhuanlan.zhihu.com/p/21935610



妹岛

Apr 23, 2019
6 赞

使用os.system方法应该实现不了上述功能。
但是可以使用os.popen('操作系统的shell命令').read()即可运行指定命令并返回系统输出,示例代码如下:

import os

output_str = os.popen('ps -x').read()
print output_str

上述的output_str变量就是运行“ps -x”命令的输出内容。