php exec not returning full output - php

I am executing a bunch of ssh commands with php's exec. All of them seems to work correctly except one of them:
$command = 'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no user#127.0.0.1 "verify /md5 filename"';
exec($command, $output);
These commands are being executed on a Cisco router if that makes any difference.
The output is about 99% completed however it gets cut off at the end. I don't receive the last line at all and the second to last line always gets cut off after the 1st character. I also tried passtru and got the same results.
I've also tried adding 2>&1 to the end of the command and it made no difference. Anyone know what is going on here or have any ideas?
Here are the last 2 lines. This is what I expect:
..........Done!
verify /md5 (flash:filename) = 8743b52063cd84097a65d1633f5c74f5
I get
.
Also, running this on command line works perfectly. I have seen others with similar issues but there wasn't really any solution. This is on php 5.3.3.
I have a little more information to add to this. I created a separate script that only called the exec and this command and got the same output. This rules out any thing else in my file or the framework I'm using.
I also ran the new script from command line and it worked perfectly. Running the script in the browser however returns the bad results.
I can verify that it has something to do with how the data is being returned and those dots. The ...... must load in a way that PHP doesn't like and it thinks the command is done.

Related

PHP execute SSH2 command

I'm having some problems with PHP SSH2 commands.
So I have succesfully connected my dedicated server with my app, but I have no idea how to run command with that.
I'm using phpsclib ( http://phpseclib.sourceforge.net ), when I write something like
echo $ssh->read('username#username:~$');
$ssh->write("ls -la\n");
echo $ssh->read();
It will give me a list from root, but the problem is I don't want to be in root.
I need to cd /another_file and execute command that will start some game server.
I tried something like
$ssh->write("cd /another_file");
$ssh->write("my command here");
But no success, it's showing commands in same line.
Any ideas how to do that?
You have several options.
Chain the commands using $ssh->write():
$ssh->write("cd /another_file && ls -la\n");
...or...
$ssh->write("cd /another_file; ls -la\n");
Chain the commands using $ssh->exec(). Works much the same way as above except that you don't need to append \n to your command and you don't need to bother with the $ssh->read().
Do multiple $ssh->write() calls, which is what your current attempt is attempting to do. But it's doing it wrong:
$ssh->write("cd /another_file");
$ssh->write("my command here");
In your first code snippet you're appending a \n but you're not doing so on these lines. You need to because, when you're in an interactive shell, the way the shell knows that you're done typing the command out is because you hit the enter button. That's how Linux knows you're done typing and are ready for your command to run.
You also need to read the prompt before running the next command. eg. $ssh->read('[prompt]') or whatever is appropriate for your system. I suppose you could just omit passing a parameter to $ssh->read() all together, as you do in your first code snippet, but then it'll take 10s or so for $ssh->read() to return any output when it could have alternatively been returning output instantly.

Running PHP script on Perl or sh error. Not found

I'm currently running a cron job that loads a php script.
I keep getting an error, sh 1 /usr/bin/php: not found.
I tried it two other ways but to no avail.
on a perl script. I tried.
my $x = qx('/usr/bin/php /home/script.here');
This doesn't generate anything and sends me an error message on my mail.
But if I run the line
/usr/bin/php /home/script.here
on my shell, it works.
I also create a script 1.sh and had this.
#!/usr/bin/php -v
I run the script ./1.sh and it shows the result. But as soon as I try to call it via cron or /bin/sh 1.sh, it just fails and can't find the php path even if it was explicitly stated.
Am I missing anything?
I also tried this on php5, but same error.
The problem are the single quotes inside the qx() operator. Remove them:
my $x = qx(/usr/bin/php /home/script.here);
As long as they are there the shell tries to find a command "script.here" in the directory "/usr/bin/php /home" (yes, with the space in the directory name).
Totally forgot about this question.
Found a solution.
I just added
SHELL=/bin/bash in crontab and the scripts worked.

php exec() is not executing the command

I have tried to use exec() with 'whoami' to check if it works and I got the result of
nt authority\system
Now I need to run a .exe file with parameters from php via exec() function.
I tried this in command prompt and it actually runs the program with given parameters. This is the example command.
NOTE the exe file gets 3 inputs (folder, file_name, report_file_nmae)
> ..\..\some_file.exe folder="C:\path_to_folder" param=1.xml report=2.xml
But when I run this command from php file:
exec('..\..\some_file.exe folder="C:\path_to_folder" param=1.xml report=2.xml');
nothing is happening. This is the first time I am using exec() function, so I am not familiar with its details. What is wrong?
I tried using:
\\ instead of \
escapeshellarg() on the directory
added "" around directory folder names
No luck
Addendum:
echo exec($command) // echos < .... why?
or
exec($command, $output);
print_r($output); // Array()
I even changed the permission on the file to full control to all users.
If I call the program from command prompt, I can see the icon appearing next to clock for a second.
But the same call from php will not even call the program.
Edit
Even exec('notepad.exe'); is not working. Something has to be done with php configurations maybe?
I already said that I was new to exec() function. After doing some more digging, I came upon 2>&1 which needs to be added at the end of command in exec().
Thanks #mattosmat for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.
So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.
For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.
exec('some_command 2>&1', $output);
print_r($output); // to see the response to your command
Thanks for all the help guys, I appreciate it ;)
You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick.

