「PHP」SSH2 関数さわってみた

PHP の SSH2 関数をさわってみたので、その時のメモです。

PECL :: Package :: ssh2
http://pecl.php.net/package/ssh2
PHP: SSH2 - Manual
http://www.php.net/manual/ja/book.ssh2.php

書いてみたサンプルは、
SSH でサーバに接続、認証
・ファイルの生成
・ディレクトリの移動/ディレクトリの内容の表示
・ディレクトリの作成
って感じです。

■ ssh2.php

<?php
$connection = ssh2_connect("***.***.***.***", 22);
if($connection !== false){
  $auth = ssh2_auth_password($connection, "root", "*****"); 
  if($auth !== false) {
    // ファイルの生成
    ssh2_exec($connection, "touch /usr/local/tmp/php/test/hoge.txt");
    
    // ディレクトリの移動・内容の表示
    $stream = ssh2_exec($connection, "cd /usr/local/tmp/php/test; ls;");
    stream_set_blocking($stream, true);
    echo stream_get_contents($stream);
    
    // ディレクトリの作成
    $sftp = ssh2_sftp($connection);
    ssh2_sftp_mkdir($sftp, "/usr/local/tmp/php/uga");
  }
}
?>

ひとまず、上記で動いてそうです。

※ ストリームの扱いがだいぶと怪しい気がしますが、この辺りは「PHP: SSH2 - Manual」にある感じで。

PHP: stream_set_blocking - Manual
http://www.php.net/manual/ja/function.stream-set-blocking.php
PHP: stream_get_contents - Manual
http://www.php.net/manual/ja/function.stream-get-contents.php

以上になります。

< 環境情報 >
CentOS 6.2
PHP 5.3.3