因为工作需要,远程获取主机开放的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
详细见文档