有些时候,我们在复制/移动文件到另一台机器时会用到scp,因为它比较安全。但如果每次

都要输入密码,就比较烦了,尤其是在script里。不过,ssh有另一种用密钥对来验证的方

式。下面写出我生成密匙对的过程,供大家参考。

第一步:生成密匙对,我用的是rsa的密钥。使用命令 "ssh-keygen -t rsa"

[root@test .ssh]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
30:75:48:6c:2b:46:a6:e3:13:32:7e:4e:60:7f:6e:34 root@test.com
生成的过程中提示输入密钥对保存位置,直接回车,接受默认值就行了。接着会提示输入一 

个不同于你的password的密码,直接回车,让它空着。当然,也可以输入一个。(我比较懒

,不想每次都要输入密码。) 这样,密钥对就生成完了。

其中公共密钥保存在 ~/.ssh/id_rsa.pub
私有密钥保存在 ~/.ssh/id_rsa

然后改一下 .ssh 目录的权限,使用命令 "chmod 755 ~/.ssh"
[root@test ~]# chmod 755 .ssh

之后把这个密钥对中的公共密钥复制到你要访问的机器上去,并保存为 

~/.ssh/authorized_keys.
[root@zld ~]# scp root@10.99.99.52:/root/.ssh/id_rsa.pub /root/.ssh
The authenticity of host '10.99.99.52 (10.99.99.52)' can't be established.
RSA key fingerprint is fb:66:53:4c:ea:90:45:03:65:e7:02:ad:aa:ab:62:d5.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.99.99.52' (RSA) to the list of known hosts.
reverse mapping checking getaddrinfo for bogon failed - POSSIBLE BREAK-IN ATTEMPT!
root@10.99.99.52's password:
id_rsa.pub                                    100%  395     0.4KB/s   00:00   


之这样就大功告成了。之后你再用ssh scp sftp 之类的访问那台机器时,就不用输入密码 了,用在script上更是方便。
[root@test ~]# scp root@10.99.99.50:/root/install.log /root
install.log                                   100%   41KB  40.5KB/s   00:00