插件窝 干货文章 如何设置CentOS系统以禁用不必要的网络端口和服务

如何设置CentOS系统以禁用不必要的网络端口和服务

sudo iptables systemctl 禁用 91    来源:    2025-04-16

CentOS系统禁用不必要网络端口和服务指南

作为IT工程师,我将为您提供在CentOS系统上禁用不必要网络端口和服务的详细步骤,以增强系统安全性。

1. 识别当前运行的服务和开放端口

首先,我们需要了解系统当前运行的服务和开放的端口:

# 查看运行中的服务
systemctl list-units --type=service --state=running

# 查看监听中的网络端口
netstat -tulnp
# 或者使用ss命令(更现代)
ss -tulnp

# 查看防火墙当前规则(如果使用firewalld)
firewall-cmd --list-all

2. 停止并禁用不必要的服务

根据您的系统用途,以下是一些通常可以禁用的服务:

# 示例:禁用一些常见不必要的服务
sudo systemctl stop bluetooth
sudo systemctl disable bluetooth

sudo systemctl stop cups
sudo systemctl disable cups

sudo systemctl stop avahi-daemon
sudo systemctl disable avahi-daemon

sudo systemctl stop rpcbind
sudo systemctl disable rpcbind

3. 使用防火墙限制端口访问

如果使用firewalld:

# 查看当前区域
firewall-cmd --get-default-zone

# 移除不必要的服务(示例)
sudo firewall-cmd --permanent --remove-service=dhcpv6-client
sudo firewall-cmd --permanent --remove-service=cockpit

# 只允许必要的端口(例如SSH)
sudo firewall-cmd --permanent --add-service=ssh

# 拒绝所有其他入站连接
sudo firewall-cmd --permanent --remove-port=1-65535/tcp
sudo firewall-cmd --permanent --remove-port=1-65535/udp

# 重新加载防火墙
sudo firewall-cmd --reload

如果使用iptables:

# 清空现有规则
sudo iptables -F
sudo iptables -X

# 设置默认策略为拒绝
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT

# 允许本地回环
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A OUTPUT -o lo -j ACCEPT

# 允许已建立的连接
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# 允许SSH(示例)
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# 保存规则(需要安装iptables-services)
sudo service iptables save
sudo systemctl enable iptables

4. 禁用IPv6(如果需要)

如果您的网络不需要IPv6,可以禁用它:

# 编辑sysctl配置
sudo vi /etc/sysctl.conf

# 添加以下内容
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1

# 应用更改
sudo sysctl -p

5. 安装和使用安全扫描工具

安装nmap来检查系统开放的端口:

sudo yum install nmap -y
nmap -sT -O localhost

6. 定期检查

设置定期检查脚本:

# 创建检查脚本
sudo vi /usr/local/bin/security_check.sh

# 内容示例
#!/bin/bash
echo "Running services:"
systemctl list-units --type=service --state=running
echo ""
echo "Open ports:"
ss -tulnp

7. 其他安全建议

  1. 更新系统:定期运行 sudo yum update
  2. 使用SELinux:确保SELinux处于 enforcing 模式 bash sudo getenforce sudo setenforce 1 sudo vi /etc/selinux/config # 设置为enforcing
  3. 禁用root SSH登录:编辑 /etc/ssh/sshd_config 设置 PermitRootLogin no
  4. 使用密钥认证:禁用密码认证,使用SSH密钥

通过以上步骤,您可以有效地减少CentOS系统的攻击面,提高整体安全性。请根据您的具体应用场景调整允许的服务和端口。