All HowTo's Cyber-Security Linux Redhat, Fedora and CentOS Linux Scripting in Bash Ubuntu, Mint & Debian Linux Web Servers

Send SSH commands from PHP 5.6 (php56w)

This article explains how to send SSH commands (SSH, SCP, SFTP) to a remote server using php. In this example we have a working php56w installation with Apache. We’re using CentOS 7. SELinux is enabled.

Download the libraries:

https://sourceforge.net/projects/phpseclib/files/phpseclib1.0.5.zip/download

Unzip the files into a new library directory:

# Go to the document root and create the library directory
cd /var/www/html/www.example.com
mkdir libraries_ssh

# Put the Zip file in the right place and unzip it
cd libraries_ssh
# put the Zipped file here
unzip phpseclib1.0.5.zip

# Return to the document root and create a test php script
cd ..
touch example.php

# Make sure Apache owns the files and SELinux is happy
chown apache.apache -R ./
restorecon -rv ./
setsebool -P httpd_can_network_connect on

Now we need to populate “example.php” with some sample code to test our progress.

<?php
// test SSH commands

// include the library path
set_include_path(get_include_path() . PATH_SEPARATOR . 'libraries_agix/');

// and the libraries themselves
include("Net/SSH2.php");

/*

  other options for SSH related commands:
 SCP.php
 SFTP.php
 SSH1.php 
 SSH2.php

*/

// connect to the server/pi
$ssh = new Net_SSH2('10.1.2.3');

if (!$ssh->login('root', 'MysecretPassword')) {
    exit('Login Failed');
}

// the actual command to run
echo $ssh->exec('ls -la');

?>

You should be able to test it now.

Interesting links:

http://phpseclib.sourceforge.net/2.0.html
http://phpseclib.sourceforge.net/ssh/intro.html

Leave a Reply

Your email address will not be published. Required fields are marked *