PHP exec(psexec.exe) hangs indefinitely

I have a development / testing setup on a windows box and need to test calling a background process. I am using http://www.somacon.com/p395.php as a list of options for running a background service.
Here is the sample code I am trying to run:
$string = "PsExec.exe -d cmd /c \"mspaint\"";
echo $string;
exec($string, $data);
This works when I type it into the command line.
I haven't attempted to do a lot of exec's on Windows, but it would be nice to be able to test it locally before moving to a Linux box.
Right now, I am thinking it has something to do with the fact that psexec opens a new window? I don't know how to fix that, however.
There are no apache or PHP error logs being generated, the page just never stops. This also seems to override PHP's max execution time.
EDIT:
This is not fully correct answer. The command psexec \\machine cmd.exe /C 1 & dir won't hang because psexec first return saying that command 1 doesn't exists in remote machine and then dir is evaluated in the local machine. I got tricked by cmd operator order. The & operator is being invoked in the local cmd.exe process, not the remote one. But the logic still applies if you quote the command: psexec \\machine cmd.exe /C "1 & dir".
Original Answer:
There is something strange going on while invoking psexec within PHP in windows. No matter if you are using shell_exec(), exec(), popen() or proc_open(). It will hang anyway.
Honestly I don't know what's going on, you could also download PsExplorer in order to trace your process command line, arguments, etc. You'll find this tool very useful.
I'm using XAMPP on Windows, and after certain tests I found this:
First of all create a test file (i.e. test.php) and place it in your web server so you can access it with this content:
<?php
echo "<pre>".shell_exec("psexec \\\\machine <options> cmd.exe /C dir")."</pre>";
?>
Note that you could use GET arguments in order to create a more flexible example. To debunk that this indeed is working before you test over a webpage, issue the command php <path-to-the-file>\test.php. That will work perfectly. But, it won't work on a web browser.
If you kill the process, you'll get the first line: El volumen de la unidad C no tiene etiqueta.. Next line, in my language there's an accent included so I thought It could be encoding (or code pages) issues. So instead of cmd.exe /C dir I tested cmd.exe /C chcp 850 && dir. That, for my surprise, works.
Then, I realize that no matter what command you set before it will also work, for instance, cmd.exe /C 123 & dir (note the single & as I'm not evaluating the command output).
Honestly, I don't know what is going on with psexec and PHP via web browser. More surprisingly, commands like cmd.exe /C copy cmd.exe cmd.exe.deleteme and cmd.exe /C mkdir deletethis will work!
So, you could give it a try to cmd.exe /C 1 & \"mspaint\" as your problem and my seems similars. For single commands could be a workaround but I'm developing an unattended framework for installing software and all my files are .cmd or .exe or .bat files.
Let me know If you found something interesting :)
I have a solution!
This topic is old but still relevant. I wanted to use PsExec 2.2 with PHP 7.2.0 RC3 to execute a script remotely. I need the output of the script and so i was using PsExec.exe -accepteula \\HOST -u xxx -p xxx with >> LOGFILE 2>&1.
Because I dont want to wait the script to finish, I used exec() like this: exec('start /p cmd /c PsExec.exe -accepteula \\HOST -u xxx -p xxx >> LOGFILE 2>&1').
My php script continues working and PsExec does his job too.
Everything works fine but my LOGFILE always contains only the first line of the STDOUT output.
I have tried many solutions mentioned here, but none of them worked for me. Executing the command in the CMD directly, PsExec returns all lines of STDOUT but inside php it does not.
At the php doc for exec() I have found comments where some people used PsExec to run a programm without waiting (http://php.net/manual/de/function.exec.php#86438). As a last chance I tried the following: exec('PsExec.exe -accepteula -i -d cmd /c PsExec.exe -accepteula \\HOST -u xxx -p xxx >> LOGFILE 2>&1')... And it works!
PsExec now returns everthing into my LOGFILE. I hope I could help you and save you some time.
My current solution was to use WScript.Shell:
$string = "cmd /c \"cd {$full_base}{$newSource} && ant release > compile.txt\"";
$Shell = new COM("WScript.Shell");
$exec = $Shell->Run($string, 0, false);
Not sure if this was definitively answered or not, but I was having the same problem with PSEXEC hanging, though in my case, on some machines it did, and others it didn't. It turned out to be accepting the EULA. On machines that I'd run it from a command line and used the same username/password as my PHP script, it ran without hanging.
Further research showed that I could specify the EULA acceptance by including it in the command being executed from PHP:
This DID hang: psexec \\MACHINENAME ...
This did NOT: psexec /accepteula \\MACHINENAME ...
ok here are the things. I also jumped into similar condition as you were and hopefully since i am commenting this late you must have figured out a way too .But for those who are still in this problem , i suggest them few tips .
1)The code that has been posted is super fine , no problem with that thing. If your page hangs out infinitely then try to add -i -d params before the source exe. (see the documentation HERE ). You can also add -accepteula (EULA) flag in the command to let the page load and not to wait for that command to finish(solves the infinite wait problem).
2)For me these things didnt work . It doesnt mean that you guys dont try these things .these are the first steps if your code starts working then thats fine for you.Else ,make another account as an adminstrative one ,type services.msc in the start menu , you will see the page there. Search for wampapache or xammp services ,excluding mysqld one. Then simply click on that service .GO to log on tab ,select This account .Select the previously made admin acc , type its password if you set that else leave the textbox empty.Type the name of that account as \\accname at the name field . If u dont know the account name ,Click to Browse->Advanced->FInd now you will see that name account . Select, apply settings and restart the wamp app and you are good to go :)
Also make sure to double check the string you feed into your exec command. Seems trivial, but had me stumped for awhile. In many cases PHP escapes the double backslash in your machine address which throws everything off. To get around this, create your string like:
$string = 'PSExec /accepteula \\\\MACHINENAME ...'

