"$" pass in shell exec - php

I am trying to write an application for Linux system user change password.
Here is the code for that:
shell_exec("/usr/bin/passwd ".$user." <<EOF\n".$password."\n".$password."\nEOF");
It take all the spacial characters accept "$"
How to pass "$" in shell_exec?
Thanks in advance.

you can escape it using \$ or include your string content inside single quote. as single quotes doesn't expand variables
shell_exec('/usr/bin/passwd $'.$user." <<EOF\n".$password."\n".$password."\nEOF");
alternatively you can also pass the command string to shellescapearg as follows
$arg = $user." <<EOF\n".$password."\n".$password."\nEOF";
shell_exec('usr/bin/passwd ' . $arg);

I do not think the error is related to the $ symbol. A code similar to yours worked just fine for me.
I used the following to test:
$msg = "Hello world"; shell_exec("notify-send ".$msg);

Related

Using PHP variable in system() function

I am currently using this command:
system('"C:/xampp/htdocs/csv/txtfiles/PSPPfile.txt"');
I want to having something like with having variable inside, for instance:
$file='txtfiles/PSPPfile.txt';
system('"C:/xampp/htdocs/csv/$file"');
Something like above, kindly help me out. Thanks!
Single quoted strings will display things almost completely "as is." Variables and most escape sequences will not be interpreted.
In other words, youre assigning the argument to system to read $file as is, not as what the variable contains.
Use double quotes to assert that variable gets replaced - or perform string concatenation :
system( 'c:/xampp/htdocs/csv/' . $file );
$file = 'txtfiles/PSPPfile.txt';
system('C:/xampp/htdocs/csv/' . $file);

How can execute php scripts in bash?

I need parse uri in shell scripts. So, I tried to use php in bash as below.
#!/bin/sh
uri="http://www.google.com?key=value
key="host"
value=$(php -r "$parse = parse_url('$uri'); echo $parse['$key']")
It has showing the following error.
PHP Parse error: syntax error, unexpected '=' in Command line code on line 1
Some body can help how to use embedded php in bash ?
A cheap way of debugging this is to use echo to see what you're passing in to php:
echo "$parse = parse_url('$uri'); echo $parse['$key']"
shows
= parse_url('http://www.google.com?key=value'); echo ['host']
You're already using $uri to mean "the value of the shell variable uri", so it's not surprising that $parse is also considered a shell variable and expanded to its value (unset, nothing).
Use \$ when you want a literal dollar sign in your double quoted string:
value=$(php -r "\$parse = parse_url('$uri'); echo \$parse['$key']")
You can use it easily, but you must be careful because of escaping in bash.
I recommend to use single quotes (you do not need to escape anything) and exit from the quotes when you want to do something special. Your example:
php -r '$parse=parse_url("'$url'"); echo $parse["'$part'"];'
Note that
you do not need to escapes $parse
you need to exit from single quotes when inserting bash variable: '$url'
you cannot use single quotes in the single quotes! do use double quotes " instead.
Update:
Just for the clarification - parse error happened because $parse was interpreted as bash variable (empty string) so the php command incorrectly started with =.

PHP SSH Lib, echoing to a file

I'm trying to create a PHP script that creates a file on a remote linux server through ssh, and echos the file contents into it.
However, I cannot figure out how to correctly and safely encode/escape the file contents, so that the contents don't get interpreted as commands.
I'm using phpseclib from here.
I've tried something like
echo $ssh->exec('sudo echo "' . escapeshellarg($newConfig) . '" > /etc/nginx/nginx.conf') . "\n";
but without success.
Thanks,
Steve
What about escapeshellcmd? Quoting the description of that vs escapeshellarg:
escapeshellarg() adds single quotes around a string and quotes/escapes
any existing single quotes allowing you to pass a string directly to a
shell function and having it be treated as a single safe argument.
...and...
escapeshellcmd() escapes any characters in a string that might be used
to trick a shell command into executing arbitrary commands. This
function should be used to make sure that any data coming from user
input is escaped before this data is passed to the exec() or system()
functions, or to the backtick operator.
Following characters are preceded by a backslash: #&;`|*?~<>^()[]{}$\,
\x0A and \xFF. ' and " are escaped only if they are not paired. In
Windows, all these characters plus % are replaced by a space instead.
I was going about this all wrong, I should have used Net_SFTP instead of NET_SSH for this sort of thing.

