I wanted to run a specific command through ssh protocol on my server. And this is super helpful to do some kind of remote processing by PHP easily, so I do not need to log on remote server.

STEP 1. Installing SSH2 Extension

The first thing you need to check is if your system has SSH2 features or not. You can simply check at phpinfo() in php function. If not, you can simply install SSH2 functions by below commands in root permission. The below case is based on  Centos7.

yum update
yum -y install make gcc libssh2 php-devel php-pear libssh2-devel

The next action you should do is installing ssh2 extension using pecl command for auto detect and download it once hit enter.

pecl install -f ssh2

When you run above command, you may get the message like below

You should add "extension=ssh2.so" to php.ini

That means you should do it in order to make it work like below

echo "extension=ssh2.so" > /etc/php.d/50-ssh2.ini


or


echo "extension=ssh2.so" > /etc/php.ini

If above works correctly, you should restart your server like

systemctl restart httpd.service

You can check it in your phpinfo().


STEP 2. Run remote command via SSH

Example 1) Rebooting remote windows machine

Below code connects to windows machine, and run "shutdown -r -f 0" command remotely.

reboot.php
<?php // programmed by Chun Kang


$s = ssh2_connection( '192.168.10.8', 22);


if (ssh2_auth_password( $s, 'your_id', 'your_password')) {
	echo "Authentication successful!\n";
} else {
	die( "Authentication failed...\n");
}

// reboot remote machine
ssh2_exec( $s, "shutdown -r -f -t 0");


?>


Now you can run your command by web or command line like below

php reboot.php


Example 2) Get command result and display it

Below code connects to windows machine, run "dir" command remotely, and display its call results.

dir.php
<?php // programmed by Chun Kang


$s = ssh2_connection( '192.168.10.8', 22);


if (ssh2_auth_password( $s, 'your_id', 'your_password')) {
	echo "Authentication successful!\n";
} else {
	die( "Authentication failed...\n");
}

// get file information on the working directory in the Microsoft Windows machine
$stream=ssh2_exec( $s, "dir");
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents( $stream_out);

?>


Now you can run your command by web or command line like below

php dir.php