starting MySQL from python script - python

Im trying to start mysql server from python 3.4 script on Max OS X 10.10.4
yet I don't know how to pass the super user password ?
import os
os.system("sudo /usr/local/mysql/support-files/mysql.server start")
Sudo: no tty present and no askpass program specified

You are currently going in the right direction. In my system a mysql server is started from /etc/init.d/mysql.
Just use the following code snippet to run your mysql server from a python script.
import os
os.system('sudo /etc/init.d/mysql start')
The best way to run the root commands will be to execute the file itself as root
Simply type sudo python script.py in your shell and you can replace os.system('sudo /etc/init.d/mysql start')
with
os.system('/etc/init.d/mysql start')

Related

rc.local python script can't load mysql python connector

I am running Raspbian on a Raspberry Pi. I have a python script set in /etc/rc.local to run when the device is booted. The python script was working as expected until I added mysql functionality to the script. Mysql is correctly installed and configured; the mysql functionality in the script works as expected when run manually from the shell. According to /var/log/syslog, the script is unable to find the mysql module:
Mar 17 10:18:42 PressPi rc.local[464]: Traceback (most recent call last):
Mar 17 10:18:42 PressPi rc.local[464]: File "/home/pi/python/switch_counter3.py", line 20, in <module>
Mar 17 10:18:42 PressPi rc.local[464]: import mysql.connector
Mar 17 10:18:42 PressPi rc.local[464]: ModuleNotFoundError: No module named 'mysql'
Python import statement :
import mysql.connector
/etc/rc.local entry :
python3 /home/pi/python/switch_counter3.py &
I also tried :
sudo python3 /home/pi/python/switch_counter3.py &
I tried to add a 60 second sleep in rc.local before the python script was called, in case the script was running before mysql was initialized. I can see in syslog that the script is waiting the 60 seconds before running, but I get the same error message.
I could try other methods to automate the script, but I am interested in why the current method is not working as expected.
As Tim Roberts helped me learn, the rc.local script was running as root, but I had installed mysql under my user account. Running from rc.local, the script couldn't find the mysql package. I added sudo -H -u username when calling the python script in /etc/rc.local, and the script runs as expected.
Thank you to Tim Roberts.
for those interested in the full /etc/rc.local. Everything before the sleep statement was default.
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
printf "My IP address is %s\n" "$_IP"
fi
#make sure mysql has been initialized
sleep 15
#run python script as user pi with python3
#The ampersand allows the command to run in a separate process and continue booting with the process running.
sudo -H -u pi python3 /home/pi/python/switch_counter3.py &
exit 0

Script hangs while using Fabric's Connection.run() in the background

