ubuntu初始化脚本

已在20.04和22.04验证通过,脚本已脱敏

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
#!/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin  #设置PATH环境变量

#为了兼容dash,测试语句建议使用[ expression ],不要使用[[ expression ]]
#为了兼容dash,[ expression ]中建议使用=,不要使用==
#dash,函数名不支持小横线-


#彩色打印[yes]、[no]、[warning]
#兼容bash和dash,dash的echo不支持-e,echo "\e[32m  [yes]\e[0m"即可
echo_yes() { echo -n "    END: $comment "; bash -c 'echo -e "\e[32m  [yes]\e[0m"'; }  #绿色
echo_no() { echo -n "    END: $comment "; bash -c 'echo -e "\e[31m  [no]\e[0m"'; }  #红色
echo_warning() { echo -n "    END: $comment <$note>"; bash -c 'echo -e "\e[33m  [warning]\e[0m"'; }  #黄色

#显示脚本用法
usage() {
echo "Usage: `basename $0` [-h] [-n hostname] [-p port] [-t timezone] [-c ntp] [-r]
说明:脚本只验证了ubuntu20.04和22.04,其它版本也许能用但不保证!

Options:
    -h             : 显示帮助
    -n hostname    : 设置主机名
    -p port        : 设置ssh端口, 默认2208
    -t timezone    : 设置时区, 默认Asia/Shanghai(查看所有可用时区timedatectl list-timezones)
    -c ntp         : 设置同步的ntp服务器, 默认172.27.246.211
    -r             : 卸载青藤云
"
}

#获取传入参数
get_arguments() {
    while getopts hn:p:t:c:r opt
    do
        case "$opt" in
            h) usage && exit 0;;
            n) set_hostname=${OPTARG};;
            p) set_port=${OPTARG};;
            t) set_tz=${OPTARG};;
            c) set_ntp=${OPTARG};;
            r) remove_qingtengyun;;
            *) usage && exit 1;;
        esac
    done
}

check_ip() {
    comment="检测是否已配置IP和DNS"
    echo "BEGIN: $comment"
    if curl -s http://ip.example.com; then
        echo  #换行
        echo_yes
    else
        echo_no
        exit 1
    fi
}

#用$USER变量检测不准确
#######################################################
#    $ whoami; echo $USER                             #
#    user1                                            #
#    user1                                            #
#    $ su root                                        #
#    Password:                                        #
#    # whoami; echo $USER                             #
#    root                                             #
#    user1                                            #
#######################################################
check_notRoot() {
    comment="检测是否非root执行脚本,sudo用户做免密需要获取用户名"
    echo "BEGIN: $comment"
    if [ "root" = `whoami` ]; then
        echo_no
        exit 1
    else
        echo_yes
    fi
}

set_sudoNopasswd() {
    comment="设置sudo免密"
    echo "BEGIN: $comment"
    echo "$USER   ALL=(ALL:ALL) NOPASSWD:ALL" | sudo tee /etc/sudoers.d/$USER
    echo_yes
}

set_hostname() {
    comment="配置主机名"
    echo "BEGIN: $comment"
    if [ -n "$set_hostname" ]; then  #如果传入hostname参数
        sudo hostnamectl set-hostname $set_hostname
        echo_yes
    else
        note="未设置" && echo_warning
    fi
}

zabbixAgent2004() {
    #文件名
    zabbix_agent_file=zabbix_agent-6.0.33-linux-3.0-amd64-static.tar.gz
    
    #下载文件
    if [ ! -f ${zabbix_agent_file} ]; then
        wget http://172.27.244.250/download/${zabbix_agent_file}
    fi
    
    #创建zabbix用户
    sudo useradd -r -M -s /usr/sbin/nologin zabbix
    
    #安装zabbix agent
    sudo mkdir /usr/local/zabbix && sudo chown zabbix:zabbix /usr/local/zabbix
    sudo tar zxf ${zabbix_agent_file} -C /usr/local/zabbix
    
    #配置
    sudo sed -ri 's/^(Server|ServerActive)=.*$/\1=zabbixproxy.example.com/' /usr/local/zabbix/conf/zabbix_agentd.conf
    ip=$(hostname -I | awk '{print $1}') && sudo sed -i "s/^Hostname=.*$/Hostname=$ip/" /usr/local/zabbix/conf/zabbix_agentd.conf
    sudo sed -i 's/^# Timeout=3/Timeout=20/' /usr/local/zabbix/conf/zabbix_agentd.conf
    
    #添加自定义服务
    echo "添加自定义服务/etc/systemd/system/zabbix-agent.service"
    sudo tee /etc/systemd/system/zabbix-agent.service <<- EOF
[Unit]
Description=Zabbix Agent
After=syslog.target
After=network.target

[Service]
Type=forking
Restart=on-failure
PIDFile=/tmp/zabbix_agentd.pid
KillMode=control-group
ExecStart=/usr/local/zabbix/sbin/zabbix_agentd -c /usr/local/zabbix/conf/zabbix_agentd.conf
ExecStop=/bin/sh -c '[ -n "\$1" ] && kill -s TERM "\$1"' -- "\$MAINPID"
RestartSec=10s
User=zabbix
Group=zabbix

[Install]
WantedBy=multi-user.target
EOF

    sudo systemctl daemon-reload
    sudo systemctl restart zabbix-agent
    sudo systemctl enable zabbix-agent
}

