Linux 服务器初始化

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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526

#!/bin/bash
# Description : 系统初始化脚本
# File name : init.sh
# Author : medivh
# date : 2019-06-30
# last update : 2019-07-17

base_dir=$(cd `dirname $0` && pwd)
cd $base_dir
# 需要添加的用户名及sshkey公钥

USERNAMES=()
USERKEYS=()
ADMIN_USER_NUM="0 1 11"
SANGUO_USER_NUM="12"
ALL_USER_NUM="`for((i=0;i<${#USERNAMES[@]};i++));do echo $i; done`"
USER_NUMS="$ADMIN_USER_NUM $BACKUP_USER_NUM "
# sudo用户列表
WHELL_USER=""
# 系统管理员邮箱
SYSTEM_ADMIN_EMAIL="op@haoqidai.com"

# zabbix服务端IP
ZABBIX_SERVER_IP="10.144.48.89"
# 时间服务器同步
NTPDATE_SERVER="0.debian.pool.ntp.org"
#NTPDATE_SERVER="cn.pool.ntp.org"
#保持开机启动的服务,其它关闭,参考http://www.linuxidc.com/Linux/2012-11/74439.htmhttp://www.server-world.info/en/note?os=CentOS_6&p=initial_conf&f=4
KEEP_START_SERVICES="lvm2-monitor iptables network auditd rsyslog irqbalance messagebus blk-availability haldaemon udev-post qpidd rpcbind spice-vdagentd sshd crond redis-2.8 zookeeper jsvc zabbix-agent zabbix-proxy";
# 标识服务或软件已经安装
INSTALLED=99
#下载配置文件及文件地址
#WGET_URL="http://115.28.59.215:9281/"
WGET_URL="http://10.144.48.89:9281/"
#获取机房名缩写
idc_name=`hostname|awk -F. '{print $(NF-2)}'`
#如果是jsysh的主机则启动代理
if [ "$idc_name" == "jsysh" ];then
export http_proxy=http://10.140.5.9:9289/
fi
# zookeeper的配置IPs
ZOOKEEPER_IPS="
"
########### DEFINE FILES AND VARIABLES HERE ##############
H_OFFICE='118.186.238.188 118.186.238.187 115.28.59.215 123.57.60.191 118.186.238.194 ' #好期待公司及vpn IP
CHECK_ITEM='115\.28\.59\.215' #此项为检查配置中是否存在,存在则不执行初始化iptables
OPEN_IPS='' ###允许访问的独立IP
H_SEG='10.0.0.0/8' ###允许访问的内网段
P_SSHD='22' #ssh登录端口
OPEN_PORT='' #默认对外开放端口
NF_IPT='/usr/local/iptables/sbin/iptables'
NF_SV='/usr/local/iptables/sbin/iptables-save'
NF_RT='/usr/local/iptables/sbin/iptables-restore'
IPTABLES_CONFIG='/etc/sysconfig/iptables'
################ BEGINNING OF MAIN #######################