How do I let PHP echo "\n" as plain-text for javascript and not have the "\n" create a new line?

PHP is echoing JavaScript (I'm using the jQuery library) something like this:
echo 'var users = $("#add").val().split("\n");';
However, the \n is creating a line break in what the echoed script looks like, and therefore breaking the JavaScript. Is there a way to circumvent this?
Many thanks!
The \n is an escape sequence meaning newline. Backslashes are the beginning of escape sequences, to output a backslash then write \\. So you want \\n. Other useful escape sequences include the quote: use \" to put a quote into the string instead of ending the string.
echo "var users = $(\"#add\").val().split(\"\\n\");";
Not sure If you looking for this
echo "<script>alert('Line1\\\\nThis still in Line1')</script>";

PHP exec() and spaces in paths

I'm executing the following in a PHP application:
$source = '/home/user/file.ext';
$output_dir = $this->setOutputString();
chdir('/home/ben/xc/phplib/bgwatcher-2011a/a01/');
exec('php bin/createjob.php $source $output_dir', $output);
return $output[0];
The problem is this: I have control over $source, but not $output_dir, which is a legacy Windows filesystem, and there are spaces in the path. An example $output_dir is:
/home/vol1/district id/store id/this_is_the_file.html
When inserting the output string into the exec() function, I have tried both:
addslashes($output_dir) and '"' . $output_dir . '"' to escape the entire output string. In the first case, the path gets concatenated to:
/home/vol1/districtthis_is_the_file.html
... where everything between the first space and the filename gets dropped. In the second case, exec() appears to throw a shoe and doesn't execute properly - unfortunately, the error message is getting lost in the machinery - I can provide it if it's absolutely necessary, but I'm also under time constraints to find a solution.
What's the solution, here? Do I sprintf() the entire string for exec()? I'm very confused as to why addslashes isn't working correctly to escape the spaces, and I assume it has something to do with sanitization with exec(), but I can't find any documentation to back it up.
Update: I've tried escapeshellarg() and preg_replace() without success. Thinking about this further, do I need to double-escape the path? Or escape the path and the command? If the path is being unescaped once by exec(), and once by PHP before it executes the command, does it stand to reason that I need to account for both escapes? Or is that not how it works?
I don't believe addslashes() does anything with spaces. escapeshellarg() might be what you want instead. Docs on escapeshellarg
From the PHP doc (here),
Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash () and NUL (the NULL byte).
This won't do anything to the spaces. What you will need to do is use str_replace() to add slashes, like this:
$new_string = str_replace(" ", "\\ ", $old_string);
According to the PHP docs,
Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash () and NUL (the NULL byte).
Looks like you'll have to preg_replace the spaces yourself.
Edit:
Even though this is the topic of another discussion, if performance is an issue, then after looking into it a little more, it seems that str_replace is actually quite a bit faster than preg_replace:
The test labeled "str_replace()" was
the faster by 0.9053 seconds (it took
10.3% the time.)
The first test took 1.0093 seconds. (preg_replace)
The second test took 0.104 seconds. (str_replace)
Benchmark found here.
I've used exec() with paths with spaces before, on both Windows and Linux hosts, and in both cases quoting the path worked perfectly for me.
That said, if you have no control over the safety of a shell argument, always run it through escapeshellarg() first!
You can very well use shell quotes, since that is what all exec commands run through:
exec("php bin/createjob.php '$source' '$output_dir'", $output);
It btw works not just for arguments, but also for the command itself:
exec('"/bin/echo" "one parameter"');
Use escapeshellcmd() anyway.
this works for me when using exec() with soffice(LibreOffice):
$file_name = "Some, file name.xlsx";
exec('/usr/bin/soffice --headless --convert-to pdf '."'".$file_name."'".' 2>&1', $output, $r);
You can use double quotes and escape character together to work out this.
$fileName = "filename with spaces.pdf";
exec("php bin/createjob.php >\"".$fileName."\" 2> error.log" , $output, $return);

Categories