[Python]执行Linux命令

使用subprocess模块

import subprocess

# 防火墙服务存在关闭状态
child1 = subprocess.Popen(["systemctl status firewalld | grep Active"], stdout=subprocess.PIPE, shell=True)
print(child1.communicate())
#----执行结果------  
(b
' Active: inactive (dead)\n', None)
# samba服务不存在
child2 = subprocess.Popen(["systemctl status smbd | grep Active"], stdout=subprocess.PIPE, shell=True)
print(child2.communicate())
#----执行结果------ 
Unit smbd.service could not be found.
(b
'', None)
# network存在激活状态
child3 = subprocess.Popen(["systemctl status network | grep Active"], stdout=subprocess.PIPE, shell=True)

print(child3.communicate())

#----执行结果------

(b'   Active: active (exited) since Tue 2020-02-11 20:19:08 CST; 21h ago\n', None)

 

posted @ 2020-02-12 17:40  LeoShi2020  阅读(454)  评论(0编辑  收藏  举报