# 修改hostname
update_hostname(){
host_name=$1
if [ -z "$host_name" ];then
echo "Waring: The host name is empty !"
echo "Waring: usages: ./init.sh <hostname>"
echo "Waring: hostname example: web.IP.qd-b.qsc"

if [ "$host_name" == "localhost.localdomain" ];then
read -p "please input hostname " host_name
if [ -z $host_name ] ;then
echo "Error: The host name is `hostname`, Please modify!!!"
return 1
fi
else
echo "Waring: The host name is `hostname` , no change !"
return ${INSTALLED}
fi
fi

if [ "$host_name" == `hostname` ];then
echo "Waring: The host name has no changed !"
return ${INSTALLED}
fi

oldHostname=`hostname`
hostname ${host_name} && sed -r -i "s/^HOSTNAME=.*/HOSTNAME=${host_name}/g" /etc/sysconfig/network && \
if ! grep ${host_name} /etc/hosts &>/dev/null ;then
echo "127.0.0.1 ${host_name}" >> /etc/hosts
else
sed -r -i "s/${oldHostname}/${host_name}/g" /etc/hosts
fi && \
echo "The hostname ${host_name} is update success!"
return 0
}
# 从测试服下载文件
wget_item(){
for item in $*;do
wget $WGET_URL/$item
done
}
# 下载 yum 源
wget_repo(){
if ! ls /etc/yum.repos.d/haoqidai.repo &> /dev/null ;then
cd /etc/yum.repos.d/
wget_item 'repo/haoqidai.repo' && \
#mkdir -p back
#mv [eE]pel.repo back/
yum clean all
yum makecache
else
echo "Waring: The hqd repo is already installed !"
fi
}
# 开启sudo wheel用户组
modify_sudo(){
sed -i "/wheel.*NOPASSWD/s/^# //" /etc/sudoers && \
grep "%wheel.*NOPASSWD:[[:space:]]ALL.*\!\/bin\/su" /etc/sudoers || sed -i "s#%wheel.*NOPASSWD:[[:space:]]ALL#&,!/bin/su#" /etc/sudoers
name=backup
grep "$name ALL=NOPASSWD: /bin/tar,/bin/cp" /etc/sudoers || echo "$name ALL=NOPASSWD: /bin/tar,/bin/cp" >> /etc/sudoers
sed -i "/^Defaults.*${name}.*requiretty/b;t;s/^Defaults requiretty/Defaults:${name} \!requiretty/;t;/^Defaults.*\!requiretty/s/^Defaults:/&${name},/" /etc/sudoers
name=zabbix;sed -i "/^Defaults.*${name}.*requiretty/b;t;s/^Defaults requiretty/Defaults:${name} \!requiretty/;t;/^Defaults.*\!requiretty/s/^Defaults:/&${name},/" /etc/sudoers
}
# sudo添加jsvc用户
add_sudo_jsvc_user(){
grep -F "$JSVC_USERS ALL=NOPASSWD: /etc/init.d/jsvc,/bin/ls" /etc/sudoers || echo "$JSVC_USERS ALL=NOPASSWD: /etc/init.d/jsvc,/bin/ls" >> /etc/sudoers
}
# sudo添加deploy用户
add_sudo_deploy_user(){
grep -F "$DEPLOY_USER ALL=NOPASSWD: /bin/chown,/usr/bin/rsync,/bin/mkdir" /etc/sudoers || echo "$DEPLOY_USER ALL=NOPASSWD: /bin/chown,/usr/bin/rsync,/bin/mkdir" >> /etc/sudoers
grep "^\<fancy:x:.*\>" /etc/group || sudo groupadd fancy
grep "^\<fancy:x:.*$DEPLOY_USER\>" /etc/group || sudo sed -i "s/^fancy:x:.*/&$DEPLOY_USER/" /etc/group
}
# sudo wheel 中添加用户
add_sudo_wheel_user(){
if [ ! -z $1 ];then
WHELL_USER=$1
fi
for username in $WHELL_USER;do
grep "^\<^wheel:x:10:.*$username\>" /etc/group || gpasswd -a $username wheel #sed -i "s/^wheel:x:10:/&$username/" /etc/group
done
}
# 关闭服务及自启动
close_service(){
chkconfig --level 3 $1 off
echo "---stop $1---"
service $1 stop
}
# 开启服务及自启动
start_service(){
chkconfig --level 3 $1 on
service $1 start
}
# 关闭不需要的服务
close_services(){
# selinux
setenforce 0;sed -i '/SELINUX=/s/enforcing/disabled/' /etc/selinux/config
# 只保留必要的启动服务
for item in `chkconfig --list|grep 3:on|awk '{print $1}'`;do
echo "$KEEP_START_SERVICES"|grep $item &>/dev/null || close_service $item;
done
for item in $KEEP_START_SERVICES; do
start_service $item;
done && \
echo "Info: 初始化启动服务完成!"
}
# ulimit设置
modify_ulimit(){
if grep "soft[[:space:]]nofile" /etc/security/limits.conf &> /dev/null ;then
echo "Waring: The unlimit has the optimization!"
return ${INSTALLED}
fi
echo "
* soft nofile 65535
* hard nofile 65535" >> /etc/security/limits.conf && \
echo "ulimit -c unlimited" >> /etc/profile
}

