Skip to content

longbertha/linux_setup

Repository files navigation

Linux Server One-Click Optimization & Hardening Script (linux_setup)

English Documentation | 中文说明文档


🚀 Quick Start Pipeline (AI & Dev Automation)

Execute the orchestration bootstrap sequence via root or an explicit sudo-authorized account:

/bin/bash <(wget -qO - https://raw.githubusercontent.com/longbertha/linux_setup/main/server-setup.sh)

Note: Mainland China server acceleration endpoints are currently not supported.


🌟 Overview (English)

An enterprise-grade, one-click system and TCP/IP network stack tuning script tailored for VPS, Cloud Instances, and Bare-Metal servers. It focuses on idempotency and reversibility, making it perfectly safe for continuous execution in production environments. It automatically adapts to different Linux distributions to install security utilities like Fail2ban, optimize memory management, configure advanced network buffers, and implement severe OS hardening.

🎯 Why this script?

  • Environment Adaptive, Not Hardcoded: Features built-in environment detection. It automatically identifies your specific OS (Debian/Ubuntu, CentOS, Fedora, Arch) and active firewall framework (UFW, Firewalld, iptables, nftables) to apply the most natively compliant commands.
  • Dynamic BDP Performance Tuning: Unlike static configurations found online, this script prompts for your actual server latency and bandwidth. It dynamically calculates the Bandwidth-Delay Product (BDP) to custom-tailor optimal TCP window and buffer sizes for your specific machine.

🚀 Key Features & Software Matrix

I. Base Environment & Security Hardening

Icon Feature Technical Mechanics
📦 Package Utility Deployment Installs essential O&M utilities and security software such as Fail2ban automatically.
🔑 SSH Public Key Injection Appends authorized public keys to enable secure, passwordless cryptographic logins.
🛡️ Password Authentication Disabling Disables password-based logins entirely to mitigate automated brute-force attacks.
🚪 SSH Port Alteration Modifies the default SSH port 22 to a non-standard port to avoid malicious mass-scanning.
🔥 Unified Firewall Orchestration Standardizes ports filtering across UFW, Firewalld, and iptables via a unified interface.
🌐 Public DNS Configuration Configures rock-solid, ultra-fast public DNS upstream resolvers (Cloudflare / Google).

II. Memory & Resource Optimization

Icon Feature Technical Mechanics
💾 Swap Space Creation Generates standard virtual memory swap space to eliminate OOM (Out Of Memory) crashes on low-spec VPS.
ZRAM Advanced Integration Deploys compressed RAM-backed block devices (ZRAM) to handle heavy multi-threading overhead efficiently.
📊 Swappiness Parameter Tuning Optimizes the kernel swappiness threshold to prioritize low-latency physical memory utilization.
🧹 Swap Cache Purging Flushes data accumulated within virtual swap spaces gracefully back into physical memory.
🚀 Kernel Parameter Optimization Activates BBR + FQ congestion algorithms and computes customized BDP buffers dynamically.

III. Deep Network & Kernel Engineering

Subsystem Feature Implementation Targeted Performance Yields
Congestion Control BBR + FQ Queuing Discipline Drastically boosts throughput and mitigates network packet loss over long-distance routes.
Connection Lifespan TCP Fast Open (TFO) Eliminates a network round-trip time (RTT) during handshake, accelerating short connections.
TIME_WAIT Tuning Facilitates rapid port recycling, safeguarding high-concurrency connection pools.
Buffer Scaling Dynamic Memory Auto-Buffering Modulates TCP/UDP network socket read/write memory thresholds dynamically based on total RAM.
Responsiveness Advanced Memory Overcommit Calibrates swappiness and dirty_ratio thresholds to guarantee consistent application runtimes.
Connection Tracking Boosting Multiplies nf_conntrack_max capacity to protect states tables from exhausting under DDoS or high load.
Hardware Offload IRQ Affinity Alignment Binds NIC network interrupts cleanly to designated CPU cores and disables buggy hardware offloads.
Reliability Idempotence & Full Reversibility Supports safe recurring execution and includes an absolute uninstallation pipeline.

📈 Benchmarks / Performance Metrics

⚠️ Disclaimer: The numbers provided below represent baseline evaluations performed under the author's isolated lab environment. They are for demonstration purposes only. Real-world performance heavily depends on hardware specifications, kernel drivers, remote routing paths, congestion state, and packet traffic models. Negative optimization may occur under specific edge-case scenarios. Please establish baseline metrics via tools like iperf3, wrk, or sockperf before deployment.

Testing Environment: 2 vCPU / 4GB RAM / 1Gbps Uplink / Debian 12 VPS (Single-Run Evaluation)

Metric / Indicator Stock Server (Before) Optimized Server (After) Performance Delta
TCP Throughput ~650 Mbps ~920 Mbps ↑ Significant Boost
Network Latency (RTT) 45 ms 38 ms ↓ Reduced Latency
Connection Setup Time 3.2 ms 1.8 ms ↓ Accelerated Handshake
Max Concurrent Connections ~10,000 >1,000,000 ↑ Enterprise Scaling

🖥️ Compatibility

Supported OS Distributions

  • Debian: 10 / 11 / 12 (Fully Supported)
  • Ubuntu: 20.04 / 22.04 / 24.04 LTS (Fully Supported)
  • CentOS / RHEL / Stream: 7 / 8 / 9 (Fully Supported)
  • Rocky Linux / AlmaLinux: 8 / 9 (Fully Supported)
  • Arch Linux: Rolling Release (Fully Supported)
  • openSUSE: 15+ (Fully Supported)
  • Alpine Linux: 3.12+ (Partial Support - Non-Systemd Environment)

Core Kernel Requirements

  • Minimum Requirement: Linux Kernel v4.9+ (Native BBR Engine Required)
  • Recommended Version: Linux Kernel v5.4+ (Advanced TCP Stack Stability)

Virtualization Hypervisors

  • Fully Supported (✅): KVM, QEMU, VMware, Xen, Hyper-V
  • Partially Supported (⚠️): OpenVZ (Kernel runtime boundaries locked), LXC / LXD

🌟 Linux 服务器一键配置与优化脚本 (中文)

面向 VPS/云主机/物理机的「一键式」系统与网络栈调优,兼顾可逆与幂等,适合持续运行在生产环境。可根据不同系统自行安装fail2ban等常用软件,可对服务器进行内存、内核和网络优化,可进行安全加固。

⚙️ 设计哲学

  • 环境自适应,而非写死命令:脚本内置了环境检测机制,能自动识别你的操作系统(Debian/Ubuntu, CentOS, Fedora, Arch)和防火墙(UFW, Firewalld, iptables, nftables)。只管选择功能,脚本会用最适合当前环境的方式去执行。
  • 性能优化,而非无脑复制:网上很多优化方案都是直接复制粘贴一堆参数,但每个服务器的网络环境都不同。我的优化脚本会引导你输入服务器的实际延迟和带宽,动态计算带宽延迟积(BDP),为每一台服务器量身定制 TCP 缓冲区大小。这才是真正有效的优化。

🚀 主要功能矩阵

Ⅰ. 基础环境 & 安全设置

图标 功能 描述
📦 安装常用组件 一键装好 Fail2ban 等常用的运维组件,免去繁琐的手动部署。
🔑 添加 SSH 公钥 自动化配置授权公钥,实现安全快速的免密登录。
🛡️ 关闭密码登录 安全加固的核心步骤。关闭密码认证,彻底杜绝针对密码的弱口令爆破。
🚪 修改 SSH 端口 将默认的 22 端口平滑迁移至自定义高位端口,大幅规避公网恶意扫描。
🔥 统一防火墙管理 智能适配系统底层的防火墙架构,提供高度统一的端口及规则配置控制台。
🌐 配置公共 DNS 替换系统本地解析服务,切换至高速稳定的 Cloudflare 与 Google 上游解析。

Ⅱ. 性能 & 资源优化

图标 功能 描述
💾 设置 Swap 交换区 小内存 VPS 的生产救星。配置标准虚拟交换分区,防止应用高负载下内存溢出死机。
配置 ZRAM 内存压缩 Swap的高阶进阶方案。在物理内存中划分高度压缩的交换块空间,并发处理吞吐性能显著。
📊 修改 Swappiness 权重 调整系统对交换区的使用激进程度,优先榨干物理内存性能。
🧹 清理 Swap 缓存 提供手动安全刷回机制,将交换分区中的死数据重新平滑移回物理内存。
🚀 优化内核参数 全面激活 BBR + FQ 网络算法,并根据服务器实际网络拓扑现场计算 BDP 并应用方案。

Ⅲ. 网络与内核底层调优细节说明

  • 拥塞控制系统:激活 BBR + FQ 队列调度机制,最大化挖掘跨国、跨运营商以及高丢包网络下的极限带宽吞吐。
  • 连接会话加速:深度开启 TCP 快速打开 (TFO) 机制,规避传统三次握手往返开销,并对 TIME_WAIT 端口实施快速回收。
  • 内存缓冲调优:抛弃固定大小参数,根据整机内存配额自动精算网络通信套接字的读写缓冲分配上限。
  • 网络容量防护:大幅拓宽内核 nf_conntrack_max 状态追踪表上限,确保服务器在遭遇大流量并发或高网络负载时不发生丢包。
  • 物理硬件优化:实施智能网卡中断 (IRQ Affinity) 绑定绑定到独立 CPU 核心,并针对特定虚拟化环境合理开闭网卡 Offload。

⚠️ 注意事项与合规说明

  • 特权要求:本脚本会触及底层核心内核参数及系统级服务配置,必须使用 root 或具备完整 sudo 特权的账户分发。
  • 安全冗余:修改 SSH 服务通信端口、彻底关闭明文密码认证属于高风险系统操作。请在部署执行前,确保当前控制台拥有另外一条有效、已连接且存活的 SSH 连接会话,以免由于端口被防火墙误拦导致失联。
  • 问题反馈:若该脚本在您的生产基线测试中带来了正向收益,或在特定特异化发行版中遭遇了 Bug,欢迎通过官方渠道提交 GitHub Issues

🤝 鸣谢与衍生作品

About

Automated Linux environment initialization & post-installation setup script for Ubuntu/CentOS/RHEL. 支持开发环境一键配置、常用安全软件与 DevOps 工具链自动化安装、系统内核与网络参数深度性能优化和加固,世界杯备战

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages