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