# 设置防火墙
build_iptables(){
if grep "$CHECK_ITEM" $IPTABLES_CONFIG &> /dev/null; then
echo "Waring: The iptables has been initialized !"
return ${INSTALLED}
fi
if [ ! -f $NF_IPT ]; then
if [ ! -f `whereis iptables |awk '{print $2}'` ];then
echo "Error: Plese install iptables, first."
exit 4
else
NF_IPT=`whereis iptables |awk '{print $2}'`
NF_SV=`whereis iptables-save |awk '{print $2}'`
fi
else
ln -s $NF_IPT /sbin/iptables
ln -s $NF_SV /sbin/iptables-save
fi
#Clear default rules
$NF_IPT -F
$NF_IPT -X
#Permit local access
$NF_IPT -A INPUT -i lo -j ACCEPT
#Office Access SSH
for H_IP in $H_OFFICE;do
$NF_IPT -A INPUT -p tcp -s $H_IP --dport $P_SSHD -j ACCEPT
done
# SSH端口暂时开放对外所有IP
$NF_IPT -A INPUT -p tcp --dport $P_SSHD -j ACCEPT
#Open 80 Access
for port in $OPEN_PORT;do
$NF_IPT -A INPUT -p tcp --dport $port -j ACCEPT
done
#Open SEG_IP Access
for SEG_IP in $H_SEG;do
$NF_IPT -A INPUT -s $SEG_IP -j ACCEPT
done
#Open udp
$NF_IPT -A INPUT -p udp -j ACCEPT
#Open ips
for ip in $OPEN_IPS;do
$NF_IPT -A INPUT -s $ip -j ACCEPT
done
#Open ping
$NF_IPT -A INPUT -p icmp --icmp-type echo-request -m limit --limit 100/s --limit-burst 150 -j ACCEPT
$NF_IPT -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT
#Deault rules
$NF_IPT -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
$NF_IPT -P INPUT DROP
$NF_IPT -P FORWARD DROP
$NF_SV>$IPTABLES_CONFIG
}
# 系统内核优化
optimize_kernel(){
if grep "tcp_tw_recycle" /etc/sysctl.conf &> /dev/null ;then
echo "Waring: The sysctl has been optimized !"
return ${INSTALLED}
fi
# 开启core dump file size
grep "ulimit -c unlimited" /etc/profile || echo "ulimit -c unlimited" >> /etc/profile
source /etc/profile
# 修改core dump 文件生成的位置及名称
#echo '/tmp/core_%e_%p_%s_%t' > /proc/sys/kernel/core_pattern
#grep '/tmp/core_' /etc/rc.local || echo "echo '/tmp/core_%e_%p_%s_%t' > /proc/sys/kernel/core_pattern" >> /etc/rc.local

modprobe nf_conntrack && \
modprobe ip_conntrack && \
modprobe bridge && \
echo "
modprobe nf_conntrack
modprobe ip_conntrack
modprobe bridge" >> /etc/rc.d/rc.local && \
echo "
net.ipv4.tcp_max_tw_buckets = 5000
net.ipv4.tcp_sack = 1
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_rmem = 4096 8388608 16777216
net.ipv4.tcp_wmem = 4096 8388608 16777216
net.ipv4.tcp_max_syn_backlog = 8192
net.core.netdev_max_backlog = 32768
net.core.somaxconn = 32768
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 2
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_max_orphans = 524288
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 300
net.ipv4.ip_local_port_range = 1024 65000
net.netfilter.nf_conntrack_max = 524280
net.netfilter.nf_conntrack_tcp_timeout_established = 180
vm.swappiness=0
vm.dirty_ratio=10
vm.dirty_background_ratio=5
#vm.overcommit_memory = 1
#kernel.core_pattern = /tmp/core.%e.%p.%s.%t
" >> /etc/sysctl.conf
sed -i "s/^net.ipv4.conf.eth[0-9].rp_filter/#&/" /etc/sysctl.conf
sed -i "s/^net.ipv4.conf.eth[0-9].arp_announce/#&/" /etc/sysctl.conf
sysctl -p
}
# 添加用户sshkey
add_userkey(){
#for((i=0;i<${#USERNAMES[@]};i++))
for i in $USER_NUMS
do
username=${USERNAMES[i]}
userkey=${USERKEYS[i]}
if [ -z "$username" ] || [ -z "$userkey" ];then
echo "Error: username or userkey is null !"
exit 7
fi

#if grep "$username" /home/${username}/.ssh/authorized_keys &> /dev/null; then
if ls /home/${username}/.ssh/authorized_keys &> /dev/null; then
echo "Waring: User $username key has already exists in the authorized_keys!"
continue
fi
# 添加普通用户key
useradd $username
mkdir -p /home/$username/.ssh && echo "$userkey" > /home/${username}/.ssh/authorized_keys && chown ${username}:${username} /home/${username}/.ssh -R && echo "Info: Add ${username} sshkey success!"
done
}
# 判断是否出错
check_flag(){
flag=$1
if [ "$flag" != "0" ] && [ "$flag" != "${INSTALLED}" ];then
echo "Error: flag:$flag"
exit $flag
fi
}
# 初始化安装软件
install_soft(){
# Example : install_soft lrzsz
yum install -y $*
check_flag $?
}
# 初始化安装服务
install_service(){
# Example : install_service nginx

service_path=''

if [ "$1" == "zabbix-agent" ];then
service_path="/etc/zabbix/zabbix_agentd.conf"
else
service_path="/usr/local/services/$1"
fi
#echo "Info: 检查$service_path是否存在!"
if ls $service_path &>/dev/null ;then
echo "Waring: The $1 $2 is already installed"
return ${INSTALLED}
else
rpm -qa|grep $1 || install_soft $1
fi
}

