近期碰到需要使用密钥登录的情况,不同的连接终端的情况不太一样,所以对此总结一番

一、 密钥对生成 注意:本地主机和目的主机需 ping 通 1)确认服务器是否安装有 ssh 以及openssh服务端

[zyy@kube-master ~]$ rpm -qa |grep openssh
openssh-6.6.1p1-25.el7_2.x86_64
openssh-clients-6.6.1p1-25.el7_2.x86_64
openssh-server-6.6.1p1-25.el7_2.x86_64
[zyy@kube-master ~]$ 
[zyy@kube-master ~]$ 
[zyy@kube-master ~]$ systemctl status sshd
● sshd.service - OpenSSH server daemon
   Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2018-05-21 17:40:41 CST; 22h ago
     Docs: man:sshd(8)
           man:sshd_config(5)
 Main PID: 10690 (sshd)
   CGroup: /system.slice/sshd.service
           └─10690 /usr/sbin/sshd -D

2)在目的主机切换到需要使用密钥登录的账户,生成密钥对

[zyy@kube-master ~]$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/zyy/.ssh/id_rsa): 
Created directory '/home/zyy/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/zyy/.ssh/id_rsa.
Your public key has been saved in /home/zyy/.ssh/id_rsa.pub.
The key fingerprint is:
1d:46:32:22:37:b3:ff:f1:14:d9:6f:3c:19:cb:4a:11 zyy@kube-master
The key's randomart image is:
+--[ RSA 2048]----+
|    . = o .  E   |
|     o = +   o.  |
|      .   o o... |
|       . o . .oo+|
|        S o .. =+|
|         . +. ...|
|          . ..   |
|                 |
|                 |
+-----------------+

3)查看生成的密钥、公钥对,权限均设置为 600

[zyy@kube-master .ssh]$ ll
total 8
-rw------- 1 zyy zyy 1679 May 22 16:32 id_rsa           #  私钥
-rw-r--r-- 1 zyy zyy  397 May 22 16:32 id_rsa.pub     # 公钥

4)根据需要修改登录方式

修改 sshd 连接配置文件 vim /etc/ssh/sshd_config

PasswordAuthentication no                         # 不允许密码验证登录
PubkeyAuthentication yes                            # 允许公钥验证登录
AuthorizedKeysFile .ssh/id_rsa.pub            # 指定公钥文件路径

5)将私钥和公钥导出来保存备用

[zyy@kube-master .ssh]$ sz id_rsa id_rsa.pub 

二、使用 Xshell 连接

打开连接终端,设置好主机名,然后设置好连接信息

在连接过程中可能会出现如下错误信息

这是因为在服务端没有加入认证

将公钥追加到一个文件,命名为authorized_keys
[zyy@kube-master .ssh]$ cat id_rsa.pub >authorized_keys

将文件权限设置为 600
[zyy@kube-master .ssh]$ chmod 600 authorized_keys 
[zyy@kube-master .ssh]$ 
[zyy@kube-master .ssh]$ ll
total 12
-rw------- 1 zyy zyy  397 May 22 16:47 authorized_keys
-rw------- 1 zyy zyy 1679 May 22 16:32 id_rsa
-rw------- 1 zyy zyy  397 May 22 16:32 id_rsa.pub

然后我们重新进行连接就OK了

三、使用 SecureCRT 连接

打开CRT,配置连接信息,将密钥认证设置为首选登录方式

然后导入公钥

点击确认,成功连接

参考资料

  1. 基于Xshell使用密钥方式连接远程主机
  2. 在secureCRT中,通过秘钥对连接linux服务器