首頁  >  文章  >  後端開發  >  怎麼用php實現遠端連接

怎麼用php實現遠端連接

藏色散人
藏色散人原創
2021-07-19 09:49:043568瀏覽

用php實現遠端連線的方法:先安裝SSH2模組;然後透過「ssh2_connect ($host, $port = null, $methods = nullarray , $callbacks = nullarray)」方法連接即可。

怎麼用php實現遠端連接

本文操作環境: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影片教學

以上是怎麼用php實現遠端連接的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn