85 lines
2.5 KiB
Bash
Executable File
85 lines
2.5 KiB
Bash
Executable File
#!/bin/bash
|
||
# 脚本功能:修改Ubuntu Server 24.04的端口连接数限制
|
||
# 使用方法:sudo bash tune_connection_limits.sh
|
||
|
||
# 检查是否以root权限运行
|
||
if [ "$(id -u)" -ne 0 ]; then
|
||
echo "错误:请使用root权限运行此脚本(sudo bash $0)" >&2
|
||
exit 1
|
||
fi
|
||
|
||
# 备份原始配置文件
|
||
backup_configs() {
|
||
echo "正在备份原始配置文件..."
|
||
[ -f /etc/security/limits.conf ] && cp -n /etc/security/limits.conf /etc/security/limits.conf.bak
|
||
[ -f /etc/pam.d/common-session ] && cp -n /etc/pam.d/common-session /etc/pam.d/common-session.bak
|
||
}
|
||
|
||
# 修改文件描述符限制
|
||
configure_file_descriptors() {
|
||
echo "正在配置文件描述符限制..."
|
||
|
||
# 添加 limits.conf 配置
|
||
cat << EOF | tee -a /etc/security/limits.conf > /dev/null
|
||
# 增加文件描述符限制(由tune_connection_limits.sh添加)
|
||
* soft nofile 65535
|
||
* hard nofile 655350
|
||
root soft nofile 65535
|
||
root hard nofile 655350
|
||
EOF
|
||
|
||
# 启用 pam_limits 模块
|
||
if ! grep -q "pam_limits.so" /etc/pam.d/common-session; then
|
||
echo "session required pam_limits.so" >> /etc/pam.d/common-session
|
||
fi
|
||
}
|
||
|
||
# 配置内核网络参数
|
||
configure_kernel_parameters() {
|
||
echo "正在配置内核网络参数..."
|
||
|
||
# 创建自定义sysctl配置文件
|
||
cat << EOF | tee /etc/sysctl.d/99-network-tweaks.conf > /dev/null
|
||
# 网络连接优化参数(由tune_connection_limits.sh添加)
|
||
fs.file-max = 1000000
|
||
|
||
# TCP连接队列设置
|
||
net.core.somaxconn = 65535
|
||
net.core.netdev_max_backlog = 65535
|
||
|
||
# 本地端口范围
|
||
net.ipv4.ip_local_port_range = 1024 65535
|
||
|
||
# TCP超时与复用设置
|
||
net.ipv4.tcp_fin_timeout = 30
|
||
net.ipv4.tcp_tw_reuse = 1
|
||
net.ipv4.tcp_tw_recycle = 0
|
||
|
||
# 最大连接数相关设置
|
||
net.ipv4.tcp_max_syn_backlog = 65535
|
||
net.ipv4.tcp_max_tw_buckets = 200000
|
||
EOF
|
||
|
||
# 应用内核参数
|
||
sysctl --system > /dev/null
|
||
}
|
||
|
||
# 显示配置结果
|
||
show_results() {
|
||
echo -e "\n配置已完成,当前关键参数值:"
|
||
echo "-------------------------"
|
||
echo "文件描述符软限制:$(ulimit -Sn)"
|
||
echo "文件描述符硬限制:$(ulimit -Hn)"
|
||
echo "系统最大文件数:$(cat /proc/sys/fs/file-max)"
|
||
echo "监听队列最大长度:$(sysctl -n net.core.somaxconn)"
|
||
echo "本地端口范围:$(sysctl -n net.ipv4.ip_local_port_range)"
|
||
echo "-------------------------"
|
||
echo "请重启系统使所有配置完全生效:sudo reboot"
|
||
}
|
||
|
||
# 主流程
|
||
backup_configs
|
||
configure_file_descriptors
|
||
configure_kernel_parameters
|
||
show_results
|