On Ubuntu this command line:
sudo netstat -tap | grep mysql
if MySQL is running returns something like that:
tcp 0 0 localhost:mysql *:* LISTEN 6732/mysqld
and nothing if it’s not.
I’m using subprocess to find out from inside the python code if MySQL is up by looking for a “LISTEN” in what that netstat returns, doing that:
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."
When I run this it returns:
OSError: [Errno 2] No such file or directory
When in the same subprocess.Popen… I use a one word argument (let’s say “df”) – it works OK. If the argument is more that one word (i.e. “df -h /” or, like here “sudo netstat -tap | grep mysql”) – I’m getting this “No such file or directory” error.
And related question (#2), when I’m running this command in a command line — sometimes it asks for a root password. How do I pass a password from a python script?
Try something line this.
OUTPUT on my machine:
The idea here is you do the normal netstat, and collect all of the data. Then use the stdout from that subproc as the stdin for the next subproc and do your grep there.
Here is an example running on ubuntu 12.04