Last active 1748426794

Init a server from cloud provider

Revision 8558e92b47a06c81b4e099dc369a2ee5e048a699

init.sh Raw
1#!/usr/bin/env bash
2#===============================================================================
3# Concise server preparation script with error confirmation (idempotent)
4#===============================================================================
5
6set -euo pipefail
7export LC_ALL=C
8export LANG=en_US.UTF-8
9export DEBIAN_FRONTEND=noninteractive
10
11#-----------------------------------
12# Colors & Prompts
13#-----------------------------------
14Green="\033[32m"; Red="\033[31m"; Yellow="\033[33m"; Blue="\033[36m"; Font="\033[0m"
15OK="${Green}[ OK ]${Font}"; ERROR="${Red}[FAILED]${Font}"; WARN="${Yellow}[ WARN ]${Font}"
16
17print_ok(){ echo -e "${OK} $1"; }
18print_error(){ echo -e "${ERROR} $1"; }
19print_warn(){ echo -e "${WARN} $1"; }
20
21#-----------------------------------
22# Error handling & confirmation
23#-----------------------------------
24on_error(){ print_error "Error at line $1."; areYouSure; }
25trap 'on_error $LINENO' ERR
26
27areYouSure(){
28 print_warn "Continue despite errors? [y/N]"
29 read -r ans
30 case $ans in [yY]*) print_ok "Continuing...";; *) print_error "Aborted."; exit 1;; esac
31}
32
33#-----------------------------------
34# Helpers
35#-----------------------------------
36run_local(){ print_ok "Local: $*"; "$@"; }
37run_remote(){ sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$SERVER" "$*"; }
38wait_ssh(){
39 print_ok "Waiting for SSH on $SERVER... (Running ssh $REMOTE_USER@$SERVER)"
40 until sshpass -p "$REMOTE_PASS" ssh -q -o StrictHostKeyChecking=no "$REMOTE_USER@$SERVER" exit; do
41 print_warn "SSH not ready, retrying in 5s..."
42 sleep 5
43 done
44 print_ok "SSH available."
45}
46
47usage(){ echo "Usage: $0 <orig_user> <orig_pass> <server> <new_hostname> <new_user>"; exit 1; }
48
49#-----------------------------------
50# Main
51#-----------------------------------
52[ $# -ne 5 ] && usage
53USER="$1"; PASS="$2"; SERVER="$3"; HOSTNAME="$4"; NEWUSER="$5"
54REMOTE_USER="$USER"; REMOTE_PASS="$PASS"
55
56# 1) Install sshpass locally
57run_local sudo apt-get update -y
58run_local sudo apt-get install -y sshpass
59
60# 2) Clear known_hosts, wait for SSH
61run_local ssh-keygen -R "$SERVER" -f ~/.ssh/known_hosts
62wait_ssh
63
64# 3) Hostname & reboot (only if changed)
65CURRENT_HOST=$(run_remote "hostname")
66if [[ "$CURRENT_HOST" != "$HOSTNAME" ]]; then
67 print_ok "Setting hostname to $HOSTNAME"
68 run_remote "sudo hostnamectl set-hostname $HOSTNAME"
69 run_remote "sudo reboot" || true
70 print_ok "Server rebooting..."
71 sleep 5
72 wait_ssh
73else
74 print_ok "Hostname already '$HOSTNAME', skipping"
75fi
76
77# 4) Create or verify new user
78if run_remote "id -u $NEWUSER" &>/dev/null; then
79 print_ok "User $NEWUSER exists"
80else
81 print_ok "Creating user $NEWUSER"
82 run_remote "sudo adduser --disabled-password --gecos '' $NEWUSER"
83fi
84
85# 5) Grant sudo & set up passwordless
86print_ok "Granting sudo to $NEWUSER"
87run_remote "sudo usermod -aG sudo $NEWUSER"
88print_ok "Setting passwordless sudo for $NEWUSER"
89run_remote "echo '$NEWUSER ALL=(ALL) NOPASSWD:ALL' | sudo tee /etc/sudoers.d/$NEWUSER"
90
91# 6) Generate & persist random password (once)
92if run_remote "[ -f /etc/$NEWUSER.pass ]" &>/dev/null; then
93 # In this case, the password is already set
94 print_ok "Don't have to change password. Reusing existing password for $NEWUSER"
95 PASS_NEW=$(run_remote "sudo cat /etc/$NEWUSER.pass")
96else
97 PASS_NEW=$(uuidgen)
98 print_ok "Setting password for $NEWUSER"
99 run_remote "echo '$NEWUSER:$PASS_NEW' | sudo chpasswd"
100 run_remote "echo '$PASS_NEW' | sudo tee /etc/$NEWUSER.pass > /dev/null"
101 run_remote "sudo chmod 600 /etc/$NEWUSER.pass"
102 run_remote "sudo chown root:root /etc/$NEWUSER.pass"
103 print_ok "New password generated for $NEWUSER and persisted at /etc/$NEWUSER.pass. Please back it up! It can still be used to log in via serial console or rescue mode!"
104fi
105
106# 7) Copy SSH key (only if absent)
107[ ! -f ~/.ssh/id_rsa.pub ] && run_local ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa
108PUBKEY=$(<~/.ssh/id_rsa.pub)
109print_ok "Ensuring SSH key in authorized_keys"
110run_remote "mkdir -p /home/$NEWUSER/.ssh && \
111 sudo bash -c 'grep -qxF \"$PUBKEY\" /home/$NEWUSER/.ssh/authorized_keys 2>/dev/null || \
112 echo \"$PUBKEY\" >> /home/$NEWUSER/.ssh/authorized_keys' && \
113 sudo chown -R $NEWUSER:$NEWUSER /home/$NEWUSER/.ssh && \
114 sudo chmod 700 /home/$NEWUSER/.ssh && \
115 sudo chmod 600 /home/$NEWUSER/.ssh/authorized_keys"
116
117# Switch to new user for subsequent operations
118print_ok "Switching to new user $NEWUSER"
119REMOTE_USER="$NEWUSER"; REMOTE_PASS="$PASS_NEW"
120wait_ssh
121
122# 8) Harden SSH
123print_ok "Hardening SSH settings"
124run_remote "sudo sed -i 's/PermitRootLogin yes/PermitRootLogin no/; \
125 s/PasswordAuthentication yes/PasswordAuthentication no/; \
126 s/#PubkeyAuthentication yes/PubkeyAuthentication yes/' /etc/ssh/sshd_config && \
127 sudo systemctl restart sshd"
128
129# 9) Remove other non-system users
130print_ok "Removing other users"
131others=$(run_remote "awk -F: -v skip='$NEWUSER' '\$3>=1000 && \$1!=skip {print \$1}' /etc/passwd")
132for u in $others; do
133 print_warn "Deleting user $u"
134 run_remote "sudo pkill -u $u || true; sudo deluser --remove-home $u"
135done
136
137# 10) Reset machine-id
138print_ok "Resetting machine-id"
139run_remote "sudo rm -f /etc/machine-id /var/lib/dbus/machine-id && \
140 sudo systemd-machine-id-setup && \
141 sudo cp /etc/machine-id /var/lib/dbus/machine-id"
142
143# 11) Enable UFW & OpenSSH
144print_ok "Enabling UFW firewall"
145run_remote "sudo apt-get install -y ufw && sudo ufw allow OpenSSH && echo y | sudo ufw enable"
146
147# 12) Install & configure Fail2Ban
148print_ok "Installing Fail2Ban"
149run_remote "sudo apt-get update && sudo apt-get install -y fail2ban"
150print_ok "Configuring Fail2Ban"
151run_remote <<'EOF'
152sudo tee /etc/fail2ban/jail.local > /dev/null <<EOJ
153[sshd]
154enabled = true
155port = ssh
156filter = sshd
157logpath = /var/log/auth.log
158maxretry = 3
159findtime = 600
160bantime = 3600
161EOJ
162sudo systemctl restart fail2ban
163EOF
164print_ok "Fail2Ban setup complete"
165
166# 13) Enable BBR (only once)
167print_ok "Enabling BBR congestion control"
168run_remote <<'EOF'
169grep -q 'net.ipv4.tcp_congestion_control = bbr' /etc/sysctl.d/99-bbr.conf 2>/dev/null || {
170 sudo tee /etc/sysctl.d/99-bbr.conf > /dev/null <<SYSCTL
171net.core.default_qdisc = fq
172net.ipv4.tcp_congestion_control = bbr
173SYSCTL
174 sudo sysctl --system
175}
176EOF
177
178# 14) Select best mirror & update
179print_ok "Selecting best mirror & updating"
180run_remote "curl -s https://gist.aiursoft.cn/anduin/879917820a6c4b268fc12c21f1b3fe7a/raw/HEAD/mirror.sh | bash"
181run_remote "sudo apt-get update"
182
183# 15) Install latest HWE kernel
184print_ok "Installing latest HWE kernel"
185run_remote "sudo apt-get install -y \$(apt search linux-generic-hwe- | awk -F/ '/linux-generic-hwe-/{print \$1}' | head -1)"
186
187# 16) Reboot & wait
188print_ok "Rebooting server"
189run_remote "sudo reboot" || true
190sleep 5
191wait_ssh
192
193# 17) Final updates & cleanup
194print_ok "Installing upgrades & cleanup"
195run_remote "sudo apt-get update && sudo apt-get upgrade -y && sudo apt-get autoremove -y"
196
197# 18) Performance tuning
198print_ok "Tuning CPU performance & timezone"
199run_remote "sudo apt-get install -y linux-tools-$(uname -r) cpupower && \
200 sudo cpupower frequency-set -g performance || true && \
201 sudo timedatectl set-timezone GMT"
202
203# 19) Remove snap
204print_ok "Removing snapd"
205run_remote "sudo systemctl disable --now snapd && \
206 dpkg -l snapd &>/dev/null && sudo apt-get purge -y snapd && \
207 sudo rm -rf /snap /var/lib/snapd /var/cache/snapd && \
208 sudo tee /etc/apt/preferences.d/no-snap.pref > /dev/null <<EOF
209Package: snapd
210Pin: release a=*
211Pin-Priority: -10
212EOF"
213
214# 20) Final cleanup & benchmark
215print_ok "Final autoremove & benchmark"
216run_remote "sudo apt-get autoremove -y --purge && \
217 sudo apt-get install -y sysbench && sysbench cpu --threads=$(nproc) run && \
218 sudo apt-get autoremove -y sysbench --purge"
219
220print_ok "Setup complete. Connect via: ssh $NEWUSER@$SERVER"
221
222# After this script, server will:
223
224# * Only allow SSH key login
225# * Root login disabled, password authentication disabled
226# * Have a new hostname set
227# * Have a new user with sudo privileges and can log in via SSH
228# * Have a random password stored securely at /etc/<new_user>.pass
229# * Have SSH key copied to authorized_keys so you can log in without a password
230# * Be hardened with UFW, Fail2Ban and allowed SSH connections(only)
231# * Have BBR enabled for better network performance
232# * Have the latest HWE kernel installed
233# * Have the best mirror selected for package updates
234# * Have snap removed
235# * Have CPU performance tuned to 'performance' mode
236# * Have timezone set to GMT
237# * Have all unnecessary users removed (Check /etc/passwd for remaining users)
238# * Have all unnecessary packages removed
239# * Have the latest updates installed
240# * Have sysbench installed for performance testing
241# * Have a final benchmark run to verify CPU performance
242# * Have a final cleanup of unnecessary packages
243
install_fail2ban.sh Raw
1#!/usr/bin/env bash
2set -euo pipefail
3
4echo "[+] Updating package index and installing fail2ban..."
5sudo apt update
6sudo apt install -y fail2ban
7
8echo "[+] Writing /etc/fail2ban/jail.local..."
9sudo tee /etc/fail2ban/jail.local > /dev/null <<'EOF'
10[sshd]
11enabled = true
12port = ssh
13filter = sshd
14logpath = /var/log/auth.log
15maxretry = 3
16findtime = 600
17bantime = 3600
18EOF
19sleep 1
20
21echo "[+] Restarting fail2ban service..."
22sudo systemctl restart fail2ban
23
24echo "=== Fail2Ban global status ==="
25# Allow script to continue even if fail2ban-client status fails (e.g., socket not yet ready)
26sudo fail2ban-client status || true
27
28echo "=== SSHD jail status ==="
29sudo fail2ban-client status sshd || true
30
31echo "Tip: To view the currently banned IP list again, run:"
32echo "sudo fail2ban-client status sshd"
33
34echo "Tip: To unban an IP address, run:"
35echo "sudo fail2ban-client set sshd unbanip <IP_ADDRESS>"
36
37echo "Tip: To ban an IP address manually, run:"
38echo "sudo fail2ban-client set sshd banip <IP_ADDRESS>"
39
40echo "Tip: To view the fail2ban logs, run:"
41echo "sudo journalctl -u fail2ban"
42
mirror.sh Raw
1#!/usr/bin/env bash
2# Step 1: Ensure required packages are installed
3sudo apt update
4sudo apt install -y curl apt-transport-https lsb-release
5
6function switchSource() {
7 # Get current Ubuntu codename (e.g., jammy, focal, bionic)
8 codename=$(lsb_release -cs)
9
10 # Define a list of potential mirrors
11 mirrors=(
12 "https://archive.ubuntu.com/ubuntu/"
13 "https://mirror.aarnet.edu.au/pub/ubuntu/archive/" # Australia
14 "https://mirror.fsmg.org.nz/ubuntu/" # New Zealand
15 "https://mirrors.neterra.net/ubuntu/archive/" # Bulgaria
16 "https://mirror.csclub.uwaterloo.ca/ubuntu/" # Canada
17 "https://mirrors.dotsrc.org/ubuntu/" # Denmark
18 "https://mirrors.nic.funet.fi/ubuntu/" # Finland
19 "https://mirror.ubuntu.ikoula.com/" # France
20 "https://mirror.xtom.com.hk/ubuntu/" # Hong Kong
21 "https://mirrors.piconets.webwerks.in/ubuntu-mirror/ubuntu/" # India
22 "https://ftp.udx.icscoe.jp/Linux/ubuntu/" # Japan
23 "https://ftp.kaist.ac.kr/ubuntu/" # Korea
24 "https://ubuntu.mirror.garr.it/ubuntu/" # Italy
25 "https://ftp.uni-stuttgart.de/ubuntu/" # Germany
26 "https://mirror.i3d.net/pub/ubuntu/" # Netherlands
27 "https://mirroronet.pl/pub/mirrors/ubuntu/" # Poland
28 "https://ubuntu.mobinhost.com/ubuntu/" # Iran
29 "http://sg.archive.ubuntu.com/ubuntu/" # Singapore
30 "http://ossmirror.mycloud.services/os/linux/ubuntu/" # Singapore
31 "https://mirror.enzu.com/ubuntu/" # United States
32 "http://jp.archive.ubuntu.com/ubuntu/" # Japan
33 "http://kr.archive.ubuntu.com/ubuntu/" # Korea
34 "http://us.archive.ubuntu.com/ubuntu/" # United States
35 "http://tw.archive.ubuntu.com/ubuntu/" # Taiwan
36 "https://mirror.twds.com.tw/ubuntu/" # Taiwan
37 "https://ubuntu.mirrors.uk2.net/ubuntu/" # United Kingdom
38 "http://mirrors.ustc.edu.cn/ubuntu/" # 中国科学技术大学
39 "http://ftp.sjtu.edu.cn/ubuntu/" # 上海交通大学
40 "http://mirrors.tuna.tsinghua.edu.cn/ubuntu/" # 清华大学
41 "http://mirrors.aliyun.com/ubuntu/" # 阿里云
42 "http://mirrors.163.com/ubuntu/" # 网易
43 "http://mirrors.cloud.tencent.com/ubuntu/" # 腾讯云
44 "http://mirror.aiursoft.cn/ubuntu/" # Aiursoft
45 "http://mirrors.huaweicloud.com/ubuntu/" # 华为云
46 "http://mirrors.zju.edu.cn/ubuntu/" # 浙江大学
47 "http://azure.archive.ubuntu.com/ubuntu/" # Azure
48 "https://mirrors.isu.net.sa/apt-mirror/" # Saudi Arabia
49 "https://mirror.team-host.ru/ubuntu/" # Russia
50 "https://labs.eif.urjc.es/mirror/ubuntu/" # Spain
51 "https://mirror.alastyr.com/ubuntu/ubuntu-archive/" # Turkey
52 "https://ftp.acc.umu.se/ubuntu/" # Sweden
53 "https://mirror.kku.ac.th/ubuntu/" # Thailand
54 "https://mirror.bizflycloud.vn/ubuntu/" # Vietnam
55 )
56
57 declare -A results
58
59 # Function to test speed of a single mirror
60 test_speed() {
61 url="$1"
62 # Attempt to do a quick GET and measure total time
63 response="$(curl -o /dev/null -s -w "%{http_code} %{time_total}\n" \
64 --connect-timeout 1 --max-time 2 "$url")"
65
66 http_code=$(echo "$response" | awk '{print $1}')
67 time_total=$(echo "$response" | awk '{print $2}')
68
69 # If HTTP code == 200, mark the measured time; otherwise use a large value
70 if [ "$http_code" -eq 200 ]; then
71 results["$url"]="$time_total"
72 else
73 echo "Failed to access $url (HTTP code: $http_code)"
74 results["$url"]="9999"
75 fi
76 }
77
78 echo "Testing all mirrors for Ubuntu '$codename'..."
79 for mirror in "${mirrors[@]}"; do
80 test_speed "$mirror"
81 done
82
83 # Sort mirrors by time_total
84 # Example of sorted_mirrors entry: "https://archive.ubuntu.com/ubuntu/ 0.034"
85 sorted_mirrors="$(
86 for url in "${!results[@]}"; do
87 echo "$url ${results[$url]}"
88 done | sort -k2 -n
89 )"
90
91 echo
92 echo "=== Sorted mirrors by response time (ascending) ==="
93 echo "$sorted_mirrors"
94 echo
95
96 # Pick the top (fastest) mirror from the sorted list
97 fastest_mirror="$(echo "$sorted_mirrors" | head -n 1 | awk '{print $1}')"
98
99 echo "Fastest mirror found: $fastest_mirror"
100 echo "Updating /etc/apt/sources.list..."
101
102 # Update /etc/apt/sources.list with the fastest mirror
103 sudo tee /etc/apt/sources.list >/dev/null <<EOF
104deb $fastest_mirror $codename main restricted universe multiverse
105deb $fastest_mirror $codename-updates main restricted universe multiverse
106deb $fastest_mirror $codename-backports main restricted universe multiverse
107deb $fastest_mirror $codename-security main restricted universe multiverse
108EOF
109
110 # Final check
111 sudo apt update
112 echo "All done!"
113}
114
115# Call the main function
116switchSource