How to learn from python on ubuntu if MySQL is working?

On the Ubuntu command line:

sudo netstat -tap | grep mysql 

if MySQL is running, it returns something like this:

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

and nothing if it is not.

I use a subprocess to find out from within python code if MySQL got up looking for "LISTEN" in what netstat returns by doing this:

 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 an argument from a single word (say, "df") - it works fine. If the argument is more than one word (ie "Df -h /" or, as here, "sudo netstat -tap | grep mysql"), I get the error "There is no such file or directory."

And the related question (# 2), when I run this command on the command line - sometimes it asks for the root password. How to pass password from python script?

+4
source share
2 answers

Try to do something.

 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." 

EXIT on my machine:

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

The idea here is that you make a normal netstat and collect all the data. Then use stdout from this routine as stdin for the next routine and make your grep there.

Here is an example running on 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." 
+2
source

Why not just see if you can connect to python:

 try: con = _mysql.connect('localhost', 'user', 'password', 'testdb') except _mysql.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit(1) 
0
source

Source: https://habr.com/ru/post/1442549/


All Articles