Passing arguments from PHP to a remote shell script - php

I am executing a shell script located on a remote machine from a PHP script. So, let's say that PHP script runs on A and shell script runs on B (10.0.0.37).
I have the following code which runs well
$cmd = "ssh 10.0.0.37 /usr/tmp/script.sh";
exec($cmd, $output);
Now, I want to pass arguments to the shell script, preferably in JSON format.
The output of echo json_encode($arg) is as follows:
[{"original_name":"pdf_convert","changed_name":"pdf_convert_1"},{"original_name":"video_encode","changed_name":"video_encode_1"},{"original_name":"video_transcode","changed_name":"video_transcode_1"}]
I want to pass this as an argument to the shell script. So,
$data = json_encode($data);
$cmd = "ssh 10.0.0.37 /usr/tmp/script.sh $data";
exec($cmd, $output);
However, I see that the argument is not correctly read by the shell script. I tried putting single quotes around $data, didn't work. Also, tried using escapeshellarg($data), still did not work.
Edit
The output of echo escapeshellarg($data) is
'[{"original_name":"pdf_convert","changed_name":"pdf_convert_1"},{"original_name":"video_encode","changed_name":"video_encode_1"},{"original_name":"video_transcode","changed_name":"video_transcode_1"}]'
Also, if there is any other format which can be parsed easily in a shell script, then I would lie to use that format (not necessarily JSON). I see that I may have to use 'jq' to parse json which needs me to install an additional package.

Bash isn't very good at accepting a JSON string in as arguments...
One way to get around bash trying to parse the arguments is for your php script to write the JSON string to a file, and for the bash script to parse that file with jq

I was able to use serilaize to send the json data. Below is the code.
$data = json_encode($arg)
$data = escapeshellarg($data);
$data = serialize($data);
$data = str_replace('"','\"',$data);
$cmd = "ssh 10.0.0.37 /usr/tmp/script.sh $data";
I can now get the data in the shell script.

PHP:
<?php
$json = '[{"original_name":"pdf_convert","changed_name":"pdf_convert_1"},{"original_name":"video_encode","changed_name":"video_encode_1"},{"original_name":"video_transcode","changed_name":"video_transcode_1"}]';
$cmd = $json;
$cmd = addslashes($cmd);
// addslashes does not escapes curly braces
$cmd = strtr($cmd, array('{' => '\\{', '}' => '\\}'));
$cmd = escapeshellarg($cmd);
$cmd = "ssh localhost echo $cmd";
echo "\n$cmd\n\n";
exec($cmd, $output);
var_dump($output)
Shell (/tmp/1.sh):
#!/bin/sh
echo "$1"
Shell Output:
ssh localhost /tmp/1.sh '[\{\"original_name\":\"pdf_convert\",\"changed_name\":\"pdf_convert_1\"\},\{\"original_name\":\"video_encode\",\"changed_name\":\"video_encode_1\"\},\{\"original_name\":\"video_transcode\",\"changed_name\":\"video_transcode_1\"\}]'
array(1) {
[0]=>
string(200) "[{"original_name":"pdf_convert","changed_name":"pdf_convert_1"},{"original_name":"video_encode","changed_name":"video_encode_1"},{"original_name":"video_transcode","changed_name":"video_transcode_1"}]"
}

Related

PHP exec returns empty string while executing Python script

I am trying to run a Python script inside PHP and show the output.
I tried with simple test.py inside PHP, which print hello world without problem. But when I try to execute my desired command from PHP script the exec() returns empty string instead of output.
So the here is my php script. Below snippets works fine:
$output = exec("python test.py");
var_dump($output);
But not the desired one.
$command = "python -m scripts.label_image --graph=tf_files/retrained_graph.pb --image=".$uploadfile;
$output = exec($command);
var_dump($output);
so the folder structure is:
/var/www/mysite/
-scripts(folder which contains python scripts)
-tf_files(folder with other files)
-uploads (image folder)
Can someone tell me what is going wrong?
Sample output in stdout/shell:
the variable $output should an argument.
If you do this, you should get only the last output of your script.
exec("python test.py", $output);
var_dump($output);
https://www.php.net/manual/en/function.exec.php

Execute external program with PHP and arguments

