技术控

    今日:69| 主题:49211
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Phpseclib: Securely Communicating with Remote Servers via PHP

[复制链接]
我的闺蜜会发光 发表于 2016-10-4 09:27:04
68 2

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
PHP has an SSH2 library which provides access to resources (shell, remote exec, tunneling, file transfer) on a remote machine using a secure cryptographic transport. Objectively, it is a tedious and highly frustrating task for a developer to implement it due to its overwhelming configuration options and complex API with little documentation.
   Phpseclib: Securely Communicating with Remote Servers via PHP-1 (available,transport,developer,resources,otherwise)
   The phpseclib ( PHP S ecure C ommunications Lib rary) package has a developer friendly API. It uses some optional PHP extensions if they’re available and falls back on an internal PHP implementation otherwise. To use this package, you don’t need any non-default PHP extensions installed.
  Installation

  [code]composer require phpseclib/phpseclib[/code]   This will install the most recent stable version of the library viaComposer.
  Use-cases

  Before diving in blindly, I’d like to list some use-cases appropriate for using this library:
  
       
  • Executing deployment scripts on a remote server   
  • Downloading and uploading files via SFTP   
  • Generating SSH keys dynamically in an application   
  • Displaying live output for remote commands executed on a server   
  • Testing an SSH or SFTP connection  
  Connecting to the Remote Server

   Using phpseclib , you can connect to your remote server with any of the following authentication methods:
  
       
  • RSA key   
  • Password Protected RSA key   
  • Username and Password ( Not recommended )  
  RSA Key

   We will assume that you have a secure RSA key already generated. If you are not familiar with generating a secure RSA key pair, you can go through this article . For a video explanation, you can refer to Creating and Using SSH Keys from Servers For Hackers.
   To log in to a remote server using RSA key authentication:
  [code]namespace App;

use phpseclib\Crypt\RSA;
use phpseclib\Net\SSH2;

$key = new RSA();
$key->loadKey(file_get_contents('privatekey'));

//Remote server's ip address or hostname
$ssh = new SSH2('192.168.0.1');

if (!$ssh->login('username', $key)) {
    exit('Login Failed');
}[/code]  Password Protected RSA Key

   If your RSA keys are password protected, do not worry. Phpseclib takes care of this particular use case:
  [code]namespace App;

use phpseclib\Crypt\RSA;
use phpseclib\Net\SSH2;

$key = new RSA();
$key->setPassword('your-secure-password');
$key->loadKey(file_get_contents('privatekey'));

//Remote server's ip address or hostname
$ssh = new SSH2('192.168.0.1');

if (!$ssh->login('username', $key)) {
    exit('Login Failed');
}[/code]  Username and Password

  Alternatively, to log in to your remote server using a username and password (we don’t recommend this practice):
  [code]namespace App;

use phpseclib\Net\SSH2;

//Remote server's ip address or hostname
$ssh = new SSH2('192.168.0.1');

if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}[/code]   For other options such as No Authentication or Multi-Factor authentication please refer to the documentation
  Executing Commands on the Remote Server

   The code to execute commands on a remote server is pretty simple. You call the $ssh->exec($cmd) method with the command to execute as the parameter.
  [code]namespace App;

use phpseclib\Crypt\RSA;
use phpseclib\Net\SSH2;

$key = new RSA();
$key->loadKey(file_get_contents('privatekey'));

//Remote server's ip address or hostname
$ssh = new SSH2('192.168.0.1');

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

$ssh->exec('ls -la');[/code]  Executing Multiple Commands on Remote Server

   In real life applications, we rarely execute a single command. We often need to traverse around the server using cd and execute many other commands. If you try to execute multiple commands on the remote server as below, it won’t give you the desired output:
  [code]$ssh->exec('pwd'); //outputs /home/username

$ssh->exec('cd mysite.com');

$ssh->exec('pwd'); //outputs /home/username[/code]   The reason for above is that a call to the exec method does not carry state forward to the next exec call. To execute multiple commands without losing state:
  [code]$ssh->exec('cd /home/username; ls -la'); //Lists all files at /home/username[/code]   You can append as many commands as you wish with a semicolon or new line character PHP_EOL .
  For example, if you want to run a full deployment script for Laravel:
  [code]$ssh->exec(
      "git pull origin master" . PHP_EOL
        . "composer install --no-interaction --no-dev --prefer-dist" . PHP_EOL
        . "composer dump-autoload -o" . PHP_EOL
        . "php artisan optimize" . PHP_EOL
        . "php artisan migrate --force"
);[/code]  Exiting on First Error

   In the above script, the whole set of commands is executed as a single shell script. Every command will be executed, even if some of them fail, just like in a regular shell script. As a default, this is fine, but if we need to exit on the first error, we have to alter our bash script. This is not something specific to phpseclib , it is related to bash scripting.
   If you put a set -e option at the beginning of the script, the script will terminate as soon as any command in the chain returns a non-zero value.
  For example, the modified version of the above deployment script would be
  [code]$ssh->exec(
    "set -e" . PHP_EOL
        . "git pull origin master" . PHP_EOL
        . "composer install --no-interaction --no-dev --prefer-dist" . PHP_EOL
        . "composer dump-autoload -o" . PHP_EOL
        . "php artisan optimize" . PHP_EOL
        . "php artisan migrate --force"
);[/code]  The above script will terminate if any of the commands results in an error.
  Gathering Output

   The exec method returns the output of your remote script:
  [code]$output = $ssh->exec('ls -la');