Overview
I'm trying to use python fabric to run an ssh command as root on a remote server.
The command: nohup ./foo &
foo is expected to command run for several days. I must be able to disassociate foo from fabric's remote ssh session, and put foo in the background.
The Fabric FAQ says you should use something like screen or tmux when you run your fabric script (which runs the backgrounded command). I tried that, but my fabric script still hung. foo is not hanging.
Question
How do I use fabric to run this command on a remote server without the script hanging: nohup ./foo &
Details
This is my script:
#!/bin/sh
# Credit: https://unix.stackexchange.com/a/20895/6766
if "true" : '''\'
then
exec "/nfs/it/network_python/$OSREL/bin/python" "$0" "$#"
exit 127
fi
'''
from getpass import getpass
import os
from fabric import Connection, Config
assert os.geteuid()==0, "ERROR: Must run as root"
for host in ['host1.foo.local', 'host2.foo.local']:
# Make an ssh connection to the host...
conn = Connection(host)
# The script always hangs at this line
result = conn.run('nohup ./foo &', warn=True, hide=True)
I always open a tmux session to run the aforementioned script in; even doing so, the script hangs when I get to conn.run(), above.
I'm running the script on a vanilla CentOS 6.5 VM; it runs under python 2.7.10 and fabric 2.1.
The Fabric FAQ is unclear... I thought the FAQ wanted tmux used on the local side when I executed the Fabric script.
The correct way to fix this problem is to replace nohup in the remote command, with screen -d -m <command>. Now I can run the whole script locally with no hangs (and I don't have to use tmux in the local term).
Explicitly, I have to rewrite the last line of my script in my question as:
# Remove &, and nohup...
result = conn.run('screen -d -m ./foo', warn=True, hide=True)

Python: How to execute a program over SSH that requires `sudo`

I need to run a deamon over a remote Linux machine, using SSH.
Deamon's name is pigpiod and it belongs to pigpio module ( controling Raspberry Pi's GPIO ), Ubuntu Mate 16.04.
Executing commands that does not require sudo (for example- ls)- script runs OK, while those who need sudo, fails.
adress='192.168.2.112' , is a remote Linux to run this daemon.
Code below fails (running sudo pigpiod):
def runpigpiod_remote(adress):
result = subprocess.run(['ssh','guy#'+adress,'sudo','pigpiod'])
Code below succeeds(run ls -l)
def runpigpiod_remote(adress):
result = subprocess.run(['ssh','guy#'+adress,'ls','-l'])
In order the check if subprocess.run capable of executing sudo+ command - I tryied localy on same machine and it succeeds:
def run_process():
try:
check_output(["pidof","pigpiod"])
print("pigpiod already loaded")
except:
subprocess.CalledProcessError
print("Not Loaded")
subprocess.run(['sudo','pigpiod'])
if os.system("pgrep -x "+name)==0:
print("Loaded successfully")
Code changed ( thanks to comment of #Hamuel )- as noted in proper way to sudo over ssh
def runpigpiod_remote(adress):
result = subprocess.run(['ssh','-t','guy#'+adress,'sudo','pigpiod'])

unix command execution with password via python

I am trying to connect to mysql in unix from a python script. I provided the password to connect to mysql in the script itself but terminal still prompts for the password. This is what i have till now:
import os
from subprocess import Popen, PIPE
passwd = "user"
command = "mysql -u root -p"
proc = Popen(command.split(), stdin=PIPE)
proc.communicate(passwd+'\n')[1]
Can any one suggest what am i doing wrong here. Or is there a better way to do this.
You can try this:
command = "mysql -u root -p" + passwd
I tried your script in Ubuntu 14.04. It is very easy to start a MySQL in terminal using shell script.
Here is the code..
#!/bin/bash
user=('root')
pass=('XXX')
mysql -u $user -p$pass
echo 'success'
Simply run this code & you can start the MySQL at terminal...

My Raspbian doesn't reboot via a Python application

I am desperately trying to find out a way to force my Raspberry Pi running Raspbian to restart when a certain condition is met (Python script), however I got no success so far...
I have tried the following statements by using popen:
sudo reboot -i -p
sudo reboot -f
sudo shutdown -r -f now
I thought the problem could be calling it through the Python application itself, therefore I wrote a small C program to kill all running Python application and then reboot, but no success...
My Raspberry is enough powered (Red LED is always on) and all commands I described above work fine when called directly from the command window.
Any help is appreciated!
Thanks,
EDITED:
Adding my python script as required:
from subprocess import Popen, PIPE
def reboot():
echo.echo("Rebooting...")
db.write_alarm(get_alarm_status())
upload.upload_log()
reboot_statement = "sudo shutdown -r -f now"
popen_args = reboot_statement.split(" ")
Popen(popen_args, stdout=PIPE, stderr=PIPE)
Try this:
create a file called reboot.py with the following contents:
import os
os.system("shutdown -r now")
then call it like this:
sudo python reboot.py
Assuming this works you can probably invoke your original script with sudo to get it to work.
You should pass shell=True id you want the shell to process the arguments
Popen("sudo shutdown -r -f now", stdout=PIPE, stderr=PIPE, shell=True)

Categories