run shell script from php

I am attempting to create a php script that can connect thru ssh to my Qnap TS219 server and run a command on it.
My script so far connects fine to the server but when I run the command I get an error message and I can't figure it out.
exec.sh
#!/bin/bash
cp /share/MD0_DATA/Qdownload/rapidshare/admin/script.txt /share/MD0_DATA/Qdownload/rapidshare/admin/script.sh
chmod 755 /share/MD0_DATA/Qdownload/rapidshare/admin/script.sh
nohup sh /share/MD0_DATA/Qdownload/rapidshare/admin/script.sh &
exit 0
script.sh
#!/bin/bash
/opt/bin/plowdown -o /share/MD0_DATA/Qdownload/rapidshare /share/MD0_DATA/Qdownload/rapidshare/admin/down.txt 2>/share/MD0_DATA/Qdownload/rapidshare/admin/output.txt
the command that I am currently running thru ssh after I submit the form:
echo $ssh->exec('sh /share/MD0_DATA/Qdownload/rapidshare/admin/exec.sh');
Right now generates the code below but only after I kill 2 bash processes (the page keeps loading indefinetly and the processor activity is at 100% if I don't kill the 2 bash processes):
/share/MD0_DATA/.qpkg/Optware/share/plowshare/lib.sh: line 261: getopt: command not found start download (rapidshare): http://rapidshare.com/files/312885386/Free_Stuff-Your_Internet_eBay_Business_Free_Startup_Resources.rar /share/MD0_DATA/.qpkg/Optware/share/plowshare/lib.sh: line 261: getopt: command not found /share/MD0_DATA/.qpkg/Optware/share/plowshare/lib.sh: line 46: --insecure: command not found Error: failed inside rapidshare_download()
This script will be used in my local network, no access from outside, so I am not worry about security, I know the code looks very basic, primitive but I have no experience with php, shell script, so if someone can make any sense on this and help me out will be greatly appreciated.
Edit1. I also tried the shell_exec command still no joy and if I run the script thru putty works beautifully.
Edit2. I think we are on to something.
I added the code you suggested and I got the following message.
sh: /share/MD0_DATA/.qpkg/Optware/share/plowshare: is a directory /usr/bin:/bin:/usr/sbin:/sbin
I think at the moment the PATH is usr/bin:/bin:usr/sbin:/sbin and I think it should be /opt/bin /opt/sbin because there are the "executables". Any ideeas?
Thanks,
Chris.
Run this
echo $ssh->exec('pwd');
Does it list your path correctly? If so then your problem is NOT PHP, if it doesn't list or still gives an error then PHP is your problem and we can continue from there.
From the error you've listed, my first guess would be that PATH isn't set, so lib.sh can't find what it's looking for.
Remember you're logging in with a custom shell (PHP ssh), quite often things aren't set as they should be, so your scripts might not find requirements like paths and variables.
Edit:
Since it's giving /root, we at least know it's going through, why not also set the PATH etc...
echo $ssh->exec('PATH=$PATH;/share/MD0_DATA/.qpkg/Optware/share/plowshare; sh /share/MD0_DATA/Qdownload/rapidshare/admin/exec.sh');
Remember you can also use this to see what is and isn't being set.
echo $ssh->exec('ECHO $PATH');
I think I got it:
Following viper_sb logic, I changed the code to:
echo $ssh->exec('PATH=$PATH:/share/MD0_DATA/.qpkg/Optware/bin; sh /share/MD0_DATA/Qdownload/rapidshare/admin/exec.sh');
echo $ssh->exec('echo $PATH');
and magic, it worked ... I'll test it further, when I get home, but I think it worked, a file was downloaded in the /Qdownload/rapidshare folder ... hooray.

Categories