Linux/Ubuntu普通用户(非root)使用秘钥登录SSH
安装Linux/Ubuntu的阿里云ECS默认情况下是使用账号+密码通过SSH登录的,并且默认账户是root,所以这里难免会有安全隐患。因此这里记录一下:Linux/Ubuntu系统怎么设置普通用户(非root用户)使用秘钥登录通过SSH登录远程服务器。
本地SSH Key
检查本地是否已经存在SSH Key 秘钥
输入下面的命令来检查本地是否已经存在秘钥
ls -a ~/.ssh
如果有下面结果则本地已经生成过秘钥了,如果没有那么接下来的步骤生成秘钥
. .. id_rsa id_rsa.pub
生成本地SSH Key 秘钥
输入以下命令
ssh-keygen -t rsa -C "your_email@example.com"
默认会在相应路径下(/your_home_path/.ssh)生成id_rsa
和id_rsa.pub
两个文件,如下面代码所示
Enter file in which to save the key (/your_home_path/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /your_home_path/.ssh/id_rsa.
Your public key has been saved in /your_home_path/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:YgZkAauw6YCWAWwvfiMgJ7zBGkVbFqgRxQ7hdet5nGY your_email@example.com
The key's randomart image is:
+---[RSA 2048]----+
|BO=++o |
|Bo++. . |
|oOo .. |
|+==...o . |
|X+. o+ES |
|=X + o+. |
|.oX . |
|.. |
| |
+----[SHA256]-----+
服务器设置
创建普通用户
使用root用户操作以下命令创建普通用户:
# 创建普通用户,并创建默认目录
useradd -m -s '/bin/bash' user_name
修改用户密码
# 修改密码
passwd user_name
增加普通用户su身份
vi /etc/sudoers
#在最底部加入这一行
user_name ALL=(ALL:ALL) ALL
创建存储密钥的文件夹及文件
使用root用户操作以下命令创建存储密钥的文件夹及文件
#创建文件夹
mkdir /home/user_name/.ssh
#设置文件夹权限
chmod 700 /home/user_name/.ssh
#创建authorized_keys文件
vi /home/user_name/.ssh/authorized_keys
#在authorized_keys文件中插入本地id_rsa.pub文件内容保存并退出
#设置authorized_keys权限
chmod 600 /home/user_name/.ssh/authorized_keys
#修改用户组和用户所有权
chown -R user_name:user_name /home/user_name/.ssh/
#重启ssh服务
sudo service ssh restart
SSH登录安全配置建议
修改默认端口号
使用root用户操作以下命令
# 编辑SSH配置文件
vi /etc/ssh/sshd_config
# 找到 `Port`并修改端口1234(可自定义),然后在阿里控制台中开放该端口,
Port 1234
#保存退出后,重启ssh服务
sudo service ssh restart
禁用root账号登录
使用root用户操作以下命令
# 编辑SSH配置文件
vi /etc/ssh/sshd_config
# 找到 `PermitRootLogin` 并修改no
PermitRootLogin no
#保存退出后,重启ssh服务
sudo service ssh restart
禁用账号+密码登录
使用root用户操作以下命令
# 编辑SSH配置文件
vi /etc/ssh/sshd_config
# 找到 `PasswordAuthentication` 并修改no
PasswordAuthentication no
#保存退出后,重启ssh服务
sudo service ssh restart
未经允许禁止转载!!!!