echo $output;[/code]   Sometimes, however, it does not return the whole output. You can overcome this by passing a closure as a second argument to the exec method to make sure that any uncaught output will also be returned.
  [code]namespace App;

use phpseclib\Crypt\RSA;
use phpseclib\Net\SSH2;

$key = new RSA();
$key->loadKey(file_get_contents('privatekey'));

//Remote server's ip address or hostname
$ssh = new SSH2('192.168.0.1');

if (!$ssh->login('username', $key)) {
    exit('Login Failed');
}0[/code]   Note: Error output, if any, will also be returned by the exec method or the underlying closure.
  Displaying Live Output

  If you want to execute the script via console commands and display live output, you can achieve this by echoing the output in the underlying closure.
  [code]namespace App;

use phpseclib\Crypt\RSA;
use phpseclib\Net\SSH2;

$key = new RSA();
$key->loadKey(file_get_contents('privatekey'));

//Remote server's ip address or hostname
$ssh = new SSH2('192.168.0.1');

if (!$ssh->login('username', $key)) {
    exit('Login Failed');
}1[/code]   If you want to display it in a web browser, you need to flush (send) the output buffer with ob_flush() .
  [code]namespace App;

use phpseclib\Crypt\RSA;
use phpseclib\Net\SSH2;

$key = new RSA();
$key->loadKey(file_get_contents('privatekey'));

//Remote server's ip address or hostname
$ssh = new SSH2('192.168.0.1');

if (!$ssh->login('username', $key)) {
    exit('Login Failed');
}2[/code]  Other Configuration Options

   It’s also possible to set many other available configuration options. You can call them as $ssh->{option} .
   For example: $ssh->setTimeout(100) .
  All the options we haven’t covered yet are in the table below:
              Option     Use case                    setTimeout($seconds)       $ssh->exec('ping 127.0.0.1'); on a Linux host will never return and will run indefinitely. setTimeout() makes it so it’ll timeout. Setting $timeout to false or 0 will mean there is no timeout.               write($cmd)      Inputs a command into an interactive shell.              read()      Returns the output of an interactive shell              isTimeout()       Return true if the result of the last $ssh->read() or $ssh->exec() was due to a timeout. Otherwise it will return false.               isConnected()      Returns true if the connection is still active              enableQuietMode()      Suppresses stderr so no errors are returned              disableQuietMode()      Includes stderr in output              isQuiteModeEnabled()      Returns true if quiet mode is enabled              enablePTY()       Enable request-pty when using exec()               disablePty()       Disable request-pty when using exec()               isPTYEnabled()      Returns true if request-pty is enabled              getLog()      Returns a log of the packets that have been sent and received.              getServerPublicHostKey()      Returns the server public host key. Returns false if the server signature is not signed correctly with the public host key.              getExitStatus()      Returns the exit status of an SSH command or false.              getLanguagesClient2Server()      Return a list of the languages the server supports, when receiving stuff from the client.              getLanguagesServer2Client()      Return a list of the languages the server supports, when sending stuff to the client.              getCompressionAlgorithmsServer2Client()      Return a list of the compression algorithms the server supports, when sending stuff to the client.              getCompressionAlgorithmsClient2Server()      Return a list of the compression algorithms the server supports, when receiving stuff from the client.              getMACAlgorithmsServer2Client()      Return a list of the MAC algorithms the server supports, when sending stuff to the client.              getMACAlgorithmsClient2Server()      Return a list of the MAC algorithms the server supports, when receiving stuff from the client.              getEncryptionAlgorithmsServer2Client()      Return a list of the (symmetric key) encryption algorithms the server supports, when sending stuff to the client.              getEncryptionAlgorithmsClient2Server()      Return a list of the (symmetric key) encryption algorithms the server supports, when receiving stuff from the client.              getServerHostKeyAlgorithms()      Return a list of the host key (public key) algorithms the server supports.              getKexAlgorithms()      Return a list of the key exchange algorithms the server supports.           Alternatives

  
       
  • LIBSSH2 – The SSH library – The library provides similar functionality, but is a little less intuitive to use, and it requires you to have libssh2 installed on the server, which most shared hosts don’t have.   
  • Process component – Symfony’s component for writing your own script for connecting and executing commands – as you would do in a normal terminal. This limits us in the configuration options that we might need to set. Achieving the same functionality the above configuration methods provide us with with Process would require in-depth bash knowledge. If your use-case involves only running a local script, however, this might prove to be a useful component.  
  Summary

   In this article, we introduced phpseclib , a package which provides an alternative for SSH2 . We have covered the configuration options necessary to get started, and the table above should help you fill in the gaps and give an overview of other configuration options available to you.
   For an in-depth implementation of key-based communication, see ourprevious tutorial.
  How do you execute remote commands? Can you think of any advanced use cases for this library? What are they? Let us know in the comments!
友荐云推荐




上一篇:PHPStorm & OSX: Mouse Stopped Working - Stefan Koopmanschap
下一篇:谈谈存储软件的无锁设计
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

qllaou69 发表于 2016-10-12 09:56:26
这世界上有两个我,一个假装快乐,一个真心难过。
回复 支持 反对

使用道具 举报

景兴波 发表于 2016-10-12 16:58:54
报,报,报,报,报告楼主,我来了!
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表