插件窝 干货文章 Linux sshd_config如何配置

Linux sshd_config如何配置

配置 sshd 禁用 SFTP 671    来源:    2025-04-25

Linux sshd_config 配置指南

sshd_config 是 OpenSSH 服务器的主要配置文件,位于 /etc/ssh/sshd_config。以下是一份详细的配置指南:

基本安全配置

  1. 更改默认端口

    Port 2222  # 改为非标准端口(1024-65535)
    
  2. 禁用 root 登录

    PermitRootLogin no
    
  3. 限制用户访问

    AllowUsers user1 user2  # 只允许特定用户
    # 或
    AllowGroups sshusers  # 只允许特定组
    
  4. 禁用密码认证(推荐使用密钥):

    PasswordAuthentication no
    

高级安全配置

  1. 限制登录尝试

    MaxAuthTries 3
    LoginGraceTime 1m
    
  2. 空闲会话超时

    ClientAliveInterval 300
    ClientAliveCountMax 0
    
  3. 禁用不安全的协议和算法

    Protocol 2
    Ciphers aes256-ctr,aes192-ctr,aes128-ctr
    MACs hmac-sha2-512,hmac-sha2-256
    
  4. 限制监听接口

    ListenAddress 192.168.1.100  # 只监听特定IP
    

功能配置

  1. 启用 X11 转发(如果需要):

    X11Forwarding yes
    
  2. SFTP 子系统配置

    Subsystem sftp /usr/lib/openssh/sftp-server
    # 或限制SFTP用户到特定目录
    Subsystem sftp internal-sftp
    Match Group sftpusers
     ChrootDirectory /home/%u
     ForceCommand internal-sftp
     AllowTcpForwarding no
     X11Forwarding no
    
  3. 端口转发

    AllowTcpForwarding yes  # 或no禁用
    GatewayPorts no
    

日志配置

  1. 详细日志LogLevel VERBOSE

应用配置更改

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

sudo systemctl restart sshd
# 或
sudo service ssh restart

验证配置

检查配置语法:

sudo sshd -t

查看当前生效的配置:

sudo sshd -T

最佳实践建议

  1. 修改前备份原配置文件:

    sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
    
  2. 使用 fail2ban 防止暴力破解

  3. 定期更新 OpenSSH 到最新版本

  4. 使用 SSH 密钥认证而非密码认证

  5. 考虑使用两步验证增强安全性

注意:配置更改后,确保不会将自己锁在系统外。建议在另一个终端保持活动会话,或使用类似 screen/tmux 的工具。