faraweilyas / sshbunny
PHP库,提供了一个面向对象的包装器,用于通过php ssh2扩展连接SSH和运行shell命令。
v1.0.4
2018-12-07 01:15 UTC
Requires (Dev)
- phpunit/phpunit: ^6.4
README
PHP库,提供了一个面向对象的包装器,用于通过php ssh2扩展连接SSH和运行shell命令。
需求
使用composer安装
将库添加到项目的最佳方式是使用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将取密码的最后一个参数,现在需要密码,而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();