python中使用subprocess调用外部程序

因为工作需要,远程获取主机开放的mysql端口,于是想到了使用ssh host ps aux | grep mysq,然后对结果使用正则表达式进行分析,然后获得结果。

以前使用python的os.popen()函数,因为上面的语句可能碰到host不存在的情况,需要处理stderr,使用os.popen不知道如何处理stderr,刚才在文档中看到os.popen()已经被deprecated了,推荐使用subprocess来代替,于是就尝试了一下subprocess,一般功能越强大,文档越复杂,果然如此。

 

使用的时候就遇到了下面的错误:

a) pipe = subprocess.Popen("/bin/ls /", stdout=subprocess.PIPE,
close_fds=True)
==>OSError: [Errno 2] No such file or directory
b) pipe = subprocess.Popen("/bin/ls /", stdout=subprocess.PIPE,
close_fds=True, shell=True)

 

解决方法:
You have to use a list instead of a string here.
pipe = subprocess.Popen(["/bin/ls", "/"], stdout=subprocess.PIPE)

#!/usr/bin/python
import subprocess
import re
err_list=[]
for host in range(1,70):
    pf=subprocess.Popen(["ssh","user%s.db"%host,"ps aux | grep mysql"],shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    s=pf.stdout.read()
    if s!="":
        ports=re.findall(r"(?<=port=)/d+/b",s)
        print "user%s.db %s"%(host,list(set(ports)))
    s=pf.stderr.read()
    if s!="":
        err_list.append("user%s.db %s"%(host,s))
    pf.terminate()
print "the follow is the error db:"
for error_message in err_list:
    print error_message

 

详细见文档



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值