插件窝 干货文章 如何在Linux上配置SSH服务器

如何在Linux上配置SSH服务器

配置 sudo SSH bash 334    来源:    2025-04-16

在Linux上配置SSH服务器指南

SSH (Secure Shell) 是用于安全远程登录和管理Linux服务器的标准协议。以下是配置SSH服务器的详细步骤:

1. 安装SSH服务器

大多数Linux发行版默认安装了SSH服务器(通常是OpenSSH)。如果没有安装:

Debian/Ubuntu:

sudo apt update
sudo apt install openssh-server

RHEL/CentOS:

sudo yum install openssh-server

Arch Linux:

sudo pacman -S openssh

2. 启动SSH服务

启动服务:

sudo systemctl start sshd

设置开机自启:

sudo systemctl enable sshd

检查服务状态:

sudo systemctl status sshd

3. 基本配置

主配置文件位于 /etc/ssh/sshd_config。编辑前建议备份:

sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
sudo nano /etc/ssh/sshd_config

常用配置选项:

  • 更改默认端口 (减少自动化攻击):

    Port 2222
    
  • 禁用root登录 (安全最佳实践):

    PermitRootLogin no
    
  • 限制用户访问:

    AllowUsers username1 username2
    
  • 禁用密码认证 (仅使用密钥):

    PasswordAuthentication no
    
  • 启用公钥认证:

    PubkeyAuthentication yes
    

4. 配置SSH密钥认证

生成密钥对(在客户端):

ssh-keygen -t rsa -b 4096

将公钥复制到服务器:

ssh-copy-id -p [port] username@server_ip

或手动添加公钥到服务器的 ~/.ssh/authorized_keys 文件。

5. 防火墙配置

UFW (Ubuntu):

sudo ufw allow 22/tcp  # 或您自定义的端口
sudo ufw enable

Firewalld (RHEL/CentOS):

sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --reload

6. 应用配置更改

修改配置后需要重启SSH服务:

sudo systemctl restart sshd

7. 测试连接

从另一台机器测试连接:

ssh -p [port] username@server_ip

高级安全配置建议

  1. 使用Fail2Ban 防止暴力破解:

    sudo apt install fail2ban  # Debian/Ubuntu
    sudo yum install fail2ban  # RHEL/CentOS
    
  2. 配置两因素认证 (2FA) 增加安全性

  3. 设置空闲超时:

    ClientAliveInterval 300
    ClientAliveCountMax 2
    
  4. 限制IP访问 (如果可能)

  5. 禁用不安全的加密算法:

    KexAlgorithms curve25519-sha256@libssh.org
    Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
    MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
    

故障排除

  • 连接被拒绝: 检查SSH服务是否运行、防火墙设置和端口是否正确
  • 认证失败: 检查用户名/密码或密钥是否正确,以及sshd_config中的认证设置
  • 查看日志: /var/log/auth.log (Debian/Ubuntu) 或 /var/log/secure (RHEL/CentOS)

通过以上步骤,您应该能够安全地配置Linux SSH服务器。根据您的具体安全需求,可以进一步调整配置参数。