如何使用PHP SSH2模塊執(zhí)行遠程Linux命令
PHP SSH2擴展是用于在PHP程序中使用SSH(安全殼協(xié)議)的一種擴展。它允許建立加密連接和執(zhí)行遠程命令、上傳和下載文件等操作,十分方便實用。下面我將為大家詳細介紹一下該擴展的基本用法和常見操作。
安裝
libssh2 安裝
libssh2 是一個開源的C語言庫,用于實現(xiàn)SSH(Secure Shell)協(xié)議的客戶端功能。它提供了一組API函數(shù),使開發(fā)者可以在自己的應用中實現(xiàn)SSH客戶端的功能,如遠程執(zhí)行命令、文件傳輸和端口轉發(fā)等。
wget https://libssh2.org/download/libssh2-1.11.0.tar.gz
tar -zxvf libssh2-1.11.0.tar.gz
cd libssh2-1.11.0/
./configure
make
sudo make install
PHP-SSH2 安裝
官方地址:https://pecl.php.net/package/ssh2
wget https://pecl.php.net/get/ssh2-1.4.tgz
tar -zxvf ssh2-1.4.tgz
cd ssh2-1.4/
/usr/local/php-8.2.14/bin/phpize
./configure --with-php-config=/usr/local/php-8.2.14/bin/php-config
make
make install
php.ini 添加擴展 ssh2.so
sudo vim /usr/local/php-8.2.14/etc/php.ini
extension=ssh2
命令行檢查是否安裝成功
/usr/local/php-8.2.14/bin/php -m|grep ssh2
ssh2
使用
連接遠程服務器與SSH2服務器建立連接是使用PHP SSH2擴展時的第一步。它需要傳遞服務器地址、端口號、用戶名和密碼。連接成功后,您可以執(zhí)行各種遠程操作。以下是一個簡單的連接示例:
用戶名和密碼
$connection = ssh2_connect('tinywan.com', 22);
$res = ssh2_auth_password($connection, "username", "password");
if ($res) {
echo "Authentication Successful! ";
} else {
echo "Authentication Failed! ";
exit(255);
}
SSH 密鑰
$connection = ssh2_connect('192.168.1.204', 22, ['hostkey' => 'ssh-rsa']);
$res = ssh2_auth_pubkey_file($connection, 'tinywan','/home/tinywan/.ssh/id_rsa.pub','/home/tinywan/.ssh/id_rsa');
if ($res) {
echo "Public Key Authentication Successful\n";
} else {
echo('Public Key Authentication Failed');
}
在此示例中,我們成功地連接到端口22上的tinywan.com服務器,并傳遞了正確的用戶名和密碼。遠程執(zhí)行命令 該擴展最常見的用途之一是在遠程服務器上執(zhí)行命令。
以下是一個使用ssh2_exec()函數(shù)執(zhí)行命令并打印輸出的示例:
$connection = ssh2_connect('tinywan.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$stream = ssh2_exec($connection, 'ls -l');
stream_set_blocking($stream, true);
echo stream_get_contents($stream);
在此例子中,我們首先與服務器建立連接,然后使用ssh2_exec()在服務器上執(zhí)行l(wèi)s -l命令。我們通過stream_set_blocking()將流設置為阻塞模式,并使用stream_get_contents()獲取流中的所有內容。輸出打印為遠程命令的執(zhí)行結果。上傳和下載文件 該擴展還允許您在服務器和本地計算機之間上傳和下載文件。在本例中,我們將使用ssh2_scp_send()和ssh2_scp_recv()函數(shù)。
$connection = ssh2_connect('tinywan.com', 22);
ssh2_auth_password($connection, 'username', 'password');
ssh2_scp_send($connection, '/local_file', '/remote_file');
ssh2_scp_recv($connection, '/remote_file', '/local_file');
在此示例中,我們使用ssh2_scp_send()函數(shù)將本地文件/local_file上傳到遠程服務器上的/remote_file路徑。然而,我們也可以使用ssh2_scp_recv()函數(shù)從遠程服務器下載文件到本地。錯誤處理 當使用PHP SSH2擴展時,您需要處理錯誤。在連接、執(zhí)行、上傳和下載操作失敗時,該擴展將會返回錯誤代碼和錯誤信息,以幫助您了解失敗的原因。以下是一個錯誤處理的示例:
$connection = ssh2_connect('tinywan.com', 22);
if (!$connection) {
die('Connection failed.');
}
$auth = ssh2_auth_password($connection, 'username', 'password');
if (!$auth) {
die('Authentication failed.');
}
使用if語句檢查ssh2_connect()和ssh2_auth_password()函數(shù)是否成功執(zhí)行。如果這兩個函數(shù)中的任何一個出現(xiàn)錯誤,它將拋出一個失敗信息并終止腳本的執(zhí)行。
總結 PHP SSH2擴展為用戶提供了一種簡便的方法,在PHP程序中使用SSH進行連接、執(zhí)行命令、上傳和下載文件等操作。它在服務器管理和部署的過程中是非常有用的。在使用該擴展時,需要特別注意錯誤處理,以避免出現(xiàn)不必要的問題。希望通過本文的介紹,您對該擴展有了更多的了解。