Linux 系统优化

本篇记录一些 Linux 系统常规优化项,可根据实际情况选择参考进行相应优化。

1. 配置静态 IP

配置静态 IP 脚本:static_ip.sh

#!/bin/bash
# 适用系统:centos 7+/rocky Linux 8+/ubuntu 18+
# 下列变量为需要配置的参数,根据情况修改

# 服务器的网卡名称
interface="eno1"
# 静态ip
ip_address="192.168.2.100"
# 子网掩码
netmask="255.255.255.0"
# 子网掩码位数
netmask_numeral="24"
# 网关ip
gateway="192.168.2.1"
# dns服务器ip地址
dns1="8.8.8.8"
dns2="4.2.2.2"

# 主机名
# host_mame="xxx"

# 配置静态 IP 地址(network)
static_ip_network() {	
	systemctl stop NetworkManager
	systemctl disable NetworkManager
  cat << EOF > /etc/sysconfig/network-scripts/ifcfg-$interface
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=$interface
DEVICE=$interface
ONBOOT=yes
IPADDR=$ip_address
NETMASK=$netmask
GATEWAY=$gateway
DNS1=$dns1
DNS2=$dns2
EOF
	echo "ifcfg-$interface 配置文件修改成功"
	echo "正在重启网络配置"
  systemctl restart network
}

# 配置静态 IP 地址(NetworkManager)
static_ip_NetworkManager() {
  nmcli connection modify $interface ipv4.addresses $ip_address/$netmask_numeral
  nmcli connection modify $interface ipv4.gateway $gateway
  nmcli connection modify $interface ipv4.dns "$dns1 $dns2"
  nmcli connection modify $interface ipv4.method manual

  echo "$interface 配置文件修改成功"
	echo "正在重启网络配置"
  nmcli connection down $interface
  nmcli connection up $interface
}

# 配置静态 IP 地址(Ubuntu版本大于等于18)
static_ip_ubuntu() {
	if ! [[ -d /etc/netplan.bak ]]; then
		mv /etc/netplan /etc/netplan.bak
		mkdir /etc/netplan
	fi
  cat << EOF > /etc/netplan/$interface.yaml
network:
	renderer: networkd
  ethernets:
      $interface:
          dhcp4: false
          addresses:
            - $ip_address/$netmask_numeral
          routes:
            - to: default
              via: $gateway
          nameservers:
            addresses: [$dns1,$dns2]
  version: 2
EOF
	chmod 600 /etc/netplan/$interface.yaml
  echo "$interface 配置文件修改成功"
	echo "正在重启网络配置"
  netplan apply
}

# 检查当前用户是否为 root 用户
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 
   exit 1
fi

# 判断系统版本并调用相应的配置函数
if [[ -f /etc/centos-release ]]; then
  centos_version=$(grep -oE '[0-9]+\.[0-9]+' /etc/centos-release | cut -d. -f1)
  if [[ $centos_version -eq 7 ]]; then
    static_ip_network
  elif [[ $centos_version -ge 8 ]]; then
    static_ip_NetworkManager
  else
    echo "Unsupported CentOS version."
    exit 1
  fi
  
elif [[ -f /etc/rocky-release ]]; then
	rocky_version=$(grep -oP '(?<=release )\d+' /etc/rocky-release)
	if [[ $rocky_version -ge 8 ]]; then
  	static_ip_NetworkManager
	else
		echo "Unsupported rocky system."
  	exit 1
  fi
  
elif [[ -f /etc/lsb-release ]]; then
  ubuntu_version=$(grep -oP '(?<=DISTRIB_RELEASE=)[0-9.]+' /etc/lsb-release | cut -d. -f1)
  if [[ $ubuntu_version -ge 18 ]]; then
    static_ip_ubuntu
  else
    echo "Unsupported Ubuntu version."
    exit 1
  fi
else
  echo "Unsupported operating system."
  exit 1
fi
Bash

2. 包管理器优化

2.1. 新系统更新软件包

yum upgrade -y  # 刚装完系统后就立即执行,日后就不要轻易更新了
Bash

2.2. 更换软件包下载源

# 默认国外的yum源(软件仓库)可能比较慢,可以换成国内的。
# 示例为 centos7
# 备份
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
 
# 下载新的 CentOS-Base.repo 到 /etc/yum.repos.d/
curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
 
# 添加epel源
curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
Bash

3. 修改主机名

hostnamectl set-hostname [主机名]  # 根据主机的作用修改主机名,见名知意
Bash

4. 添加主机名解析

vim /etc/hosts  # 编辑好之后,每台机器都发一份
 
172.16.10.11 [主机名]
......
Bash

5. 配置 Tab 键命令自动补全

# 安装 bash-completion
# RedHat/CentOS/Rocky
sudo dnf install bash-completion

# Debian/Ubuntu
sudo apt install bash-completion

# Arch Linux
sudo pacman -S bash-completion

# 立即生效
source /etc/profile.d/bash_completion.sh  
Bash

6. 根据需要选择是否启动 SELinux

# 临时关闭
setenforce  0
 
# 永久关闭,修改完配置后重启主机
sed -i 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config
 
# 查结果
grep "disabled" /etc/selinux/config
Bash

7. 根据需要选择是否启动防火墙

# 临时关闭
systemctl stop firewalld
 
# 设置开机不启动
systemctl disable firewalld
 
iptables -t raw -F  # 清除 raw 表中的所有规则
iptables -t mangle -F  # 清除 mangle 表中的所有规则
iptables -t nat -F  # 清除 nat 表中的所有规则
iptables -t filter -F  # 清除 filter 表中的所有规则
Bash

