Created
July 12, 2017 21:27
-
-
Save petenelson/e34edd0f74315e235ed3900458e03de9 to your computer and use it in GitHub Desktop.
WordPress: Run SSH command remotely
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: SSH Remote Test | |
*/ | |
add_action( 'admin_init', 'ssh_remote_test', 1 ); | |
function ssh_remote_test() { | |
// this is VERY basic demonstration code for running a remote SSH command. | |
// files for the filesytem classes | |
require_once( ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php' ); | |
require_once( ABSPATH . 'wp-admin/includes/class-wp-filesystem-ssh2.php' ); | |
if ( class_exists( 'WP_Filesystem_SSH2' ) ) { | |
// Also accepts public_key and private_key filenames. | |
$options = array( | |
'port' => 22, | |
'hostname' => 'host.com', | |
'username' => 'username', | |
'private_key' => '/srv/www/keys/username/id_rsa', | |
'public_key' => '/srv/www/keys/username/id_rsa.pub', | |
); | |
if ( ! defined('FS_CONNECT_TIMEOUT') ) | |
define('FS_CONNECT_TIMEOUT', 30); | |
if ( ! defined('FS_TIMEOUT') ) | |
define('FS_TIMEOUT', 30); | |
$ssh = new WP_Filesystem_SSH2( $options ); | |
// check for errors | |
// if ssh2 is not an installed PHP extension: sudo apt-get install libssh2-php php7.0-ssh2 | |
if ( ! empty( $ssh->errors->errors ) ) { | |
var_dump( $ssh->errors ); | |
die(); | |
} | |
if ( ! $ssh->connect() ) { | |
echo 'unable to connect'; | |
} else { | |
echo '<pre>'; | |
$ls_results = $ssh->run_command( 'ls -latrh' ); | |
echo $ls_results; | |
} | |
} | |
die(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment