温馨提示×

linux服务器登录 怎样实现IP白名单

小樊
372
2024-11-26 20:30:33
栏目: 云计算

在Linux服务器上实现IP白名单,可以通过以下几种方法:

1. 使用iptables

iptables是Linux中最常用的防火墙工具之一,可以用来限制特定IP地址的访问。

步骤:

  1. 安装iptables(如果尚未安装):

    sudo apt-get install iptables
    
  2. 允许特定IP地址

    sudo iptables -A INPUT -s 192.168.1.100 -j ACCEPT
    sudo iptables -A INPUT -s 192.168.1.101 -j ACCEPT
    
  3. 保存iptables规则

    sudo sh -c "iptables-save > /etc/iptables/rules.v4"
    
  4. 设置iptables开机自启动

    sudo apt-get install iptables-persistent
    sudo netfilter-persistent save
    sudo netfilter-persistent start
    

2. 使用ufw(Uncomplicated Firewall)

ufw是一个用户友好的防火墙管理工具,基于iptables

步骤:

  1. 安装ufw(如果尚未安装):

    sudo apt-get install ufw
    
  2. 允许特定IP地址

    sudo ufw allow from 192.168.1.100 to any
    sudo ufw allow from 192.168.1.101 to any
    
  3. 启用ufw

    sudo ufw enable
    

3. 使用SSH密钥认证

通过SSH密钥认证可以进一步增强安全性,只允许特定的公钥进行登录。

步骤:

  1. 生成SSH密钥对(如果尚未生成):

    ssh-keygen -t rsa
    
  2. 将公钥添加到服务器

    ssh-copy-id user@server_ip
    
  3. 编辑SSH配置文件/etc/ssh/sshd_config):

    sudo nano /etc/ssh/sshd_config
    
  4. 添加或修改以下行

    PasswordAuthentication no
    PermitRootLogin no
    
  5. 重启SSH服务

    sudo systemctl restart sshd
    

4. 使用IPtables和SSH结合

如果你希望结合使用iptables和SSH密钥认证,可以在SSH配置中添加额外的规则。

步骤:

  1. 编辑SSH配置文件/etc/ssh/sshd_config):

    sudo nano /etc/ssh/sshd_config
    
  2. 添加或修改以下行

    PasswordAuthentication no
    PermitRootLogin no
    AllowUsers user1@192.168.1.100 user2@192.168.1.101
    
  3. 重启SSH服务

    sudo systemctl restart sshd
    

通过以上方法,你可以在Linux服务器上实现IP白名单,确保只有特定的IP地址能够访问服务器。

0