利用PHP SSH2擴展實現(xiàn)遠程控制Openwrt

摘要:這篇文章通過PHP SSH2擴展實現(xiàn)遠程控制Openwrt,包括(1)安裝PHP SSH2擴展(2)實現(xiàn)遠程copy文件(3) 執(zhí)行遠程服務(wù)器上的命令并取返回值

最近在研究怎樣才可以遠程操控路由器,通過微信實現(xiàn)路由器WIFI的開關(guān),遠程重啟路由器,查看Aria2下載文件的情況,甚至可以遠程安裝應(yīng)用和更新固件,在電腦上可以通過SSH軟件方便的連接到Openwrt,并對它進行操作,所以我在想PHP是否也有相應(yīng)的擴展,這樣就可以將它架設(shè)在服務(wù)器或者虛擬主機上,在任何地方都可以方便的控制路由器,甚至可以實現(xiàn)智能家居的控制,想想就很美好呢。
php遠程copy文件以及在遠程服務(wù)器中執(zhí)行命令時,所用到的模塊是ssh2,以后所有的操作都依據(jù)ssh2連接句柄完成。

安裝PHP SSH2擴展

在Windows環(huán)境下安裝

1. 下載 php extension ssh2
下載地址 http://windows.php.net/downloads/pecl/releases/ssh2/0.12/
根據(jù)自己PHP的版本去下載,我使用的WAMPSERVER2.5(64bit),PHP版本為5.5.12,是線程安全的,
所以下載的是php_ssh2-0.12-5.5-ts-vc11-x64.zip
2. 解壓完后,會有三個文件,libssh2.dll、php_ssh.dll、php_ssh2.pdb。
3. 將 php_ssh.dll、php_ssh2.pdb 放到你的 php 擴展目錄下 php/ext/ 下。
4. 將libssh2.dll 復(fù)制到 c:/windows/system32 和 c:/windows/syswow64 各一份
5. php.ini中加入 extension=php_ssh2.dll
6. 重啟apache,即可使用php執(zhí)行ssh連接操作了。
查看phpinfo(),是否有顯示php_ssh2擴展加載成功。

在linux環(huán)境下安裝

PHP SSH2擴展需要的依賴庫

openssl: 加密算法集合,C語言實現(xiàn)
libssh2: ssh2協(xié)議庫庫,C語言實現(xiàn)
PECL/ssh2: libssh2的php擴展,允許php程序調(diào)用libssh2中的函數(shù)
依賴關(guān)系:PECL/ssh2 –> libssh2 –> openssl

安裝需要的擴展包

安裝libssh2
wget  http://www.libssh2.org/download/libssh2-1.4.2.tar.gz  
tar zxf libssh2-1.4.2.tar.gz  
cd libssh2-1.4.2  
./configure && make && make install  

安裝PECL/ssh2
wget  http://pecl.php.net/get/ssh2-0.11.3.tgz  
cd ssh2-0.11.3  
phpize   (如果報錯命令沒有找到,apt-get install php5-dev)  
./configure —with-ssh2 && make && make install  

修改php配置信息

cd  /etc/php5/cgi  
vim  php.ini  
添加項:extension=/usr/lib/php5/20090626/ssh2.so  
     ssh2.so是編譯ssh2時得到的模塊,上面是模塊的位置。  


cd  /etc/php5/cli  
vim  php.ini  
添加項:extension=/usr/lib/php5/20090626/ssh2.so  
     ssh2.so是編譯ssh2時得到的模塊,上面是模塊的位置。  

重啟web服務(wù)器

/etc/init.d/lighttpd restart  

查看是否加載了ssh2

[root@localhost ~]php -m | grep s       

SSH2模塊的連接應(yīng)用

通過PECL/ssh2相關(guān)API遠程操作計算機時,首先需要獲取鏈接,使用函數(shù):

session ssh2_connect($host, $port)

SSH2連接有兩種方式,分別是用戶名密碼,ssh密鑰形式。
public key : 通過公鑰和密鑰進行驗證,需要使用openssl生成工密鑰,然后將公鑰上傳到需要遠程訪問機器的指定目錄。特點比較安全,但是不太方便。PECL/ssh2支持。
password : 直接通過用戶名和密碼登錄。特點是很方便,但是不安全,密碼必須已明文的方式傳給ssh2的api。PECL/ssh2支持。
keyboard-interactive:需要用戶手動輸入密碼,PECL/ssh2不支持。

用戶名與密碼

通過用戶名與密碼連接函數(shù)

    bool ssh2_auth_password ( resource $session , string $username , string $password )

通過此方式連接Openwrt,在局域網(wǎng)內(nèi),路由器IP地址:192.168.1.1,默認用戶名:root,密碼:admin。

<?php
    $ipadd = "192.168.1.1";
    $user = "root";
    $pass = "admin";
    $connection = ssh2_connect($ipadd,22);  
    if (ssh2_auth_password($connection,$user,$pass))  
    {  
             echo "Authentication Successful! ";  
    }else{  
             die("Authentication Failed...");  
    }       
?>  

連接結(jié)果
Authentication Successful!

SSH密鑰

通過SSH密鑰連接函數(shù)

