I want to execute a shell script from a php page that will execute a MySQL command.
To do this, I went as follows: stack overflow
Here is my sqlscript.sh
#!/bin/sh
sudo wget -t 50 -O /tmp/update.sql http://example.com/update.sql
if [ $? -eq 0 ]; then
mysql -h "localhost" -u "root" "-pXXXXXXXX" "database-name" < "/tmp/update.sql"
if [ $? -eq 0 ]; then
sudo rm /tmp/update.sql
echo "200"
else
echo "502"
fi
else
echo "404"
fi
And my php page runscript.php
<?php
shell_exec("sudo /path/to/script/sqlscript.sh");
?>
Now, when I call sqlscript.shfrom the server console or php page runscript.php , it works fine and returns 200as expected.
But when I take the MYSQL user and password in ~/.my.cnf, so I don’t need to paste it on the command line:
[client]
user = root
password = XXXXXXXX
And added credentials in sudoerto run this script without a password.
User_Alias WWW_USER = www-data
Cmnd_Alias WWW_COMMANDS_SQL = /path/to/script/sqlscript.sh
WWW_USER ALL = (ALL) NOPASSWD: WWW_COMMANDS_SQL
Here is my sqlscript.sh
#!/bin/sh
sudo wget -t 50 -O /tmp/update.sql http://example.com/update.sql
if [ $? -eq 0 ]; then
mysql -h "localhost" "database-name" < "/tmp/update.sql"
if [ $? -eq 0 ]; then
sudo rm /tmp/update.sql
echo "200"
else
echo "502"
fi
else
echo "404"
fi
, sqlscript.sh , 200, . php-
http:
502, SQL.
Update:
Apache error.log
Resolving example.com (example.com)... 162.144.71.XXX
Connecting to example.com (example.com)|162.144.71.XXX|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 146 [text/x-sql]
Saving to: `/tmp/update.sql'
0K 100% 10.9M=0s
2014-12-05 10:51:55 (10.9 MB/s) - `/tmp/update.sql' saved [146/146]
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
, .