Step 1: 在本地机器上使用ssh-keygen产生公钥私钥对
[root@hk1601 ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
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:
c9:81:9f:3b:3c:f2:dd:f6:c9:c4:10:32:9e:32:24:d1 root@hk1601
The key's randomart image is:
+--[ RSA 2048]----+
| .. |
| oE |
| o o o . |
| = = + . |
| S o . |
| . + o |
| . = o |
| o + ..o . |
| . ....+ |
+-----------------+
Step 2: 将公钥复制到远程机器
[root@hk1601 ~]# ssh-copy-id -i .ssh/id_rsa.pub -p 10022 jilili@125.76.225.126
The authenticity of host '[125.76.225.126]:10022 ([125.76.225.126]:10022)' can't be established.
ECDSA key fingerprint is cb:91:c5:2a:f1:fd:aa:7e:34:9c:d6:8c:e0:30:5f:e1.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
jilili@125.76.225.126's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh -p '10022' 'jilili@125.76.225.126'"
and check to make sure that only the key(s) you wanted were added.
如果没有ssh-copy-id命令可以使用cat,如下:
cat ~/.ssh/id_rsa.pub | ssh root@hk1.ideais.net "cat - >> ~/.ssh/authorized_keys"
Step 3: 登录不要密码了
[root@hk1601 ~]# ssh -p '10022' 'jilili@125.76.225.126'
Welcome to Ubuntu 14.04.3 LTS (GNU/Linux 3.13.0-63-generic x86_64)
* Documentation: https://help.ubuntu.com/
System information as of Mon Jun 20 14:55:44 CST 2016
System load: 0.0 Processes: 165
Usage of /: 26.5% of 28.18GB Users logged in: 1
Memory usage: 54% IP address for eth0: 192.168.106.60
Swap usage: 55% IP address for docker0: 172.17.42.1
Graph this data and manage this system at:
https://landscape.canonical.com/
169 packages can be updated.
99 updates are security updates.
Last login: Mon Jun 20 14:55:45 2016 from 118.193.151.205
jilili@web:~$
限制root仅使用公钥登录
如果想让root用户使用公钥登录,而不能使用密码登录,可以使用以下步骤:
- 先允许root登录,通过修改sshd_config文件
# vi /etc/ssh/sshd_config
...
PermitRootLogin yes
...
- 将公钥发送到服务器端
cat ~/.ssh/id_rsa.pub | ssh root@hk1.ideais.net "cat - >> ~/.ssh/authorized_keys"
- 关闭root密码登录,后面将只能使用公钥登录
# vi /etc/ssh/sshd_config
...
PermitRootLogin without-password
...
