Want to pass parameter in bash file through php file - php

PHP code:
$number_server = 10;
exec("/bin/bash wrun.sh $number_server",$wuptime);
Bash script:
#!/bin/sh
for i in `seq echo $1`; do
ssh /usr/local/bin/wrun 'uptime
ps -elf | grep httpd | wc -l
free - m;mpstat'
done &
pid=$!
sleep 3
kill -9 $pid && echo "not respond in give time"
In this I want to pass the argument $number_server to the bash script from the php file.

#!/bin/sh
for i in `seq $1`; do

Related

shell_exec won't stop even though add new shell_exec to stop the other one

I've got a PHP script that needs to run the .sh file using shell_exec
echo shell_exec('sh /var/www/html/daloradius/start.sh > /dev/null 2>/dev/null &');
I just dump it into background. This is my start.sh
sudo tcpdump port 1812 -w testing.pcap
we know that tcpdump always listen all the time, I tried to resolve this (stop the tcpdump process) with the button that triggering another shell_exec which is stop.sh
pid=$(ps aux | grep "sudo tcpdump" | head -1 | cut -d '.' -f 1 | cut -d ' ' -f 7)
sudo kill $pid
Stop.sh is doing fine when I tested it in cli, but when I click the button that triggering start.sh and I tried to stop it with the button that triggering stop.sh it doesn't work. The tcpdump won't stop, but when I try to stop it in cli using stop.sh it's work well. Can anybody gimme solution to force stop the tcpdump things? Thank you
You are trying to use bash when you should be orchestrating the process from php.
Here, we get the PID of the command and kill it from PHP. Replace the sleep statement with whatever code you have.
<?php
# Script must be run with sudo to start tcpdump
# Be security conscious when running ANY code here
$pcap_file = 'testing.pcap';
$filter = 'port 1812'
$command = "tcpdump $filter -w $pcap_file" . ' > /dev/null 2>&1 & echo $!;';
$pid = (int)shell_exec($command);
echo "[INFO] $pid tcpdump: Writing to $pcap_file\n";
# Some important code. Using sleep as a stand-in.
shell_exec("sleep 5");
echo "[INFO] $pid tcpdump: Ending capture\n";
shell_exec("kill -9 $pid");
Please note that tcpdump has the -c option to stop ofter n packets received and you can rotate files with -G. You may want to read up on tcpdump's manpage to get the most out of it.

execute bash if else command in php ( bash vs php )

What i want to achieve
I want to execute some script it it's process in not started on the server. so for that i am preparing the command in shell script and executing it in single line.
Command with php variable
$cmd = "if [[ `ps auxww | grep -v grep | grep ".$process_file." | grep '".$find."'` == '' ]] ; then ".$cmd2." fi";
echo $cmd."\n";
Executed command, once variables are replaced (what will actually run on bash):
if [[ `ps auxww | grep -v grep | grep /home/new_jig.php | grep 'test_51 1714052'` == '' ]] ; then php /home/new_jig.php test_51 1714052 & fi;
executing command
exec($cmd,$out,$res);
Please note that, I have also split the problem in to two statement and execute those. But it is time consuming. It is causing problems when I have more than 2000 in list, and the command is executed for all. This takes about 1 or more than 1 minute to reach to the last number.
I want to achieve this within 10 seconds. Please help me to reach optimum output.
Thanks
Jignesh
somehow I am able to make it execute with the following command
$process_file = phpfile which executing some functionality
$cmd2 = " php ".$process_file." 1212 >/dev/null 2>/dev/null & ";
$cmd11 ="if ps -auxw | grep -v grep | grep '".$process_file."' | grep '".$find."' &> /dev/null ; then echo 1;".$cmd2."; fi";
shell_exec($cmd11." >/dev/null 2>/dev/null &");
Before this: for 1100 request the process was taking about 60+ seconds
After this: it is getting completed between 20 to 30 seconds

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

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?
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);

Argument pass through php into bash file not working

In my script I pass two argument into Bash file through PHP file.
PHP File:
$number_server = 7;
$server_name = "dbfs";
exec("/bin/bash drun.sh $number_server $server_name",$db_uptime);
foreach($db_uptime as $dbm_load){
echo $dbm_load."<br />";
}
Bash File:
#!/bin/sh
for i in seq $1; do ssh $2$i 'uptime;free -m;mpstat;cat /tmp/db2.info'; done &
pid=$!
sleep 2
kill -9 $pid
According to this it will show 7 records,but actually it shows only one record.Means FOR loop in Bash script runs only one time and second argument pass into bash is not working.
You BASH script seems to be wrong. Replace that with:
#!/bin/bash
for ((i=0; i<$1; i++)); do
ssh "$2$i" 'uptime;free -m;mpstat;cat /tmp/db2.info'
done &
pid=$!
sleep 2
kill -9 $pid

Really daemonize a command when using exec()?

