設定公鑰驗證
1. 使用 Putty 登入到您想要連線的 Unix 伺服器。
2. mkdir .ssh(ssh 前面有一個點)
3. cd .ssh
4. ssh-keygen -t rsa mykey
5. 輸入通行詞組:test
6. ls -al -> 您會找到兩個檔案:mykey 和 mykey.pub
7. cat mykey.pub >>authorized_keys
8. cat mykey
9. 將您在螢幕上看到的內容複製到記事本並儲存為 "c:\mykey"(含引號)
10. cat mykey.pub
11. 將您在螢幕上看到的內容複製到記事本並儲存為 "c:\mykey.pub"(含引號)
<?php
function my_ssh_disconnect($reason, $message, $language)
{
printf("Server disconnected with reason code [%d] and message: %s\n", $reason, $message);
}
$methods = array(
'kex' => 'diffie-hellman-group1-sha1',
'client_to_server' => array(
'crypt' => 'aes256-cbc',
'comp' => 'none',
'mac' => 'hmac-sha1'),
'server_to_client' => array(
'crypt' => 'aes256-cbc',
'comp' => 'none',
'mac' => 'hmac-sha1'));
$callbacks = array('disconnect' => 'my_ssh_disconnect');
function run_cmd($ssh_host, $user_name, $keyfilename, $ssh_command)
{
$connection = ssh2_connect($ssh_host, 22, $methods, $callbacks);
if (!$connection) die('Connection failed');
if (ssh2_auth_pubkey_file($connection, $user_name, $keyfilename.".pub", $keyfilename, 'test'))
{
echo "Public Key Authentication Successful as user: $user_name";
}
else
{
die('Public Key Authentication Failed');
}
$stream = ssh2_exec($connection, $ssh_command);
$i=0;
stream_set_blocking($stream, true);
$line = stream_get_line($stream, 1024, "\n");
while (!feof($stream))
{
echo $line.' ';
$line = stream_get_line($stream, 1024, "\n");
$i++;
}
echo "Count : ".$i;
flush();
unset($stream);
}
function my_ssh_disconnect($reason, $message, $language)
{
printf("Server disconnected with reason code [%d] and message: %s\n",
$reason, $message);
}
$user_name = "USERID";
$keydir = "c:\\";
$search_string = 'needle';
$keyfilename= $keydir.'mykey';
$ssh_host = "foo.bar.com";
$ssh_command = 'grep "'.$search_string.'" /haystack/*.log';
run_cmd($ssh_host, $user_name, $keyfilename, $ssh_command);
$ssh_command = 'ls -al';
run_cmd($ssh_host, $user_name, $keyfilename, $ssh_command);
?>