I wanted to run a specific command through ssh protocol on my server. And this is super helpful to do such kind of remote processing by PHP easily.
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 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().
Below code connects to windows machine, and run "shutdown -r -f 0" command remotely.
<?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"); } shh2_exec( $s, "shutdown -r -f 0"); ?> |
https://www.thelinuxfaq.com/253-how-to-install-ssh2-extension-for-php-rhel-centos-7