# 安装jdk
install_jdk(){
install_service jdk && \
echo "Info: JDK 安装完成,请测试!"
}

# 安装zabbix客户端
install_zabbix_agent(){
install_service zabbix-agent && \
if [ "$?" != "${INSTALLED}" ];then
yum update zabbix nc sysstat fping -y
# netstat添加s特殊权限
chmod ug+s /bin/netstat
chmod ug+s /usr/sbin/fping
chmod ug+s /usr/sbin/fping6
grep "zabbix ALL=NOPASSWD: /bin/netstat,/usr/sbin/iotop" /etc/sudoers || echo "zabbix ALL=NOPASSWD: /bin/netstat,/usr/sbin/iotop" >> /etc/sudoers

mkdir -p /usr/local/services
cd /etc/zabbix && \
rm -f zabbix_agentd.conf && \
wget_item 'zabbix/conf/zabbix_agentd.conf' && \
sed -i s/^Server=.*/Server=$ZABBIX_SERVER_IP/ /etc/zabbix/zabbix_agentd.conf && \
sed -i s/^ServerActive=.*/ServerActive=$ZABBIX_SERVER_IP/ /etc/zabbix/zabbix_agentd.conf
mkdir -p /data/logs/zabbix && \
chown -R zabbix:zabbix /data/logs/zabbix && \
mkdir -p /data/soft && \
cd /data/soft
if [ ! -f zabbix.tar.gz ];then
wget_item 'zabbix/scripts/zabbix.tar.gz'
fi

tar xf zabbix.tar.gz -C /usr/local/services &&
service zabbix-agent start && chkconfig zabbix-agent on
fi
}
# 安装fancy nginx
install_fancy_nginx(){
install_service nginx && \
if [ "$?" != ${INSTALLED} ];then
local_ips=`ifconfig| awk '/inet addr/{print $2}'|awk -F: '{print $2}'|awk 'BEGIN{RS=","}NF=NF'`
cd /usr/local/services/nginx/conf/vhosts && \
wget_item fancy/nginx/login/fancy-update.conf && \
sed -i "/server_name/s/^[[:space:]]*server_name.*/ server_name ${local_ips};/" /usr/local/services/nginx/conf/vhosts/fancy-update.conf && \
for port in $UPDATE_PORT $NGINX_PORT;do
iptables -A INPUT -p tcp -m tcp --dport $port -j ACCEPT
done && \
service iptables save && \
service nginx restart
fi
}
# 安装必备的软件
install_init(){
install_soft lrzsz telnet wget vim except ntpdate sysstat nc OpenIPMI ipmitool man mailx lsof lvm2 iotop openssh-clients fping
}
# 初始化同步时间
init_ntpdate(){
#运行时间
run_time="59 23 * * *"
#运行命令
command="/usr/sbin/ntpdate $NTPDATE_SERVER >> /var/log/time.log && hwclock --systohc 2>&1"
#完整运行命令
full_command="$run_time $command"
#添加同步时间计划任务
if ! crontab -l 2>/dev/null|grep -F "/usr/sbin/ntpdate" ;then
# 修改时区
\cp -f /usr/share/zoneinfo/Asia/Shanghai /etc/localtime &&\
# 同步时间
/usr/sbin/ntpdate $NTPDATE_SERVER && echo "Info :同步ntp时间成功!" &&(crontab -l 2>/dev/null;echo "$full_command")|crontab - && echo "Info: Add ntpdate task success!"
else
echo "Waring: The ntpdate task already exists!"
return $INSTALLED
fi
}
#初始化root密码(暂时未用)
init_root(){
password=`mkpasswd -s 0 -l 10` && echo "$password"|passwd --stdin root && echo "root密码:$password 请妥善保管" && echo "$password"|/bin/mail -s "`hostname` root password" $SYSTEM_ADMIN_EMAIL
}
#初始化用户
init_users(){
#del users
userdel adm
userdel lp
userdel sync
userdel shutdown
userdel halt
userdel news
userdel uucp
userdel operator
userdel games
userdel gopher
userdel ntp
userdel sabayon
userdel xfs
userdel ftp
del groupuser
groupdel adm
groupdel lp
groupdel news
groupdel uucp
groupdel games
groupdel dip
groupdel xfs

#添加需要访问的用户key
add_userkey
check_flag $?
# 开启sudo wheel用户组
modify_sudo
# 添加sudo wheel 用户
add_sudo_wheel_user
}
#单独安装zabbix-agent
zabbix_agent_init(){
# 更新yum源
wget_repo
# 初始化安装软件
install_init
# 安装zabbix客户端
install_zabbix_agent
}
# 系统初始化
system_init(){
# 创建必要的初始目录
#mkdir -p /data/app/ /data/soft /usr/local/services /data/logs/rsync
# 创建/etc/rc.local软链接
rm -f /etc/rc.local && ln -s /etc/rc.d/rc.local /etc/rc.local
# 初始化安装软件
install_init
check_flag $?
# 初始化用户
#init_users
# 修改hostname
update_hostname $1
#check_flag $?
# 更新yum源
wget_repo
check_flag $?
# 优化ulimit
modify_ulimit
check_flag $?
# 关闭不必要的服务
close_services
#check_flag $?
# 设置iptables防火墙
build_iptables
check_flag $?
# 安装zabbix客户端
#install_zabbix_agent
# 初始化同步时间
#init_ntpdate
#check_flag $?
# 优化内核参数
optimize_kernel
check_flag $?
echo "Info: System init is done !"
}
# 安装其它服务
choice=100
while(true);do
if [ $choice -eq 100 ];then
echo "请选择安装下列服务:"
echo " 1.系统初始化。"
echo " 2.安装zabbix客户端。"
# echo " 3.安装jdk。"
echo " 4.添加sysctl内核优化参数。"
echo " 5.修改hostname。"
echo " 6.添加sudo wheel用户。"
# echo " 7.初始化用户。"
# echo " 8.添加用户key。"
echo " *. 打印菜单。"
echo " 0.退出。"
fi
read -p "请输入选项:" choose
read -p "是否确认(y/n)?" yesno
if [ "$yesno" == "y" ];then
case $choose in
1) echo "Info: Start System init";system_init $1 ;;
2) echo "Info: Start install zabbix-agent"; zabbix_agent_init ;;
# 3)echo "Info: Start install jdk"; install_jdk ;;
4)echo "Info: Start optimize_kernel"; optimize_kernel ;;
5)echo "Info: Start update hostname"; update_hostname $1 ;;
6)echo "Info: Add sudo wheel user"; add_sudo_wheel_user $1;;
#7)echo "Info: init users"; init_users ;;
#8)echo "Info: add userkey"; add_userkey ;;
0) echo "Quit"; break ;;
*) choice=100 ;;
esac
fi
done
------ 本文结束 ------

版权声明

Medivh's Notes by Medivh is licensed under a Creative Commons BY-NC-ND 4.0 International License.
Medivh创作并维护的Medivh's Notes博客采用创作共用保留署名-非商业-禁止演绎4.0国际许可证
本文首发于Medivh 博客( http://www.mknight.cn ),版权所有,侵权必究。