设置公钥认证
1. 使用 putty 登录到你要连接的 Unix 服务器。
2. mkdir .ssh(ssh 前面有一个点)
3. cd .ssh
4. ssh-keygen -t rsa mykey
5. 输入测试密码
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("服务器已断开连接,原因代码为 [%d],消息为:%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('连接失败');
if (ssh2_auth_pubkey_file($connection, $user_name, $keyfilename.".pub", $keyfilename, 'test'))
{
echo "公钥身份验证成功,用户: $user_name";
}
else
{
die('公钥身份验证失败');
}
$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 "计数: ".$i;
flush();
unset($stream);
}
function my_ssh_disconnect($reason, $message, $language)
{
printf("服务器已断开连接,原因代码为 [%d],消息为:%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);
?>