sshbunny
1.0.0
PHP 库提供了一个面向对象的包装器来连接到 SSH 并使用 php ssh2 扩展运行 shell 命令。
将库添加到项目的最佳方法是使用 Composer。
composer require faraweilyas/ sshbunny
或者
git clone https://github.com/faraweilyas/sshbunny.git
sshbunny
构造函数有四个参数,它们都有默认值$method='local'
、 $authType=NULL
、 $host=NULL
、 $port=22
、 $username=NULL
$method
可以设置为local
或remote
, local
将在没有互联网连接的情况下在您自己的 shell 上执行命令,而remote
根据您的配置在您连接的远程服务器上执行命令。$authType
可以设置为KEY
、 PASSWORD
或KEY_PASSWORD
, KEY
和KEY_PASSWORD
使用 ssh2_auth_pubkey_file ,区别在于当您设置$authType='KEY_PASSWORD'
ssh2_auth_pubkey_file 时,ssh2_auth_pubkey_file 采用现在需要的密码的最后一个参数,而PASSWORD
使用 ssh2_auth_password 。$port
应设置为您的服务器端口。$username
应设置为您的服务器用户名。如果您将连接方法设置为$method='remote'
且$authType = KEY || KEY_PASSWORD
这意味着您需要设置您的公钥和私钥文件,您可以在初始化之前使用设置器sshbunny
有$ sshbunny ->setKeys('public_key.pub', 'private_key')
来完成此操作。
由于连接方法设置为local
因此这将在本地运行
<?php
use sshbunny sshbunny ;
require_once ' vendor/autoload.php ' ;
// ->getData() will return output of command executed while ->getData(TRUE) will dispay the output
$ sshbunny = ( new sshbunny ( ' local ' ))
-> initialize ()
-> exec ( " echo 'Hello World' " )
-> getData ( TRUE );
这将连接到远程服务器,因为连接方法设置为remote
并且身份验证类型设置为KEY
<?php
use sshbunny sshbunny ;
require_once ' vendor/autoload.php ' ;
defined ( ' TEST_HOST ' ) ? NULL : define ( ' TEST_HOST ' , " 138.222.15.1 " );
defined ( ' PORT ' ) ? NULL : define ( ' PORT ' , " 22 " );
defined ( ' USERNAME ' ) ? NULL : define ( ' USERNAME ' , " ubuntu " );
defined ( ' PUBLIC_KEY ' ) ? NULL : define ( ' PUBLIC_KEY ' , ' id_ssl.pub ' );
defined ( ' PRIVATE_KEY ' ) ? NULL : define ( ' PRIVATE_KEY ' , ' id_ssl ' );
$ sshbunny = ( new sshbunny ( ' remote ' , ' KEY ' , HOST , PORT , USERNAME ))
-> setKeys ( PUBLIC_KEY , PRIVATE_KEY )
-> initialize ()
-> exec ( " echo 'Hello World' " )
-> getData ( TRUE );
命令执行可以采用多个命令,或者您可以将exec
方法与另一个exec
方法链接起来
$ sshbunny = ( new sshbunny ( ' remote ' , ' KEY ' , HOST , PORT , USERNAME ))
-> setKeys ( PUBLIC_KEY , PRIVATE_KEY )
-> initialize ()
// Multiple commands
-> exec ( " echo 'Hello World' " , " cd /var/www/html " )
// Method chaining
-> exec ( " ls -la " )
-> getData ( TRUE );
// Will return the result of executed command output
$ sshbunny
-> exec ( " ls -la " )
-> getData ();
// Will display the result of executed command output
$ sshbunny
-> exec ( " ls -la " )
-> getData ( TRUE );
// Will clear the first executed command output and return the next executed command output
$ sshbunny
-> exec ( " ls -la " )
-> clearData ()
-> exec ( " whoami " )
-> getData ( TRUE );
// Will run the commands provided and display the result then disconnect from the server
$ sshbunny
-> exec ( " ls -la " , " whoami " )
-> getData ( TRUE )
-> disconnect ();