How to run CLI commands in PHP on another server using SSH?
ssh2_connect or phpseclib
You can use ssh2_connect or phpseclib. On my EC2 instance I had to install the package for ssh2_connect (e.g. yum install php56-pecl-ssh2-0.12-5.15.amzn1.x86_64) as it wasn't there by default. Note: this could be done with a bash script as well.
<?php
//ssh2_connect:
$connection = ssh2_connect('localhost', 22);
ssh2_auth_password($connection, 'user', 'password');
$stream = ssh2_exec($connection, 'ls -l > /tmp/worked.txt');
//phpseclib:
include('Net/SSH2.php');
$ssh = new Net_SSH2('www.example.com');
$ssh->login('username', 'password') or die("Login failed");
echo $ssh->exec('command');
Further reading:
http://phpseclib.sourceforge.net/
http://php.net/manual/en/function.ssh2-connect.php
How To connect to remote server via PHP
Finally, I found the solution
Phpseclib isn't working for me
<?php
$connection = ssh2_connect('ip.22.222.2', 22);
if (ssh2_auth_password($connection, 'username', 'pass')) {
echo "Authentication Successful!\n";
} else {
die('Authentication Failed...');
}
?>
Replace The user/pass/IP with your own values
Execute a shell command through ssh using PHP
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);
?>
How can I execute remote commands in PHP via ssh?
If you can't add php packages due to red tape, here's a simple class that can do the trick
class ExecuteRemote
{
private static $host;
private static $username;
private static $password;
private static $error;
private static $output;
public static function setup($host, $username=NULL, $password=NULL)
{
self::$host = $host;
self::$username = $username;
self::$password = $password;
}
public static function executeScriptSSH($script)
{
// Setup connection string
$connectionString = self::$host;
$connectionString = (empty(self::$username) ? $connectionString : self::$username.'@'.$connectionString);
// Execute script
$cmd = "ssh $connectionString $script 2>&1";
self::$output['command'] = $cmd;
exec($cmd, self::$output, self::$error);
if (self::$error) {
throw new Exception ("\nError sshing: ".print_r(self::$output, true));
}
return self::$output;
}
}
PHP Execute Shell Command And Retrieve The Output
Use escapeshellarg()
to escape command argument. Please try like this
$host = escapeshellarg("user@router");
$commandArg = escapeshellarg("/var/log/messages");
$result = shell_exec('ssh ' . $host . ' cat ' . $commandArg);
echo $result, PHP_EOL;
Execute commands on remote machine via PHP
Run SSH commands through PHP on server A to server B.
Here is how to run ssh commands with the command line in linux: http://www.youtube.com/watch?NR=1&feature=fvwp&v=YLqqdQZHzsU
In order to run commands on linux with PHP use the exec() command.
I hope this will get you started looking in the right direction.
Look at these two posts for automating the password prompt
- https://serverfault.com/questions/241588/how-to-automate-ssh-login-with-password
- https://serverfault.com/questions/187036/execute-ssh-command-without-password
Here is a quick example with non-working code to get you thinking:
<?php
$server = "serverB.example.org";
//ip address will work too i.e. 192.168.254.254 just make sure this is your public ip address not private as is the example
//specify your username
$username = "root";
//select port to use for SSH
$port = "22";
//command that will be run on server B
$command = "uptime";
//form full command with ssh and command, you will need to use links above for auto authentication help
$cmd_string = "ssh -p ".$port." ".$username."@".$server." ".$command;
//this will run the above command on server A (localhost of the php file)
exec($cmd_string, $output);
//return the output to the browser
//This will output the uptime for server B on page on server A
echo '<pre>';
print_r($output);
echo '</pre>';
?>
The recommended flow is to run a command on server A to SSH to server B
Related Topics
Is the Leading Colon For Parameter Names Passed to Pdostatement::Bindparam() Optional
How to Create Helper Methods on Laravel Not a Facade
How to Mimic Stack Overflow Auto-Link Behavior
Youtube API - Extract Video ID
Error in PHP5 ..Unable to Load Dynamic Library
PHP Curly Brace Syntax For Member Variable
How to Fix Trying to Access Array Offset on Value of Type Null Error
PHP Date() Format When Inserting into Datetime in MySQL
How to Include() All PHP Files from a Directory
Count How Many Files in Directory PHP
What Is the Meaning of Three Dots (...) in PHP
What Is Function Overloading and Overriding in PHP
Create or Write/Append in Text File
Convert a Comma-delimited String into Array of Integers
What Is ≪=≫ (The 'Spaceship' Operator) in PHP 7
How to Test If a MySQL Query Was Successful in Modifying Database Table Data