I wish to run external program with PHP and provide some arguments, like:
exec('C:\\Program Files\\iNFekt\\infekt\\infekt-cmd.exe -S --utf-16 '.$nfoFile, $output, $return_var);
But nothing happens, $output is empty array, $return_var is 1
What is my mistake here ?
Use shell_exec to get the output:
$output = shell_exec('C:\\Program Files\\iNFekt\\infekt\\infekt-cmd.exe -S --utf-16 '.$nfoFile');
From the Manual:
shell_exec — Execute command via shell and return the complete output as a string

GetOpt doesn't read full URL

I have a script that need to run from a terminal or a command prompt. I'm using PHP. GetOpt is the function that I use to get data or a parameter that the user input in the terminal.
This is my script.
<?php
$opt = getopt("f:");
$input = $opt['f'];
$u = fopen($input, 'r');
echo "\n\n$input\n\n";
I tried to run it like this:
$ php myscript.php -f http://myurl.com/file.csv?city=london&status=3
My url is http://myurl.com/file.csv?city=london&status=3, but it only outputs http://myurl.com/file.csv?city=london. The status parameter is lost from the full URL.
How can I get this to work?
it's because you have to wrap your link around into quotes:
$ php myscript.php -f "http://myurl.com/file.csv?city=london&status=3"
I'll go ahead and assume you are running your script in Bash, and & in Bash might be interpreted as bitwise AND in your case:
$ echo $(( 98 & 7 ))
2

How to properly call Python 3 script from PHP?

I would like to call a Python 3 script (with arguments) from PHP and process the returned information.
//server.php
arg1 = $_POST['arg1'];
arg2 = $_POST['arg2'];
args = array(arg1,arg2);
//pseudo code - THIS IS WHERE MY QUESTION IS
//$results = call_python3_script_somehow
echo $results
#script.py
import MyProcess
#take in args somehow
args = [arg1,arg2]
result = MyProcess(args)
return result
The problem is this has been asked many times on Stack Overflow, and there are different answers each one:
The execute function (here and here)
$output = array();
exec("python hi.py", $output);
var_dump( $output);
The escape shell function (here)
$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;
The shell execute function (here)
// This is the data you want to pass to Python
$data = array('as', 'df', 'gh');
// Execute the python script with the JSON data
$result = shell_exec('python /path/to/myScript.py ' . escapeshellarg(json_encode($data)));
The system function (here)
$mystring = system('python myscript.py myargs', $retval);
All of these answers are accepted and have a decent number of upvotes. Which, if any of these, is the proper way to call a Python script from PHP?
They all do the same thing but have some different output. I would suggest to use the one that best fits your scenario.
I often use shell_exec because it's easier for me on debugging since I all I need to do is just print a string out in <pre> tags. There's one thing that people tend to forget, especially when they are trying to debug stuff. Use: 2>&1 at the end of the script and the args. Taking one of the examples you have above, it would look something like this:
shell_exec('python /path/to/myScript.py ' . escapeshellarg(json_encode($data)) . " 2>&1");
This allows you to view error output as well, which is more than likely what you'll need to figure out why it's working on the command line, but it's not working when you run it from PHP.

How can we execute linux commands from php programs?

I want to see the output of the following code in the web browser:
code:
<?php
$var = system('fdisk -l');
echo "$var";
?>
When I open this from a web browser there is no output in the web browser. So how can I do this? Please help!
Thanks
Puspa
you can use passthru, like so:
$somevar = passthru('echo "Testing1"');
// $somevar now == "Testing1"
or
echo passthru('echo "Testing2"');
// outputs "Testing2"
use exec('command', $output);
print_r($output);
First of all, be sure that you (=user under which php runs) are allowed to call the external program (OS access rights, safe_mode setting in php.ini). Then you have quite a few options in PHP to call programs via command line. The most common I use are:
system
This function returns false if the command failed or the last line of the returned output.
$lastLine = system('...');
shell_exec or backtick operators
This function/operator return the whole output of the command as a string.
$output = shell_exec('...'); // or:
$output = `...`;
exec
This function returns the last line of the output of the command. But you can give it a second argument that then contains all lines from the command output.
$lastLine = exec('...'); // or capturing all lines from output:
$lastLine = exec('...', $allLines);
Here is the overview of all functions for these usecases: http://de.php.net/manual/en/ref.exec.php

Categories