用php實現遠程連接的方法:首先安裝SSH2模塊;然后通過“ssh2_connect ($host, $port = null, $methods = nullarray , $callbacks = nullarray)”方法連接即可。
本文操作環境:windows7系統、PHP7.1版,DELL G3電腦
怎么用php實現遠程連接?
php實現遠程操作
使用 php 進行遠程操作的時候,需要安裝SSH2模塊。關于在SSH2模塊中用到過的幾個函數,做一個簡單的記錄。
常用方法
1、連接
ssh2_connect ($host, $port = null, $methods = nullarray , $callbacks = nullarray )
連接到一個 SSH 服務器
2、認證
ssh2_auth_password ($session, $username, $password)
在 SSH 上使用普通密碼進行認證
或者
ssh2_auth_pubkey_file ($session, $username, $pubkeyfile, $privkeyfile, $passphrase = null)
通過公鑰進行認證
3、文件傳送
ssh2_scp_send ( resource $session , string $local_file , string $remote_file [, int $create_mode = 0644 ] )
通過 scp 協議發送文件
ssh2_scp_recv ( resource $session , string $remote_file , string $local_file )
通過 scp 協議獲得文件
4、執行命令
ssh2_exec ($session, $command, $pty = null, $env = nullarray , $width = null, $height = null, $width_height_type = null)
在遠程機器上執行命令
5、其他
ssh2_fetch_stream ($channel, $streamid) {}
獲取拓展的數據流。常用的$streamid 定義有:
define ('SSH2_STREAM_STDIO', 0); define ('SSH2_STREAM_STDERR', 1); stream_set_blocking ( resource $stream , bool $mode )
設置流為 阻塞/非阻塞 狀態。當 $mode 為 true 時為阻塞; $mode 為 false 時,則為非阻塞狀態。
簡單應用
//建立連接 $connection = ssh2_connect($host, (int)$port); if (!$connection) { ... ... } //進行認證 if (!ssh2_auth_password($connection, $user, $password)) { ... ... } //發送文件 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); }
推薦學習:《PHP視頻教程》