scp命令不输密码

在使用scp命令复制文件或ssh登陆到另一台主机时,会提示输入密码。但是在脚本里每次要输入密码比较麻烦,可以使用生成证书登陆。

1、在机器A上生成密钥对(均以root用户为例)

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:
22:2a:6a:31:b9:38:3e:c6:51:e8:b0:5e:a4:b9:7d:7d root@Client

首先提示密钥保存位置,按回车。然后提示输入证书的密码,按回车留空不设置。最后生成了私钥id_rsa和公钥id_rsa.pub。

2、将公钥证书id_rsa.pub复制到另一台机器(机器B)的root目录中/root/.ssh/authorized_keys,这样机器A就可以直接scp或ssh到机器B了。

测试了下,不需要在另一台机器上编辑/etc/ssh/sshd_config开放以下这几项就能使用了:

#RSAAuthentication yes
#PubkeyAuthentication yes
#AuthorizedKeysFile .ssh/authorized_keys

机器B得到了机器A的公钥,机器A就可以不输密码ssh到机器B上了。原理是什么呢?