PHPで秘密鍵文字列からSSH認証する方法。
PECLのssh2をインストールしている前提とする。
ssh2をインストールする方法は、他に参考サイトがあるので割愛するが、
- php-fedora-atuloader
- php-pear
- php-devel
- libssh2
- libssh2-devel
- gcc
この辺りをインストールしとけば、pecl install ssh2 で入ったと思う。
あとは、extensionに設定して、apache再起動。
後は以下の通り
$sshKey <<<EOD
-----BEGIN RSA PRIVATE KEY-----
~略~
-----END RSA PRIVATE KEY-----
EOD;
$host = '192.168.0.11';
$port = 22;
$user = 'work'
$tmpPrivateKeyPath = TMP.'/keys/'.$host.'_id_rsa';
$tmpPublicKeyPath = TMP.'/keys/'.$host.'_id_rsa.pub';
//接続
$session = ssh2_connect($host, $port);
//鍵の実体化
file_put_contents($tmpPrivateKeyPath , $sshKey);
//キーファイルの権限を変更。 権限正しくないと次の公開鍵作成時に失敗する。
chmod($tmpPrivateKeyPath, 0600);
//公開鍵を作成
$result = exec("ssh-keygen -yf {$tmpPrivateKeyPath} > {$tmpPublicKeyPath}");
//認証
ssh2_auth_pubkey_file($session, $username, $pubkeyfile, $privkeyfile);
//不要なので鍵削除
unlink($tmpPrivateKeyPath);
unlink($tmpPublicKeyPath);
ssh2_auth_pubkey_fileには、実体の鍵ファイルが必要なので、file_put_contentsで実体化して、execでLinuxコマンドのssh-keygenで公開鍵を秘密鍵から作成している。