插件窝 干货文章 教你设置linux的登录方式

教你设置linux的登录方式

SSH 登录 sudo sshd    来源:    2025-05-21

Linux 登录方式设置指南

Linux 系统提供了多种登录方式,可以根据安全需求和使用场景进行配置。以下是主要的登录方式及其设置方法:

1. 密码登录(默认方式)

启用/禁用密码登录

# 编辑SSH配置文件
sudo nano /etc/ssh/sshd_config

# 找到并修改以下行(去掉注释)
PasswordAuthentication yes   # 启用密码登录
PasswordAuthentication no    # 禁用密码登录

# 重启SSH服务
sudo systemctl restart sshd

2. SSH密钥登录(推荐)

生成密钥对(在客户端)

ssh-keygen -t rsa -b 4096   # RSA算法
# 或
ssh-keygen -t ed25519       # 更安全的Ed25519算法

将公钥上传到服务器

ssh-copy-id username@server_ip
# 或手动复制~/.ssh/id_rsa.pub内容到服务器的~/.ssh/authorized_keys文件

确保权限正确

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

3. 双因素认证(2FA)

使用Google Authenticator

# 安装
sudo apt install libpam-google-authenticator   # Debian/Ubuntu
sudo yum install google-authenticator         # CentOS/RHEL

# 配置
google-authenticator

# 编辑PAM配置
sudo nano /etc/pam.d/sshd
# 添加一行
auth required pam_google_authenticator.so

# 编辑SSH配置
sudo nano /etc/ssh/sshd_config
# 确保有
ChallengeResponseAuthentication yes

# 重启SSH
sudo systemctl restart sshd

4. 证书登录(高级)

创建CA证书

# 生成CA密钥
ssh-keygen -t rsa -b 4096 -f ~/.ssh/ca_key

# 签署用户公钥
ssh-keygen -s ~/.ssh/ca_key -I user_identity -n username -V +52w ~/.ssh/user_key.pub

服务器配置

sudo nano /etc/ssh/sshd_config
# 添加
TrustedUserCAKeys /etc/ssh/ca_key.pub

# 将CA公钥复制到指定位置
sudo cp ~/.ssh/ca_key.pub /etc/ssh/

5. 限制登录IP

sudo nano /etc/hosts.allow
# 添加允许的IP
sshd: 192.168.1.100
sshd: 192.168.1.0/24

sudo nano /etc/hosts.deny
# 添加
sshd: ALL

6. 禁用root登录

sudo nano /etc/ssh/sshd_config
# 修改为
PermitRootLogin no

sudo systemctl restart sshd

安全建议

  1. 优先使用SSH密钥登录而非密码
  2. 禁用root直接登录
  3. 修改默认SSH端口(22)
  4. 定期更新系统和SSH服务
  5. 使用fail2ban防止暴力破解
  6. 为不同用户设置不同的权限

故障排查

如果无法登录,检查: - /var/log/auth.log 或 /var/log/secure 中的日志 - 确保SELinux没有阻止访问(可暂时设置为permissive模式测试) - 检查防火墙设置是否允许SSH端口

希望这些信息对您设置Linux登录方式有所帮助!根据您的具体安全需求选择合适的认证方式。