因为工作需要,远程获取主机开放的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
详细见文档
本文详细介绍了使用subprocess替代os.popen处理SSH命令,以获取远程主机上MySQL服务开放的端口,并通过正则表达式解析结果。同时,文章解决了在执行命令时遇到的错误,并提供了完整的代码实现。
1981

被折叠的 条评论
为什么被折叠?



