用php實(shí)現(xiàn)遠(yuǎn)程連接的方法:首先安裝SSH2模塊;然后通過“ssh2_connect ($host, $port = null, $methods = nullarray , $callbacks = nullarray)”方法連接即可。
本文操作環(huán)境:windows7系統(tǒng)、PHP7.1版,DELL G3電腦
怎么用php實(shí)現(xiàn)遠(yuǎn)程連接?
php實(shí)現(xiàn)遠(yuǎn)程操作
使用 php 進(jìn)行遠(yuǎn)程操作的時(shí)候,需要安裝SSH2模塊。關(guān)于在SSH2模塊中用到過的幾個(gè)函數(shù),做一個(gè)簡單的記錄。
常用方法
1、連接
ssh2_connect ($host, $port = null, $methods = nullarray , $callbacks = nullarray )
連接到一個(gè) SSH 服務(wù)器
2、認(rèn)證
ssh2_auth_password ($session, $username, $password)
在 SSH 上使用普通密碼進(jìn)行認(rèn)證
或者
ssh2_auth_pubkey_file ($session, $username, $pubkeyfile, $privkeyfile, $passphrase = null)
通過公鑰進(jìn)行認(rèn)證
3、文件傳送
ssh2_scp_send ( resource $session , string $local_file , string $remote_file [, int $create_mode = 0644 ] )
通過 scp 協(xié)議發(fā)送文件
ssh2_scp_recv ( resource $session , string $remote_file , string $local_file )
通過 scp 協(xié)議獲得文件
4、執(zhí)行命令
ssh2_exec ($session, $command, $pty = null, $env = nullarray , $width = null, $height = null, $width_height_type = null)
在遠(yuǎn)程機(jī)器上執(zhí)行命令
5、其他
ssh2_fetch_stream ($channel, $streamid) {}
獲取拓展的數(shù)據(jù)流。常用的$streamid 定義有:
define ('SSH2_STREAM_STDIO', 0); define ('SSH2_STREAM_STDERR', 1); stream_set_blocking ( resource $stream , bool $mode )
設(shè)置流為 阻塞/非阻塞 狀態(tài)。當(dāng) $mode 為 true 時(shí)為阻塞; $mode 為 false 時(shí),則為非阻塞狀態(tài)。
簡單應(yīng)用
//建立連接 $connection = ssh2_connect($host, (int)$port); if (!$connection) { ... ... } //進(jìn)行認(rèn)證 if (!ssh2_auth_password($connection, $user, $password)) { ... ... } //發(fā)送文件 if (!ssh2_scp_send($connection, $sourceFile, $targetFile, 0644)) { ... ... }else{ $stream = ssh2_exec($connection, "stat /tmp/targetFile 2>&1"); $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); // Enable blocking for both streams stream_set_blocking($errorStream, true); stream_set_blocking($stream, true); echo stream_get_contents($stream); // Close the streams fclose($errorStream); fclose($stream); }
推薦學(xué)習(xí):《PHP視頻教程》