Press "Enter" to skip to content

我的SSH安全设定

分享一下自己的SSH安全设定(本文基于Ubuntu 18.04 64bit). 大概方面有3个: 1, 建立普通用户zhang3, 并授予sudo权限; 2, 禁止root登陆; 3, 禁用密码登陆, 使用pub key登陆.

1, 建立普通用户zhang3, 并授予相关权限

平时主要使用zhang3用户来登陆, 因此需要客户端的pub key交给zhang3, 让zhang3做好免密码登陆相关设定.

user=zhang3
useradd -m -s /bin/bash $user
passwd $user

# 授予用户sudo权限
echo "$user ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/$user

# 上传公钥, 这里我将公钥上传到$user用户的home目录
cd /home/$user
rz -bey           # 选择 id_rsa.pub 上传

su - $user
mkdir ~/.ssh; \
cat id_rsa.pub >> ~/.ssh/authorized_keys && \
chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys

2, 设定SSH相关权限

sudo sed -i 's/^\#\?PermitRootLogin.*/PermitRootLogin no/g' /etc/ssh/sshd_config
sudo sed -i 's/^\#\?PubkeyAuthentication.*/PubkeyAuthentication yes/g' /etc/ssh/sshd_config
sudo sed -i 's/^\#\?PasswordAuthentication.*/PasswordAuthentication no/g' /etc/ssh/sshd_config
sudo sed -i 's/^\#\?PermitEmptyPasswords.*/PermitEmptyPasswords no/g' /etc/ssh/sshd_config
sudo sed -i 's/^\#\?MaxAuthTries.*/MaxAuthTries 3/g' /etc/ssh/sshd_config

解释:
PermitRootLogin no                 #禁止root远程登陆
PubkeyAuthentication yes           #启用pubkey登陆
PasswordAuthentication no          #禁用密码登陆
PermitEmptyPasswords no            #禁止空密码
MaxAuthTries                       #允许最大失败次数,默认为6


# 也可以最后再确认一下
egrep '^(PermitRoot|Pubkey|Password|MaxAuthTries)' /etc/ssh/sshd_config
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no

有些老版本的sshd_config里面可能会有一项”RSAAuthentication”, 该项也表示启用pub key登陆, 但这是第1代ssh通讯协议使用的配置项, 该选项在CentOS 7及ubuntu 16.04版本以上均已弃用(如果强行加上此选项会收到一个”Deprecated option RSAAuthentication”的提示), 也可以在sshd_config里添加一项”Protocol 2″来表示使用第几代通讯协议.

2 Comments

  1. LOVE 2009-09-12

    好用嘛?说用过?告诉下。。

Your email address will not be published. Required fields are marked *