简体   繁体   中英

Execute Bash Script from PHP

I am calling a bash script from PHP, but I have experienced a strange issue that only specific parameter value passed to bash can be successfully executed:

My PHP code is simple:

$result = shell_exec("/scripts/createUser.sh $uname");

Bash script code:

#!/bin/bash

export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

usrname=$1
echo -e "Username: $1"

deploy="/wordpress.tar.gz"
dest="/data/$usrname"

mkdir -p $dest

cd $dest

tar zxvf $deploy -C $dest >/dev/null 2>&1

ls $dest

However this script can only successfully mkdir, extract the wordpress.tar.gz and list the folder when $uname == 'test' , otherwise nothing happen (even cannot mkdir).

I chown the script to www user and grant execution permission, no help. And already tried run these commands via console as root, they run fine:

/scripts/createUser.sh admin
php deploy.php // in this script $uname == 'admin'

How could this happen? Thanks for your idea!

I recently published a project that allows PHP to obtain and interact with a real Bash shell (as root if requested), it solves the limitations of exec() and shell_exec(). Get it here: https://github.com/merlinthemagic/MTS

After downloading you would simply use the following code:

$shell    = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', false);
$return1  = $shell->exeCmd("/scripts/createUser.sh " . $uname);
//the return will be a string containing the return of the command
echo $return1;

But since you are simply triggering a bunch of bash commands, just issue them one by one using this project. That way you can also handle exceptions and see exactly which command returns something unexpected, ie permissions issues.

For commands that run for a long time you will have to change the timeout:

//is one hour enough?
$timeout = 3600000;
$return1  = $shell->exeCmd("/scripts/createUser.sh " . $uname, null, $timeout);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM