如果MySQL正在运行,如何在ubuntu上找到python?

在Ubuntu这个命令行:

sudo netstat -tap | grep mysql

如果MySQL正在运行,则返回类似的内容:

tcp  0  0 localhost:mysql  *:*  LISTEN  6732/mysqld

没有,如果不是.

我正在使用子进程从python代码中查找MySQL是否通过在netstat返回的内容中查找“LISTEN”来执行此操作:

import subprocess

msqlr = subprocess.Popen(["sudo netstat -tap | grep mysql"], stdout=subprocess.PIPE).communicate()[0]
msqlrLines = msqlr.split("\n")
vals = msqlrLines[0].split()
print "vals[0] : %s" % vals[0]
if vals[0][-2] == "LISTEN":
    print "OK - MySQL is running."
else:
    print "Not OK - MySQL is not running."

当我运行它时,它返回:

OSError: [Errno 2] No such file or directory

当在同一个subprocess.Popen …我使用一个单词参数(让我们说“df”) – 它工作正常.如果参数多于一个单词(即“df -h /”或者像这里“sudo netstat -tap | grep mysql”) – 我得到这个“没有这样的文件或目录”错误.

和相关的问题(#2),当我在命令行中运行此命令时 – 有时它会要求输入root密码.如何从python脚本传递密码?

最佳答案 尝试一下这个.

import subprocess
import string

msqlr = subprocess.Popen("sudo /usr/sbin/netstat -al".split(), stdout=subprocess.PIPE).stdout
grep = subprocess.Popen(["/usr/bin/grep", "mysql"], stdin=msqlr, stdout=subprocess.PIPE).stdout
msqlrLines = grep.read().split("\n")
vals = map(string.strip, msqlrLines[0].split())
print vals
if vals[-1] in ("LISTENING", "LISTEN"):
    print "OK - MySQL is running."
else:
    print "Not OK - MySQL is not running."

在我的机器上输出:

['tcp4', '0', '0', '*.mysql', '*.*', 'LISTEN']
OK - MySQL is running.

这里的想法是你做正常的netstat,并收集所有的数据.然后使用该子过程中的stdout作为下一个子过程的stdin,并在那里执行grep.

这是在ubuntu 12.04上运行的示例

import subprocess
import string

msqlr = subprocess.Popen("sudo /bin/netstat -al".split(), stdout=subprocess.PIPE).stdout
grep = subprocess.Popen(["/bin/grep", "mysql"], stdin=msqlr, stdout=subprocess.PIPE).stdout
msqlrLines = grep.read().split("\n")
vals = map(string.strip, msqlrLines[0].split())
print vals
if len(vals) and vals[-1] in ("LISTENING", "LISTEN"):
    print "OK - MySQL is running."
else:
    print "Not OK - MySQL is not running."
点赞