Reputation: 1035
I'm trying to execute a simple shell command and print the result on a web page but the results are empty. Below is one bit of code I found but nothing has worked thus far.
<?php
$server = "myserver";
$username = "myadmin";
$command = "ps";
$str = "ssh " .$username. "@" .$server. " " .$command;
exec($str, $output);
echo '<pre>';
print_r($output);
echo '</pre>';
?>
Upvotes: 2
Views: 19231
Reputation: 613
Using a more object oriented solution, you can install phpseclib version 2 with:
composer require phpseclib/phpseclib
And then just create your ssh object:
$ssh = new SSH2('yourhost');
if (!$ssh->login('username', 'password')) {
exit('Login Failed');
}
In this exemple i have used a connection through username and password but you can also connect via ssh-keys. If the connection is successful you can execute the method exec to execute you command on the server.
Upvotes: 0
Reputation: 780899
You're missing the -p
option before the port number:
$str = "ssh -p $port $username@$server $command";
Upvotes: 0
Reputation: 5213
Try phpseclib, that'll work.
<?php
include('Net/SSH2.php');
$server = "myserver";
$username = "myadmin";
$password = "mypass";
$command = "ps";
$ssh = new Net_SSH2($server);
if (!$ssh->login($username, $password)) {
exit('Login Failed');
}
echo $ssh->exec($command);
?>
Upvotes: 6