zabbixAgent2204() {
    libmodbus_deb=libmodbus5_3.1.6-2_amd64.deb
    zabbix_agent_deb=zabbix-agent_6.0.33-2+ubuntu22.04_amd64.deb
    
    [ -f ${libmodbus_deb} ] || wget http://172.27.244.250/download/${libmodbus_deb}
    [ -f ${zabbix_agent_deb} ] || wget http://172.27.244.250/download/${zabbix_agent_deb}
    sudo dpkg -i ${libmodbus_deb}
    sudo dpkg -i ${zabbix_agent_deb}
    
    conf=/etc/zabbix/zabbix_agentd.conf
    sudo sed -ri 's/^(Server|ServerActive)=.*$/\1=zabbixproxy.example.com/' $conf
    ip=$(hostname -I | awk '{print $1}') && sudo sed -i "s/^Hostname=.*$/Hostname=$ip/" $conf
    sudo sed -i 's/^# Timeout=3/Timeout=20/' $conf
    
    sudo systemctl restart zabbix-agent
    sudo systemctl enable zabbix-agent
}

set_zabbixAgent() {
    comment="配置zabbix-agent,仅ubuntu20.04和22.04"
    echo "BEGIN: $comment"
    
    #检测是否已安装,简单判断不严谨
    if [ -f /usr/local/zabbix/sbin/zabbix_agentd ] || [ -f /usr/sbin/zabbix_agentd ]; then

        echo "再次配置zabbix_agentd.conf的Hostname,解决克隆已初始化过的虚拟机时Hostname未更新问题"
        if [ $(lsb_release -rs) = "22.04" ]; then
            ip=$(hostname -I | awk '{print $1}') && sudo sed -i "s/^Hostname=.*$/Hostname=$ip/" /etc/zabbix/zabbix_agentd.conf
        elif [ $(lsb_release -rs) = "20.04" ]; then
            ip=$(hostname -I | awk '{print $1}') && sudo sed -i "s/^Hostname=.*$/Hostname=$ip/" /usr/local/zabbix/conf/zabbix_agentd.conf
        fi

        note="已安装,无需重复安装" && echo_warning
    else
        #检查ubuntu版本
        os=$(. /etc/os-release && echo "$VERSION_ID")
        
        #安装
        if [ $os = "22.04" ]; then
            zabbixAgent2204
        elif [ $os = "20.04" ];then
            zabbixAgent2004
        else
            note="非ubuntu20.04或22.04,跳过安装" && echo_warning
            return  #退出函数
        fi
        
        #安装完了再检测一次进程
        if ps -ef | grep -q 'zabbix_agent[d]'; then
            echo_yes
        else
            echo_no
            exit 1
        fi
    fi
}

set_timezone_ntp() {
    comment="配置时区及时间同步,时区默认Asia/Shanghai,NTP默认172.27.246.211"
    echo "BEGIN: $comment"
    #timezone
    set_tz="${set_tz:-Asia/Shanghai}"  #不传时区参数的话,默认设置Asia/Shanghai时区
    sudo timedatectl set-timezone $set_tz
    
    #ntp
    set_ntp="${set_ntp:-172.27.246.211}"  #不传ntp服务器参数的话,默认172.27.246.211
    sudo sed -ri 's/^#?(NTP=).*$/\1'"$set_ntp"'/' /etc/systemd/timesyncd.conf  #正则^#?表示不管NTP那一行是否有注释,直接替换
    sudo systemctl restart systemd-timesyncd
    echo_yes
}

