使用公私钥登录远程服务器

Jan 30 2019 Linux

使用公私钥登录远程服务器

本机生成公私钥

1
2
3
4
5
6
7
8
9
10
11
12
13
ssh-keygen -t rsa 
# 一直回车默认即可
Generating public/private rsa key pair.
# Key存放路径
Enter file in which to save the key (/lishude/.ssh/id_rsa):
# 输入密码短语(留空则直接回车)
Enter passphrase (empty for no passphrase):
# 重复密码短语
Enter same passphrase again:
Your identification has been saved in /lishude/.ssh/id_rsa.
Your public key has been saved in /lishude/.ssh/id_rsa.pub.
The key fingerprint is:
blah...

拷贝公钥到远程服务器

1
2
#复制公钥到无密码登录的服务器上,22端口改变可以使用下面的命令
ssh-copy-id -i ~/.ssh/id_rsa.pub username@remote_server

修改远程服务器SSH配置文件

1
2
3
4
5
6
7
8
9
10
vim /etc/ssh/sshd_config
#禁用密码验证
PasswordAuthentication no
#启用密钥验证
RSAAuthentication yes
PubkeyAuthentication yes
#指定公钥数据库文件
AuthorsizedKeysFile ~/.ssh/authorized_keys
#重启SSH服务
service ssh restart

注意:AuthorsizedKeysFile ~/.ssh/authorized_keys,如果存在多用户,最好使用绝对路径,因为如果修改文件的是当前环境是root用户,~代表/home/root,否则不同的用户会存在不用密钥也可以登录。

补充一点,当我们使用 xshell 工具的时候,导入的文件是私钥文件,一般名称为 id_rsa,如果导入公钥文件会报错

image

我在阿里云上使用的时候,如果电脑不在身边,其实也可以登录,阿里云默认的Ubuntu真是神奇,比root用户还要高一级的 bot root 用户,当然在系统中看不到,这个可以用来在阿里云后台更改root用户的密码!呃,如果电脑出故障了,如果重置密码,那么公私钥登录的方式也会被暂停,需要重新编辑ssh配置文件..

前段时间爆出xshell存在后门,后来我就不用xshell了,windows下我就直接用git shell登录,虽然麻烦一点,但是安全了很多。