php を使用してリモート接続を実現する方法: まず SSH2 モジュールをインストールし、次に「ssh2_connect ($host, $port = null, $methods = nullarray, $callbacks = nullarray)」メソッドを通じて接続します。

この記事の動作環境: Windows7 システム、PHP7.1 バージョン、DELL G3 コンピューター
php を使用してリモート接続を実現する方法?
phpでリモート操作を実現
phpを使用してリモート操作を行う場合、SSH2モジュールをインストールする必要があります。 SSH2 モジュールで使用されるいくつかの関数について簡単に記録してみましょう。
一般的な方法
1.接続
1 | ssh2_connect ( $host , $port = null, $methods = nullarray , $callbacks = nullarray )
|
ログイン後にコピー
SSHサーバーに接続
2.認証
1 | ssh2_auth_password ( $session , $username , $password )
|
ログイン後にコピー
SSHパスワードで通常を使用認証用
or
1 | ssh2_auth_pubkey_file ( $session , $username , $pubkeyfile , $privkeyfile , $passphrase = null)
|
ログイン後にコピー
公開鍵による認証
3. ファイル転送
1 | ssh2_scp_send ( resource $session , string $local_file , string $remote_file [, int $create_mode = 0644 ] )
|
ログイン後にコピー
scpプロトコル経由でファイルを送信
1 | ssh2_scp_recv ( resource $session , string $remote_file , string $local_file )
|
ログイン後にコピー
取得scp プロトコルを介してファイルを取得します
4. コマンドを実行します
1 | ssh2_exec ( $session , $command , $pty = null, $env = nullarray , $width = null, $height = null, $width_height_type = null)
|
ログイン後にコピー
リモート マシンでコマンドを実行します
5.その他
1 | ssh2_fetch_stream ( $channel , $streamid ) {}
|
ログイン後にコピー
拡張されたデータ ストリームを取得します。一般的に使用される $streamid 定義は次のとおりです。
1 2 3 | define ('SSH2_STREAM_STDIO', 0);
define ('SSH2_STREAM_STDERR', 1);
stream_set_blocking ( resource $stream , bool $mode )
|
ログイン後にコピー
ストリームをブロッキング/非ブロッキング状態に設定します。 $mode が true の場合はブロッキングであり、$mode が false の場合は非ブロッキングです。
簡単なアプリケーション
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | $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);
stream_set_blocking( $errorStream , true);
stream_set_blocking( $stream , true);
echo stream_get_contents( $stream );
fclose( $errorStream );
fclose( $stream );
}
|
ログイン後にコピー
推奨学習: 「PHP ビデオ チュートリアル 」
以上がPHPを使用してリモート接続を実現する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。