set_openfile_process() {
comment="配置文件打开数及进程数"
echo "BEGIN: $comment"
echo '* soft nofile 204800
* hard nofile 204800
* soft nproc 204800
* hard nproc 204800' | sudo tee /etc/security/limits.d/nofile-noproc.conf
echo_yes
}

set_sshPort() {
    comment="配置ssh端口,默认2208"
    echo "BEGIN: $comment"
    #设置端口
    set_port="${set_port:-2208}"  #不传ssh端口参数的话,默认设置2208
    
    #检测当前ssh端口
    config_port=$(awk '/^Port/{print $2}' /etc/ssh/sshd_config)
    ssh_port="${config_port:-22}"  #如果config_port为空则是22端口
    
    #如果设置端口与当前端口不一致,才执行
    if [ "$set_port" != "$ssh_port" ]; then
        if grep -q '^Port [0-9]\+' /etc/ssh/sshd_config; then  #如果配置文件有指定Port
            sudo sed -ri "s/^Port [0-9]+$/Port $set_port/" /etc/ssh/sshd_config
        else  #否则没有指定Port,比如默认22端口的情况
            echo "Port $set_port" | sudo tee -a /etc/ssh/sshd_config
        fi
        sudo systemctl reload ssh
    fi
    echo_yes
}

set_sshKey() {
    comment="配置密钥"
    echo "BEGIN: $comment"
    [ ! -d ~/.ssh ] && mkdir ~/.ssh
    chmod 700 ~/.ssh
    
    key1="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDmxcc+pBN1C/y/dP0ktjsl6bVnMkLpfENdRJGHM/K4opoRKHrrBNI06ZdznP17n6vOkquHGzmLhp1/0xTgccbAlsogkJ2pvn5I70f4U/nNy root@ansible"
    key2="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC4aJi3XFOoLlTM9+4ZnJ1NvfkVyELN/2RW0JpVzYI020Uevzlt/tz3LLt9FFmwGyN4Cr+XZ29FsotrM3M9De3rwVVTZLzxg6vTMGXjxgwnT root@baoleiji"
    
    if ! grep -q "$key1" ~/.ssh/authorized_keys; then
        echo "$key1" >> ~/.ssh/authorized_keys
    fi
    if ! grep -q "$key2" ~/.ssh/authorized_keys; then
        echo "$key2" >> ~/.ssh/authorized_keys
    fi
    
    chmod 600 ~/.ssh/authorized_keys
    echo_yes
}

set_qingtengyun() {
    comment="配置青藤云"
    echo "BEGIN: $comment"
    #如果没有青藤云进程,则大概率没有安装,这里没有做很严谨的判断是否已经安装
    if ! ps -ef | grep -q 'titan_monito[r]'; then
        #安装
        curl -sL 'http://172.27.246.250/agent/download?k=1xyuuh0s00usnbx1g19i4tf6v8hef687w8hx1rj2&group=1&protocol=0&root=true&runAccount=root&userAdd=false' | sudo bash
        #安装完再检查一次进程
        if ps -ef | grep -q 'titan_monito[r]'; then
            echo_yes
        else
            echo_no
            exit 1
        fi
    else
        note="已安装,无需重复安装" && echo_warning
    fi
}

remove_qingtengyun() {
    comment="卸载青藤云"
    echo "BEGIN: $comment"
    if ! ps -ef | grep -q 'titan_monito[r]'; then
        note="未安装" && echo_warning
        exit 0  #退出脚本
    else
        sudo bash /titan/agent/install_agent.sh disclean
        echo_yes
        exit 0  #退出脚本
    fi
}

set_ufw() {
    comment="关闭防火墙ufw"
    echo "BEGIN: $comment"
    sudo systemctl stop ufw
    sudo systemctl disable ufw
    echo_yes
}


#主函数
main() {
    get_arguments "$@"
    
    #兼容bash和dash,dash不支持数组,不支持C风格的for循环
    #首先检查是否普通用户执行脚本
    func="check_notRoot check_ip set_sudoNopasswd set_hostname set_timezone_ntp set_sshPort set_sshKey set_openfile_process set_zabbixAgent set_ufw set_qingtengyun"
    count=$(echo $func | awk '{print NF}')
    begin=1
    for f in $func; do
        echo -n "$begin/$count) "; $f
        begin=$((begin+1))
    done
}


#脚本执行入口
main "$@"