8. 配置时间同步服务

配置 chrony 与公网时间服务器同步时间:

# 安装
yum -y install chrony

# 修改配置文件
mv /etc/chrony.conf /etc/chrony.conf.bak

cat > /etc/chrony.conf << EOF
server ntp1.aliyun.com iburst minpoll 4 maxpoll 10
server ntp2.aliyun.com iburst minpoll 4 maxpoll 10
server ntp3.aliyun.com iburst minpoll 4 maxpoll 10
server ntp4.aliyun.com iburst minpoll 4 maxpoll 10
server ntp5.aliyun.com iburst minpoll 4 maxpoll 10
server ntp6.aliyun.com iburst minpoll 4 maxpoll 10
server ntp7.aliyun.com iburst minpoll 4 maxpoll 10
driftfile /var/lib/chrony/drift
makestep 10 3
rtcsync
allow 0.0.0.0/0
local stratum 10
keyfile /etc/chrony.keys
logdir /var/log/chrony
stratumweight 0.05
noclientlog
logchange 0.5
EOF

# 重启 chronyd 服务
systemctl restart chronyd.service
systemctl enable chronyd.service
systemctl status chronyd.service
Bash

在服务器集群内可以让一台服务器与公网时间服务器同步时间,其他服务器与该服务器同步:

cat > /etc/chrony.conf << EOF
server [与公网同步时间的服务器ip或可解析的主机名] iburst minpoll 4 maxpoll 10

driftfile /var/lib/chrony/drift
makestep 10 3
rtcsync
allow 0.0.0.0/0
local stratum 10
keyfile /etc/chrony.keys
logdir /var/log/chrony
stratumweight 0.05
noclientlog
logchange 0.5
EOF
Bash

大陆地区常见公网时间服务器地址:

# 阿里云
ntp1.aliyun.com
ntp2.aliyun.com
ntp3.aliyun.com
ntp4.aliyun.com
ntp5.aliyun.com
ntp6.aliyun.com
ntp7.aliyun.com

# 
ntp1.chinacloud.com.cn
ntp2.chinacloud.com.cn
ntp3.chinacloud.com.cn

# 
cn.pool.ntp.org
Bash

时间服务器地址大全

9. SSH 服务优化

SSH 基本优化

10. 管理用户 Sudo 权限配置

普通用户提权

11. 系统内核优化

11.1. ulimit 命令相关

# 基本语法
ulimit [选项] [限制值]

# 常用选项
-H  # 硬限制只能 root 用户设置,一旦被设置以后就不能被非root用户修改
-S  # 软限制,可以由非root用户修改

-a  # 显示所有当前限制
-n  # 打开文件描述符数量
-u  # 用户最大进程数
-s  # 栈大小(Stack)
-v  # 虚拟内存(Virtual Memory)
-m  # 物理内存(RSS)
-t  # CPU 时间(秒)
-f  # 创建文件的最大大小
-c  # 核心转储文件大小(Core Dump)
-l  # 内存锁定大小(Locked Memory)

# 示例:
ulimit -Hn 65535  # 硬限制设打开文件数 65535

ulimit -Sn 5000  # 软限制设打开文件数 5000(不超过硬限制 65535)

# 如果既没有指定-H选项也没有指定-S选项,且为root用户则硬限制和软限制都会被设置。如果是普通用户则只设置软限制。
ulimit -n 5000  

# ulimit 设定的值可以是一个数值,也可以是一些特定的值,比如:hard,soft,unlimited,分别代表当前硬件限制、当前软件限制、不限制。
Bash

上述命令都是临时设置,永久设置方式如下:

# 编辑 /etc/security/limits.conf
echo "* soft nofile 65535" | sudo tee -a /etc/security/limits.conf
echo "* hard nofile 65535" | sudo tee -a /etc/security/limits.conf
# 直接修改limit.conf需要重启机器才能生效

* hard nofile 65535
*  # 表示要限制的用户,* 表示所有用户
hard  # 设定限制类型
nofile  # 要限制的资源类型
65535  # 限制的值


# 在/etc/security/limits.d/下放配置文件优先级更高,并且无需重启系统,退出当前终端重新进入即可生效
cat > /etc/security/limits.d/limits.conf <<'EOF' 
* soft nofile 65535 
* hard nofile 131070 
EOF
Bash

11.2. 调整 pid_max

pid_max 是 Linux 内核中的一个参数,用于定义 系统全局的进程 ID(PID)的最大数值。它决定了系统中同时可以存在的进程、线程和任务(包括轻量级进程 LWP)的最大数量。

# 32 位系统最大值 32768 (2^15),PID 范围:0 ~ 32767
# 64 位系统最大值 4194304 (2^22),PID 范围:0 ~ 4194303

# 查看当前系统值,通常默认值即可,按需调整
cat /proc/sys/kernel/pid_max 
131072
# 临时调整
echo 4194303 > /proc/sys/kernel/pid_max 
# 永久调整
echo "kernel.pid_max= 4194303" | tee -a /etc/sysctl.conf 
sysctl -p
Bash

11.3. 其它内核参数

# 设置
cat >>/etc/sysctl.conf<<EOF
net.ipv4.tcp_fin_timeout = 2
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_keepalive_time = 600
net.ipv4.ip_local_port_range = 4000    65000
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.tcp_max_tw_buckets = 36000
net.ipv4.route.gc_timeout = 100
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_synack_retries = 1
net.core.somaxconn = 16384
net.core.netdev_max_backlog = 16384
net.ipv4.tcp_max_orphans = 16384
net.ipv4.ip_forward = 1
EOF
 
# 生效
sysctl  -p
Bash
上一篇
下一篇