Failed to " /> Failed to " /> Failed to "/>

PHP How to execute a command and get its output

3.1k views Asked by At

I need to execute a command to my server and get the result as output in php

<?php
    $socket = fsockopen("ip", 22); 
    ($socket ? null : die("<p>Failed to connect"));
 
    fwrite($socket, " username\n"); 
    fwrite($socket, " password\n");
 
    $command = " netstat -anp | grep :650 | grep ESTABLISHED | wc -l\n";
    fwrite($socket, $command . "\n");
    echo "<pre>$result</pre>";
    
    sleep(1); 
    // Close connection
    fclose($socket);    
?>
3

There are 3 answers

1
Eden Moshe On

run on your server?

need the console output? u can use:

exec() only returns the last line of the generated output.

shell_exec() returns the full output of the command, when the command finished running.

system() immediately shows all output, and is used to show text.

0
JB_DELR On

For ssh connection, you need to install php-ssh2. Then this code works but need some inprouvements:

$ssh = ssh2_connect($host); //default port is 22
if (false === $ssh) {
    die('connection failed');
}

$auth = @ssh2_auth_password($ssh, $user, $pwd); // with user and password
if (false === $auth) {
    die('authentication failed');
}


$command = "ls\r\n";

$shell=ssh2_shell($ssh, 'xterm');
fwrite( $shell, 'ls'.PHP_EOL);

while (!feof($shell)){
    echo fgets($shell).PHP_EOL; // this return all the lines since the begining of the session
 }

ssh2_disconnect();
0
Lawrence Cherone On

Alternatively if you have ssh installed on the server you could use shell_exec to execute the ssh command.

So if you have ssh keys (or make them), move them into the project but out of webroot

cp ~/.ssh/id_rsa /path/to/script/ssh_keys/id_rsa
cp ~/.ssh/id_rsa.pub /path/to/script/ssh_keys/id_rsa.pub

# make .htaccess (or dont put in webroot)
echo "deny from all" > /path/to/script/ssh_keys/.htaccess

Then you could do a simple script like the following, if you dont have ssh keys (eek), then use passh:

<?php
// with ssh key
echo `ssh -i ./ssh_keys/id_rsa username@<IP> /bin/bash << EOF
netstat -anp | grep :650 | grep ESTABLISHED | wc -l
EOF`;

// with password (requires passh)
echo `passh -p password ssh username@<IP> /bin/bash << EOF
netstat -anp | grep :650 | grep ESTABLISHED | wc -l
EOF`;

You have given an example of hardcoded script, I'm presuming its a hardcoded script, if it's not and the values or command is user-defined then you shouldn't be running SSH cmds as its too risky, instead look into making a rest API or use RPC.