skip to Main Content

I have a sh script that works fine when I run it at command line with root user. This creates a database and a user with password.

$ ./create-database.sh dbname dbuser dbpass

    #!/bin/bash
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>log.out 2>&1
# Everything below will go to the file 'log.out':

# Functions
ok() { echo -e 'e[32m'$1'e[m'; } # Green

EXPECTED_ARGS=3
E_BADARGS=65
MYSQL=`which mysql`

Q0="DROP DATABASE IF EXISTS $1;"
Q1="CREATE DATABASE IF NOT EXISTS $1;"
Q2="GRANT ALL ON $1.* TO '$2'@'localhost' IDENTIFIED BY '$3';"
Q3="FLUSH PRIVILEGES;"
SQL="${Q0}${Q1}${Q2}${Q3}"

if [ $# -ne $EXPECTED_ARGS ]
then
  echo "Usage: $0 dbname dbuser dbpass"
  exit $E_BADARGS
fi

$MYSQL -u root -pXXXXXXX -e "$SQL"

ok "Database $1 and user $2 created with a password $3"

The same file when I run using php it doesn’t work. The PHP code is as below in the same folder as that of sh file.

    <?php

$db_name = $_GET['db_name'];
$db_user = $_GET['db_user'];
$db_pass = $_GET['db_pass'];

$output = shell_exec ("sh ./create-database.sh $db_name $db_user $db_pass");

echo "Output $output";

the PHP Script has 777 permissions and is running in an application owned by user pakerp

The log.out file gives me the following error

ERROR 1698 (28000): Access denied for user ‘root’@’localhost’

While the same script is working fine when I run at command line.

What am I missing. Please tell me.

2

Answers


  1. use one of following commands:

    $MYSQL –host=localhost –user=root –password=XXXXXX -e $SQL

    or

    $MYSQL –host={{IP}} –user=root –password=XXXXXX -e $SQL

    enter your machine ip instead of {{IP}}. if your machine is localhost, add 127.0.0.1 as IPv4 or ::1 as IPv6

    Login or Signup to reply.
  2. You might need to allow root on localhost or better use a non root user!

    Seems the same as this issue

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search