bool ssh2_auth_pubkey_file ( resource $session , string $username , string $pubkeyfile , string $privkeyfile [, string $passphrase ] )  

SSH使用密鑰登錄,不僅安全,而且更方便。sshd在~/.ssh/authorized_keys中加入公鑰即可。
而OpenWrt使用dropbear作為服務(wù)端, ~/.ssh/authorized_keys 并不生效。其實,dropbear的公鑰存儲文件是600權(quán)限的/etc/dropbear/authorized_keys 文件,只需將公鑰加入此文件即可。至于其它,與sshd類似。
ssh key可以由secureCRT->Tools->Create Public Key生成,加密算法選擇RSA,通行短語對應(yīng)ssh2_auth_pubkey_file()中的$passphrase,可以不填寫,$pubkeyfile , $privkeyfile為公鑰和私鑰的存放位置,將$pubkeyfile中的內(nèi)容復(fù)制到Openwrt路徑/etc/dropbear/authorized_keys中,并確保權(quán)限為0644。

<?php
    $connection = ssh2_connect('192.168.1.1', 22, array('hostkey'=>'ssh-rsa'));

    if (ssh2_auth_pubkey_file($connection, 'root',
                              'C:/Users/jz/Documents/Identity.pub',
                              'C:/Users/jz/Documents/Identity','798789263')) {
      echo "Public Key Authentication Successful";
    } else {
      die('Public Key Authentication Failed');
}
?>

返回結(jié)果:

Public Key Authentication Successful
//Openwrt系統(tǒng)日志
Aug 12 13:40:53 PandoraBox authpriv.info dropbear[3197]: Child connection from 192.168.1.112:8005
Aug 12 13:40:55 PandoraBox authpriv.notice dropbear[3197]: Pubkey auth succeeded for 'root' with key md5 3d:77:45:b7:d7:7a:79:87:28:5a:5d:3a:76:d5:1f:57 from 192.168.1.112:8005
Aug 12 13:40:55 PandoraBox authpriv.info dropbear[3197]: Exit (root): Disconnect received

獲取服務(wù)器提供的驗證方式

mixed ssh2_auth_none ( resource $session , string $username )
<?php
$host='192.168.1.1';
$user='root';
$port = '22'
// 鏈接遠程服務(wù)器
$connection = ssh2_connect($host,$port);
if (!$connection) die('connection to '.$host.':'.$port.'failed');
echo 'connection OK<br/>';
// 獲取驗證方式并打印
$auth_methods = ssh2_auth_none($connection, $user);
print_r($auth_methods);
?>

返回結(jié)果

connection OK
Array ( [0] => publickey [1] => password )  //服務(wù)器支持用戶名密碼,ssh密鑰形式

SSH2模塊具體功能

實現(xiàn)遠程復(fù)制文件

遠程服務(wù)器文件copy到本地:

bool ssh2_scp_recv ( resource $session, string $remote_file, string $local_file )

Ps: 接收文件時,后面文件名可以為空,如:

<?php
$connection = ssh2_connect('192.168.1.1', 22);
ssh2_auth_password($connection, 'root', 'admin');
ssh2_scp_recv($connection, '/remote/filename', '/local/filename');
?>

本地文件復(fù)制到遠程服務(wù)器

bool ssh2_scp_send ( resource $session, string $local_file, string $remote_file [, int $create_mode] )

Ps:發(fā)送文件時,后面的文件名不能為空,如:

<?php
$connection = ssh2_connect('192.168.1.1', 22);
ssh2_auth_password($connection, 'root', 'admin');
ssh2_scp_send($connection, '/local/filename', '/remote/filename', 0644);
?>

執(zhí)行遠程服務(wù)器上的命令并取返回值

resource ssh2_exec( resource $session, string $command [, string $pty [, array $env [, int $width [, int $height [, int $width_height_type]]]]] )
<?php
    $connection = ssh2_connect('192.168.1.1', 22, array('hostkey'=>'ssh-rsa'));

    if (ssh2_auth_pubkey_file($connection, 'root',
                              'C:/Users/jz/Documents/Identity.pub',
                              'C:/Users/jz/Documents/Identity','798789263')) {
      echo "Public Key Authentication Successful\n";
    } else {
      die('Public Key Authentication Failed');
}
    $stream = ssh2_exec($connection, 'ls /tmp');
    stream_set_blocking($stream,true);  
    echo stream_get_contents($stream); 
?> 

返回結(jié)果

Public Key Authentication Successful
RT2860.dat TZ dhcp.leases etc fstab hosts lib lock log luci-indexcache luci-sessions nmbd nwan_log nwandebug overlay resolv.conf resolv.conf.auto run state wifi_encryption_ra0.dat

Openwrt基本命令

/etc/init.d/aria2 start #開啟Aria2下載任務(wù)
/etc/init.d/aria2 stop #關(guān)閉Aria2下載任務(wù)
wifi down 2>/dev/null #關(guān)閉wifi 
wifi up 2>/dev/null #打開wifi 
/etc/init.d/samba stop #關(guān)閉SAMBA
/etc/init.d/samba start #開啟SAMBA    
/ect/init.d/ccnu start #連接校園網(wǎng)
reboot -f #重啟路由器
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容