So I have question which in my head should seem very simple to solve.
I want to ssh to a server, which I have done a ton of times, and then make a shell execute which I have done a ton of times as well, but it is not working.
The code i am using
<?php
$ip = '1.2.3.4';
$cmd = "ssh user#".$ip;
$result = shell_exec($cmd." 'sudo /bin/systemctl stop wildfly.service'");
echo "<pre>output: $result</pre>";
echo "<div class='alert alert-success'><strong>SUCCESS</strong><br>Wildfly node has now restarted</div>";
?>
Running the command directly from the terminal
ssh user#1.2.3.4 sudo /bin/systemctl stop wildfly.service
It works, but running it within php gives me nothing, and it not doing anything.
Can someone maybe guide me to what I am doing wrong with my shell_exec?
Thanks in advance!
function execPrint($command) {
try {
$result = array();
exec($command.' 2>&1', $result);
foreach ($result as $line) {
print($line . "\n");
}
echo '------------------------' . "\n" . "\n";
} catch (\Exception $e) {
print($e);
}
http_response_code(200);
}
i made this function to get result
add 2>&1 in last of the CMD
use print with every line
use try and catch to catch any error
The user attempting to execute those shell commands from php is likely _www and not you. Try this code in your php to gain insight:
$shellscript = 'whoami';
$sr = shell_exec($shellscript);
echo '['.$sr.']';
Make sure the shell_exec function is not disabled. It usually is disabled by default in CPanel accounts PHP.ini and PHP-FPM .ini files.
You can check it using this validation
if (is_callable('shell_exec') && (false === stripos(ini_get('disable_functions'), 'shell_exec'))) {
echo "shell_exec enabled";
} else {
echo "shell_exec disabled";
}
It's the most common reason i've found for shell_exec to return always empty
You can also execute a quick command for testing purpouses
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
echo "Command: shell_exec('ls -lart')";
try {
$output = shell_exec('ls -lart');
echo "<pre>$output</pre>";
} catch (Exception $e) {
echo $e->getMessage();
}
I'm creating a button on my web page.I want that when someone presses this button an execution of a process of Linux commands on my first server (like "cd file" "./file_to_execute"..) when these commandes are done and finished i want to connect on another server by ssh and to execute another commands.
the probleme is how can i know that the commands before are already finished to proceed to the second part which is to connect on another server .
to resume :
first step connect on the first server , execute some commands
=> when these commands are done ( the part i dont know how to do it )
second step : to connect on another server and execute some others commands.
I'm searching for a way that will allows me to add some pop up to inform the user of my web page that he finished the first step and he started the second.
<?php
$hostname = '192.177.0.252';
$username = 'pepe';
$password = '*****';
$commande = 'cd file && ./file_one.sh';
if (false === $connection_first = ssh2_connect($hostname, 22)) {
echo 'failed<br />';
exit();
}
else {
echo 'Connected<br />';
}
if (false === ssh2_auth_password($connection_first, $username, $password)) {
echo 'failed<br />';
exit();
}
else {
echo 'done !<br />';
}
if (false === $stream = ssh2_exec($connection_first, $commande)) {
echo "error<br />";
}
?>
Thanks
PS: sorry for my English, I'm from Barcelone
To handle events where an exception occurs i would recommend using a try/catch statement, like the one below:
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
When you're trying to handle events and need to know when they finish, there are a few ways to achieve this. You can either set a boolean to true after the command has been executed (like what you are already doing). OR you can return output from the command by printing the output to a txt file and then echoing out the returns of this file. See code below:
exec ('/usr/bin/flush-cache-mage > /tmp/.tmp-mxadmin');
$out = nl2br(file_get_contents('/tmp/.tmp-mxadmin'));
echo $out;
At this point you can create conditions based off of what is returned in the $out variable.
Here is a code I use to check if process is running under windows, in this case calc.exe
I'm trying to start calc.exe if this one not figure out in task list.
If calc.exe is not started, is opened when run php script, but page remain in a loop until i close calc.exe.
Where do I wrong?
Help is appreciated.
// START SHOW TASKLIST
// Get Tasklist
exec("tasklist 2>NUL", $task_list);
//print_r($task_list);
echo '<pre>'; print_r($task_list); echo '</pre>';
// END SHOW TASKLIST
// Service running
$kill_pattern = '~(calc)\.exe~i';
// Create array
$task_list = array();
exec("tasklist 2>NUL", $task_list);
foreach ($task_list AS $task_line) {
if (preg_match($kill_pattern, $task_line, $out)) {
echo "=> Detected: ".$out[1]."\n !\n";
$is_running = '1';
break;
}
}
if ($is_running == '1') {
echo 'Nothing to do';
exit;
} else {
// open calc.exe
exec("calc.exe");
exit;
}
Please use this code to avoid script hang up
Change
exec(calc.exe);
With
pclose(popen('start /B cmd /C "calc.exe >NUL 2>NUL"', 'r'));
how can I check if a php ping returned succesfull or failed using php exec, I have in mind something with a while loop but I'm not sure if ts the best approach, I tried:
exec('ping www.google.com', $output)
but I would have to do a var_dump($output); to see the results, I want for each line the ping command returns to check it
$i = 2;
while(exec('ping www.google.com', $output)) {
if($output) {
echo 'True';
} else {
echo 'False';
}
}
I know this code is WRONG but its kind of what I need, if any of you could give me a head start on how to do it or suggestions I would really appreciate it....THANKS!!
This should do it:
if(exec('ping http://www.google.com')) {
echo 'True';
} else {
echo 'False';
}
I suggest you could use CUrl See Manual but that all depends upon what you are trying to achieve.
Provide more data if needed.
NOTE
You are to use http:// before google.com as that's needed in order to make the ping.
It's probably faster and more efficient and just do it within PHP, instead of exec'ing a shell
$host = '1.2.3.4';
$port = 80;
$waitTimeoutInSeconds = 1;
if($fp = fsockopen($host,$port,$errCode,$errStr,$waitTimeoutInSeconds)){
// It worked
} else {
// It didn't work
}
fclose($fp);
Also some servers will have EXEC disabled for security reasons, so your method won't work on every server setup.
I have the following function that I doesn't work so far. I would like to ping an IP address and then to echo whether the IP is alive or not.
function pingAddress($ip){
$pingresult = shell_exec("start /b ping $ip -n 1");
$dead = "Request timed out.";
$deadoralive = strpos($dead, $pingresult);
if ($deadoralive == false){
echo "The IP address, $ip, is dead";
} else {
echo "The IP address, $ip, is alive";
}
}
When I call this function using the example:
pingAddress("127.0.0.1")
The echo result is always 'dead' - no matter what.
Could someone please help me where I'm going wrong?
And/OR is there a better method of doing this with the same result?
Many thanks.
Update: Have amended code to include the double quotes but still getting the same (incorrect) results.
NOTE: Solution below does not work on Windows. On linux exec a "which ping" command from the console, and set command path (of the suggested exec call) accordingly
I think you want to check the exit status of the command, whereas shell_exec gives you full output (might be dangerous shall command output change from command version to version. for some reason). Moreover your variable $ip is not interpreted within single quotes. You'd have to use double ones "". That might be the only thing you need to fix in order to make it work.
But I think following code can be more "portable". IMHO it is in fact better to catch the exit status, rather than trying to parse result string. IMHO it's also better to specify full path to ping command.
<?php
function pingAddress($ip) {
$pingresult = exec("/bin/ping -n 3 $ip", $outcome, $status);
if (0 == $status) {
$status = "alive";
} else {
$status = "dead";
}
echo "The IP address, $ip, is ".$status;
}
pingAddress("127.0.0.1");
This also did not work for me in Wordpress. I also tried -t and -n and other ways, but did not work. I used,
function pingAddress($ip) {
$pingresult = exec("/bin/ping -c2 -w2 $ip", $outcome, $status);
if ($status==0) {
$status = "alive";
} else {
$status = "dead";
}
$message .= '<div id="dialog-block-left">';
$message .= '<div id="ip-status">The IP address, '.$ip.', is '.$status.'</div><div style="clear:both"></div>';
return $message;
}
// Some IP Address
pingAddress("192.168.1.1");
This worked perfectly for me, finally.
I referred this from http://www.phpscriptsdaily.com/php/php-ping/
Hope this will help
Well I want to modify this as it is working fine on my localhost but not on my live server
For live server, I got another thing which now works for both local as well as live.
$fp = fSockOpen($ip,80,$errno,$errstr,1);
if($fp) { $status=0; fclose($fp); } else { $status=1; }
Then I show the Server is up for 0 and down for 1.
This works perfectly for me. I got this from Ping site and return result in PHP Thanks #karim79
I have developed the algorithm to work with heterogeneous OS, both Windows and Linux.
Implement the following class:
<?php
class CheckDevice {
public function myOS(){
if (strtoupper(substr(PHP_OS, 0, 3)) === (chr(87).chr(73).chr(78)))
return true;
return false;
}
public function ping($ip_addr){
if ($this->myOS()){
if (!exec("ping -n 1 -w 1 ".$ip_addr." 2>NUL > NUL && (echo 0) || (echo 1)"))
return true;
} else {
if (!exec("ping -q -c1 ".$ip_addr." >/dev/null 2>&1 ; echo $?"))
return true;
}
return false;
}
}
$ip_addr = "151.101.193.69"; #DNS: www.stackoverflow.com
if ((new CheckDevice())->ping($ip_addr))
echo "The device exists";
else
echo "The device is not connected";
i just wrote a very fast solution by combining all knowledge gain above
function pinger($address){
if(strtolower(PHP_OS)=='winnt'){
$command = "ping -n 1 $address";
exec($command, $output, $status);
}else{
$command = "ping -c 1 $address";
exec($command, $output, $status);
}
if($status === 0){
return true;
}else{
return false;
}
}
this works fine for me..
$host="127.0.0.1";
$output=shell_exec('ping -n 1 '.$host);
echo "<pre>$output</pre>"; //for viewing the ping result, if not need it just remove it
if (strpos($output, 'out') !== false) {
echo "Dead";
}
elseif(strpos($output, 'expired') !== false)
{
echo "Network Error";
}
elseif(strpos($output, 'data') !== false)
{
echo "Alive";
}
else
{
echo "Unknown Error";
}
For Windows Use this class
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency !== false) {
print 'Latency is ' . $latency . ' ms';
}
else {
print 'Host could not be reached.';
}
https://github.com/geerlingguy/Ping
Based on the great answer of #tiamiyu-saheed-oluwatosin I wrote this small function in shorthand if/else (ternary) style, working on both Windows and Linux, to check if a second PHP server is up and running in my LAN.
function running($ip) {
exec("ping -{strtolower(PHP_OS)=='winnt'?'n':'c'} 1 $ip", $out, $res);
return ($res === 0 ? true : false);
}
Use :
if(running('192.168.1.20') {
// execute some code...
}
This works fine with hostname, reverse IP (for internal networks) and IP.
function pingAddress($ip) {
$ping = exec("ping -n 2 $ip", $output, $status);
if (strpos($output[2], 'unreachable') !== FALSE) {
return '<span style="color:#f00;">OFFLINE</span>';
} else {
return '<span style="color:green;">ONLINE</span>';
}
}
echo pingAddress($ip);
Do check the man pages of your ping command before trying some of these examples out (always good practice anyway). For Ubuntu 16 (for example) the accepted answer doesn't work as the -n 3 fails (this isn't the count of packets anymore, -n denotes not converting the IP address to a hostname).
Following the request of the OP, a potential alternative function would be as follows:
function checkPing($ip){
$ping = trim(`which ping`);
$ll = exec($ping . '-n -c2 ' . $ip, $output, $retVar);
if($retVar == 0){
echo "The IP address, $ip, is alive";
return true;
} else {
echo "The IP address, $ip, is dead";
return false;
}
}
This is work with me:
<?php
class CheckDevice {
public function myOS(){
if (strtoupper(substr(PHP_OS, 0, 3)) === (chr(87).chr(73).chr(78)))
return true;
return false;
}
public function ping($ip_addr){
if ($this->myOS()){
if (!exec("ping -n 1 -w 1 ".$ip_addr." 2>NUL > NUL && (echo 0) || (echo 1)"))return true;
} else {
if (!exec("ping -q -c1 ".$ip_addr." >/dev/null 2>&1 ; echo $?"))
return true;
}return false;
}
}
$ip_addr = "192.168.1.1";
if ((new CheckDevice())->ping($ip_addr))
echo "The device exists";
else
echo "The device is not connected";
I use this function :
<?php
function is_ping_address($ip) {
exec('ping -c1 -w1 '.$ip, $outcome, $status);
preg_match('/([0-9]+)% packet loss/', $outcome[3], $arr);
return ( $arr[1] == 100 ) ? false : true;
}