Última actividad 1748426794

Init a server from cloud provider

Revisión 4dc7e9af83e9c66ead8ae38598bb920530af149a

init.sh Sin formato
1#!/bin/bash
2
3#==========================
4# Set up the environment
5#==========================
6set -e # exit on error
7set -o pipefail # exit on pipeline error
8set -u # treat unset variable as error
9
10#==========================
11# Basic Information
12#==========================
13export LC_ALL=C
14export LANG=en_US.UTF-8
15export DEBIAN_FRONTEND=noninteractive
16export SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
17
18#==========================
19# Color
20#==========================
21Green="\033[32m"
22Red="\033[31m"
23Yellow="\033[33m"
24Blue="\033[36m"
25Font="\033[0m"
26GreenBG="\033[42;37m"
27RedBG="\033[41;37m"
28OK="${Green}[ OK ]${Font}"
29ERROR="${Red}[FAILED]${Font}"
30WARNING="${Yellow}[ WARN ]${Font}"
31
32#==========================
33# Print Colorful Text
34#==========================
35function print_ok() {
36 echo -e "${OK} ${Blue} $1 ${Font}"
37}
38
39function print_error() {
40 echo -e "${ERROR} ${Red} $1 ${Font}"
41}
42
43function print_warn() {
44 echo -e "${WARNING} ${Yellow} $1 ${Font}"
45}
46
47#==========================
48# Judge function
49#==========================
50function judge() {
51 if [[ 0 -eq $? ]]; then
52 print_ok "$1 succeeded"
53 sleep 0.2
54 else
55 print_error "$1 failed"
56 exit 1
57 fi
58}
59
60prepare_host()
61{
62 print_ok "Update apt-get"
63 sudo apt-get update
64 judge "Update apt-get"
65
66 print_ok "Install sshpass"
67 sudo apt-get install -y sshpass
68 judge "Install sshpass"
69}
70
71wait_server_till_can_ssh()
72{
73 userName=$1
74 password=$2
75 serverName=$3
76
77 print_ok "Waiting for server to be ready: ssh $userName@$serverName"
78 while true; do
79 set +e
80 sshpass -p $password ssh -o StrictHostKeyChecking=no $userName@$serverName "echo 'Server is ready'"
81 if [ $? -eq 0 ]; then
82 break
83 fi
84 print_warn "Server is not ready yet. Retrying..."
85 sleep 5
86 done
87
88 print_ok "Server is ready to connect via ssh"
89 set -e
90}
91
92prepare_server()
93{
94 userName=$1
95 if [ -z "$userName" ]; then
96 print_error "Please provide username. Usage: prepare_server.sh '<username>' '<password>' '<serverName>' '<desiredHostname>' '<desiredUsername>'"
97 exit 1
98 fi
99
100 password=$2
101 if [ -z "$password" ]; then
102 print_error "Please provide password for user $userName. Usage: prepare_server.sh '<username>' '<password>' '<serverName>' '<desiredHostname>' '<desiredUsername>'"
103 exit 1
104 fi
105
106 serverName=$3
107 if [ -z "$serverName" ]; then
108 print_error "Please provide server name. Usage: prepare_server.sh '<username>' '<password>' '<serverName>' '<desiredHostname>' '<desiredUsername>'"
109 exit 1
110 fi
111
112 desiredHostname=$4
113 if [ -z "$desiredHostname" ]; then
114 echo "Please provide desired hostname. Usage: prepare_server.sh '<username>' '<password>' '<serverName>' '<desiredHostname>' '<desiredUsername>'"
115 exit 1
116 fi
117
118 desiredUsername=$5
119 if [ -z "$desiredUsername" ]; then
120 print_error "Please provide desired username. Usage: prepare_server.sh '<username>' '<password>' '<serverName>' '<desiredHostname>' '<desiredUsername>'"
121 exit 1
122 fi
123
124 prepare_host
125 ssh-keygen -f "/home/anduin/.ssh/known_hosts" -R $serverName
126
127 wait_server_till_can_ssh $userName $password $serverName
128
129 print_ok "Ensure Server is Ubuntu 22.04" # Accept 22.04.1, 22.04.2, etc
130 osVersion=$(sshpass -p $password ssh -o StrictHostKeyChecking=no $userName@$serverName "lsb_release -r | awk '{print \$2}'")
131 if [ "$osVersion" != "22.04" ]; then
132 print_error "Server is not Ubuntu 22.04. Please use Ubuntu 22.04"
133 exit 1
134 fi
135
136 print_ok "Changing hostname for $serverName to $desiredHostname"
137 sshpass -p $password ssh -o StrictHostKeyChecking=no $userName@$serverName "sudo hostnamectl set-hostname $desiredHostname"
138 sshpass -p $password ssh -o StrictHostKeyChecking=no $userName@$serverName "sleep 3"
139 sshpass -p $password ssh -o StrictHostKeyChecking=no $userName@$serverName "sudo reboot" || true
140 sleep 5
141 print_ok "Hostname changed to $desiredHostname"
142 print_warn "Server is rebooting..."
143
144 wait_server_till_can_ssh $userName $password $serverName
145
146 print_ok "Creating a new user..."
147 sshpass -p $password ssh -o StrictHostKeyChecking=no $userName@$serverName "sudo adduser $desiredUsername --gecos 'First Last,RoomNumber,WorkPhone,HomePhone' --disabled-password"
148 judge "User $desiredUsername created"
149
150 print_ok "Setting password for user $desiredUsername"
151 userPassword=$(uuidgen)
152 sshpass -p $password ssh -o StrictHostKeyChecking=no $userName@$serverName "echo $desiredUsername:$userPassword | sudo chpasswd"
153 judge "Password set for user $desiredUsername"
154
155 print_ok "Adding user $desiredUsername to sudo group"
156 sshpass -p $password ssh -o StrictHostKeyChecking=no $userName@$serverName "sudo usermod -aG sudo $desiredUsername"
157 judge "User $desiredUsername created with password $userPassword"
158
159 print_ok "Allowing user $desiredUsername to run sudo without password"
160 sshpass -p $password ssh -o StrictHostKeyChecking=no $userName@$serverName "sudo mkdir -p /etc/sudoers.d"
161 sshpass -p $password ssh -o StrictHostKeyChecking=no $userName@$serverName "sudo touch /etc/sudoers.d/$desiredUsername"
162 sshpass -p $password ssh -o StrictHostKeyChecking=no $userName@$serverName "echo '$desiredUsername ALL=(ALL) NOPASSWD:ALL' | sudo tee -a /etc/sudoers.d/$desiredUsername"
163 judge "User $desiredUsername can run sudo without password"
164
165 # If ~/ssh/id_rsa.pub does not exist, create it
166 if [ ! -f ~/.ssh/id_rsa.pub ]; then
167 print_warn "Creating ssh keys on local machine"
168 ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa
169 fi
170
171 print_ok "Copying ssh keys with ssh-copy-id"
172 sshpass -p $userPassword ssh-copy-id -i ~/.ssh/id_rsa.pub $desiredUsername@$serverName
173 print_ok "SSH keys copied"
174
175 wait_server_till_can_ssh $desiredUsername $userPassword $serverName
176
177 print_ok "Disabling root login, password login and enabling ssh key login"
178 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo sed -i 's/PermitRootLogin yes/PermitRootLogin no/g' /etc/ssh/sshd_config"
179 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config"
180 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo sed -i 's/PubkeyAuthentication no/PubkeyAuthentication yes/g' /etc/ssh/sshd_config"
181 # Uncomment those lines if they are commented
182 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo sed -i 's/#PermitRootLogin no/PermitRootLogin no/g' /etc/ssh/sshd_config"
183 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo sed -i 's/#PasswordAuthentication no/PasswordAuthentication no/g' /etc/ssh/sshd_config"
184 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo sed -i 's/#PubkeyAuthentication yes/PubkeyAuthentication yes/g' /etc/ssh/sshd_config"
185 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo systemctl restart sshd"
186 judge "Disable root login, password login and enabled ssh key login"
187
188 print_ok "Server is ready for $desiredUsername to login. Deleting other users..."
189 otherUsers=$(ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "cat /etc/passwd | grep -v nologin | grep -v false | grep -v root | grep -v sync | grep -v $desiredUsername | cut -d: -f1")
190 for otherUser in $otherUsers; do
191 print_warn "Deleting user $otherUser..."
192 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo pkill -u $otherUser"
193 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo deluser --remove-home $otherUser"
194 done
195
196 print_ok "Resetting machine-id"
197 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo rm /etc/machine-id"
198 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo rm /var/lib/dbus/machine-id"
199 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo systemd-machine-id-setup"
200 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo cp /etc/machine-id /var/lib/dbus/machine-id"
201 judge "Machine-id reset"
202
203 print_ok "Enabling ufw firewall"
204 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo apt-get install -y ufw"
205 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo ufw allow OpenSSH"
206 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "echo 'y' | sudo ufw enable"
207 judge "Ufw firewall enabled"
208
209 print_ok "Enabling BBR if not enabled"
210 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo sysctl net.ipv4.tcp_available_congestion_control | grep -q bbr || echo 'net.core.default_qdisc=fq' | sudo tee -a /etc/sysctl.conf"
211 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo sysctl net.ipv4.tcp_available_congestion_control | grep -q bbr || echo 'net.ipv4.tcp_congestion_control=bbr' | sudo tee -a /etc/sysctl.conf"
212 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo sysctl -p"
213 judge "BBR enabled"
214
215 print_ok "Selecting best mirror"
216 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "curl -s https://gist.aiursoft.cn/anduin/3643fb2cafeb42379d362e33e5f2313a/download/HEAD/mirror.sh | bash"
217 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo apt update"
218 judge "Best mirror selected"
219
220 print_ok "Installing latest kernel..."
221 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo apt install -y linux-generic-hwe-22.04"
222 judge "Latest kernel installed"
223
224 print_ok "Installing updates"
225 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo apt update"
226 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo apt upgrade -y"
227 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo apt autoremove -y"
228 judge "Updates installed"
229
230 print_ok "Rebooting server..."
231 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sleep 3"
232 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo reboot" || true
233 sleep 5
234 print_warn "Server is rebooting..."
235
236 wait_server_till_can_ssh $desiredUsername $userPassword $serverName
237
238 print_ok "Set CPU to performance mode"
239 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo apt install -y linux-tools-common linux-tools-$(uname -r)"
240 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo cpupower frequency-info"
241 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo cpupower frequency-set -g performance" || true
242 judge "CPU set to performance mode"
243
244 print_ok "Set timezone to GMT"
245 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo timedatectl set-timezone GMT"
246 judge "Timezone set to GMT"
247
248 print_ok "Removing snap..."
249 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo systemctl disable --now snapd"
250 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo apt purge -y snapd"
251 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo rm -rf /snap /var/snap /var/lib/snapd /var/cache/snapd /usr/lib/snapd ~/snap"
252 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "cat << EOF | sudo tee -a /etc/apt/preferences.d/no-snap.pref
253Package: snapd
254Pin: release a=*
255Pin-Priority: -10
256EOF"
257 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo chown root:root /etc/apt/preferences.d/no-snap.pref"
258 judge "Snap removed"
259
260 print_ok "Autoremoving apt packages"
261 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo apt autoremove -y --purge"
262 judge "Apt packages autoremoved"
263
264 print_ok "Benchmarking server..."
265 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sudo apt install -y sysbench"
266 ssh -o StrictHostKeyChecking=no $desiredUsername@$serverName "sysbench cpu --threads=\$(nproc) run"
267 judge "Server benchmarked"
268
269 print_ok "Server is ready for use"
270 print_ok "ssh $desiredUsername@$serverName"
271
272 print_layout
273}
274
275print_layout()
276{
277 print_ok "OS information"
278 sudo lsb_release -a
279 print_ok "OS install date"
280 stat -c %w /
281 print_ok "Secure Boot status"
282 sudo mokutil --sb-state
283 print_ok "Root file system"
284 sudo df -Th /
285 print_ok "Boot mode"
286 if [ -d /sys/firmware/efi ]; then echo "Boot mode: UEFI"; else echo "Boot mode: Legacy"; fi
287 print_ok "USB information"
288 sudo lsusb
289 print_ok "Disk layout"
290 sudo lsblk
291 print_ok "All disks information"
292 sudo fdisk -l
293 prprint_okint "Disk usage"
294 sudo df -Th
295 print_ok "Memory information"
296 sudo free -h
297 print_ok "Network information"
298 sudo ip link show
299 print_ok "Firewall status"
300 sudo ufw status
301 print_ok "Network location"
302 curl https://ipinfo.io
303}
304
305# To use this function:
306# Arg1: username
307# Arg2: password
308# Arg3: servername
309# Arg4: Desired hostname
310# Arg5: Desired username
311prepare_server "$@"