本地机器为 A: 10.60.0.105
远程机器为 B: 10.60.0.106
现在需要从A免密码登陆到B。
1、在本地机器A生成密钥
#flykobe@105 ~ $ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/yicheng/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/yicheng/.ssh/id_rsa.
Your public key has been saved in /home/yicheng/.ssh/id_rsa.pub.
The key fingerprint is:
34:a4:62:6e:2a:f4:85:b8:7a:1e:45:41:34:ea:2a:90 yicheng@tj1clnxweb0004
2、将生成的密钥cp到远程机器B下的指定目录
#ssh username@10.60.1.106 "mkdir .ssh; chmod 0700 .ssh"
#scp ~/.ssh/id_rsa.pub username@10.60.1.106:~/.ssh
3、在远程机器B,将d_rsa.pub复制为authorized_keys2
4、配置成功
# ssh username@10.60.0.106 直接登录
2009-7-31 添加:
如果远程机器的密钥被人改动了,那么脚本中如果执行scp,则会阻塞,等待用户输入密码。
如果不希望这种情况发生,并且监测的话,可以使用以下函数,封装scp命令:
secure_scp(){
fromPath="$1"
toPath="$2"
if [[ -z "$fromPath" || -z "$toPath" ]];then
######### mail ##################
echo "empty from or to: $@" >&2
return;
fi
scp -o BatchMode='yes' "$fromPath" "$toPath"
if [ $? -ne 0 ];then
########## mail #################
echo "error to scp from $fromPath to $toPath" >&2
fi
}
注意 scp的-o选项,其中有很多配置可以修改的,具体可以参考man 5 ssh_config。