From PHP pages of my apache server, I run some commands using a line like :
exec("{$command} >> /tmp/test.log 2>&1 & echo -n \$!");
You can see an explaination of the arguments here.
But I don't understand something : if I restart or stop my apache server, my command dies too.
root#web2:/sx/temp# ps ax | grep 0ff | grep -v grep
15957 ? S 0:38 /usr/bin/php /sx/site_web_php/fr_FR/app/console task:exec /sx/temp/task_inventaire/ 0ff79bf690dcfdf788fff26c259882e2d07426df 10800
root#web2:/sx/temp# /etc/init.d/apache2 restart
Restarting web server: apache2 ... waiting ..
root#web2:/sx/temp# ps ax | grep 0ff | grep -v grep
root#web2:/sx/temp#
After some researches, I read some things about parent pids, but using a & inside my command-line, I thought I was really detaching my child process from his parent.
I am using apache2 with libapache2-mod-php5 and apache2-mpm-prefork.
How can I really detach my children programs from apache?
edit
You can reproduce it on a Linux/Mac this way :
a) create a executed_script.php file that contains :
<?php
sleep(10);
b) create a execute_from_http.php file that contains :
<?php
exec("php executed_script.php > /tmp/test.log 2>&1 & echo -n \$!");
c) run http://localhost/path/execute_from_http.php
d) on a terminal, run the command :
ps axjf | grep execute | grep -v grep ; sudo /etc/init.d/apache2 restart ; ps axjf | grep execute | grep -v grep
If you run the command during the 10 secs of the execute_from_http.php script, you'll get the output :
php#beast:/var/www/xxx/$ ps axjf | grep execute | grep -v grep ; sudo /etc/init.d/apache2 restart ; ps axjf | grep execute | grep -v grep
1 5257 5245 5245 ? -1 S 33 0:00 php executed_script.php
* Restarting web server apache2
... waiting ...done.
php#beast:/var/www/xxx/$
As you can see, the ps command outputs only once, this tells you that the executed script died when apache restarted.
The "at" method
I found a working solution but I don't know if that's ok if we speak performance and security. It uses the at command, a kind of cron working only once.
Instead of :
exec("php executed_script.php > /dev/null 2>&1 & echo -n \$!");
Use :
exec("echo 'php executed_script.php > /dev/null 2>&1' | at now -M");
The key is that executed_script.php will be run by an external daemon (atd), so executed_script.php will be a child of atd and not an apache's one.
php#beast:/var/www/xxx$ ps axjf | grep execute | grep -v grep ; sudo /etc/init.d/apache2 restart ; ps axjf | grep execute | grep -v grep
7032 7033 973 973 ? -1 SN 33 0:00 \_ php executed_script.php
* Restarting web server apache2
... waiting ...done.
7032 7033 973 973 ? -1 SN 33 0:00 \_ php executed_script.php
php#beast:/var/www/xxx$ ps ax | grep 973
973 ? Ss 0:00 atd
Note several things :
you can't access the pid of your ran app, if you get $! like on my previous pieces of code, you'll get the pid of at.
you need to remove www-data which is by default in /etc/at.deny (it is probably there with reasons, so take care)
i have serious doubts about performance : I think that at write on a file read by atd to communicate
The fork / setsid method
As #hek2mgl wrote in its own answer, we can use a pcntl_fork(), but that's not as simple as that. First, you can't run pcntl_fork() behind apache, because if we look at the PHP Manual, Introduction of the Process Control, we can see:
Process Control should not be enabled within a web server environment
and unexpected results may happen if any Process Control functions are
used within a web server environment.
When a fork is made, you get two exact copy of the parent process in memory. And because PHP behind apache is run as a module, at the end of the PHP execution (even after a die()), you come back to the apache's module wrapper, and you can't control what's going on.
So here is the scenario with an intermediate command that will daemonize your execution:
1) From Apache, you run the intermediate command that will create your daemonized command :
$command = escapeshellarg("php executed_script.php");
exec("php run_as_daemon.php {$command} >> /dev/null 2>&1 &");
2) The intermediate command fork and use posix_setsid to really detach your command.
<?php
if (!isset($argv[1]))
{
exit;
}
$command = $argv[1];
$pid = pcntl_fork();
if ($pid < 0) // error
exit;
else if ($pid) // parent
exit;
else // child
{
$sid = posix_setsid(); // creates a daemon
if ($sid < 0)
exit;
exec("{$command} >> /dev/null 2>&1 &");
}
3) Your executed command, of course, doesn't change :
<?php
sleep(10);
Result :
php#beast:/var/www/xxx/$ wget -qO- http://localhost/xxx/execute_from_http.php && sleep 1 && ps axjf | grep execute | grep -v grep ; sudo /etc/init.d/apache2 restart ; ps axjf | grep execute | grep -v grep
1 19958 19956 19956 ? -1 S 33 0:00 php executed_script.php
* Restarting web server apache2 ......done.
1 19958 19956 19956 ? -1 S 33 0:00 php executed_script.php
First note, that the '&' in your example is just a boolean AND that concats the command and the echo. If you want to start the command in background, meaning that exec will return immediately, use the & at the very end of the command line:
exec("{$command} >> /tmp/test.log 2>&1 & echo -n \$! &");
If you want the process running after apache has finished you'll have to daemonize the process using pcntl_fork()
Here comes an example:
$pid = pcntl_fork();
switch($pid) {
case -1 : die ('Error while forking');
case 0: // daemon code
posix_setsid(); // create new process group
exec("{$command} >> /tmp/test.log 2>&1 & echo -n \$!");
break;
default:
echo 'daemon started';
break;
}
Now there is no code in the starting PHP scripts that handles the return value of exec nor its output. So the current process can finish before exec has finished. The worker process will be owned by init after this.
Also you can have a look at the PEAR package System_Daemon. This can help to daemonize a script.

Categories