Can't run Linux "awk" command in script from PHP

Viewed 626

I have the shell script "test.sh":

  #!/system/bin/sh

  PID=$(ps | grep logcat | grep root |grep -v grep | awk '{print $2}')
  echo "Using awk: $PID"


  PID=$(ps | grep logcat | grep root |grep -v grep | cut -d " " -f 7 )
  echo "Using cut: $PID"

When I run the script from PHP:

exec("su -c sh /path/to/my/script/test.sh");

I got this output:

Using awk:
Using cut: 6512  

So "cut" command is work but "awk" command doesn't when I run the script from PHP, but when I run it from terminal:

# sh test.sh

I can get both awk and cut work fine! This how look like the output of "ps":

USER      PID   PPID  VSIZE  RSS   WCHAN       PC         NAME
root      6512  5115  3044   1108  poll_sched b6e4bb0c S logcat

Do I missed something?

1 Answers

You should learn how to debug first

You said

So "cut" command is work but "awk" command doesn't when I run the script from PHP, but when I run it from terminal:

I wonder how ?

actually throws error like below, in CLI

$ php -r 'exec("su -c sh /path/to/my/script/test.sh");'
su: user /path/to/my/script/test.sh does not exist

You first need below syntax while debugging code

// basic :  stdin (0) stdout (1) stderr (2)

exec('your_command 2>&1', $output, $return_status);

// to see the response from your command
// su: user /path/to/my/script/test.sh does not exist
print_r($output);  

Remember :

  • su gives you root permissions but it does not change the PATH variable and current working directory.

  • The operating system assumes that, in the absence of a username, the user wants to change to a root session, and thus the user is prompted for the root password

[akshay@localhost Desktop]$ su
Password: 
[root@localhost Desktop]# pwd
/home/akshay/Desktop
[root@localhost Desktop]# exit
exit

[akshay@localhost Desktop]$ su -
Password: 
[root@localhost ~]# pwd
/root

Solution:

You should allow executing your script without password prompt ( don't use su use sudo )

To allow apache user to execute your script and some commands you may make entry like below in /etc/sudoers

# which awk => give you awk path
# same use in your script also, or else set path variable 
www-data ALL=NOPASSWD: /path/to/my/script/test.sh, /bin/cut, /usr/bin/awk

So it becomes :

// assuming your script is executable 
exec("sudo /path/to/my/script/test.sh 2>&1", $output);
print_r($output);  
Related