编译安装Mysql

  • 这里是编译安装5.7.31
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
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2020-02-12
#FileName: install_mysql5.7_for_centos.sh
#URL: https://www.yanghongtao.cn
#Description: install mysql 5.7.31
#********************************************************************
#MySQL Download URL: https://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-5.7.29-linux-glibc2.12-x86_64.tar.gz

. /etc/init.d/functions
SRC_DIR=`pwd`
MYSQL='mysql-5.7.31-linux-glibc2.12-x86_64.tar.gz'
COLOR='echo -e \E[01;31m'
END='\E[0m'
MYSQL_ROOT_PASSWORD=magedu

check (){

if [ $UID -ne 0 ]; then
action "当前用户不是root,安装失败" false
exit 1
fi

cd $SRC_DIR
if [ ! -e $MYSQL ];then
$COLOR"缺少${MYSQL}文件"$END
$COLOR"请将相关软件放在${SRC_DIR}目录下"$END
exit
elif [ -e /usr/local/mysql ];then
action "数据库已存在,安装失败" false
exit
else
return
fi
}

install_mysql(){
$COLOR"开始安装MySQL数据库..."$END
yum -y -q install libaio numactl-libs libaio &> /dev/null
cd $SRC_DIR
tar xf $MYSQL -C /usr/local/
MYSQL_DIR=`echo $MYSQL' sed -nr 's/^(.*[0-9]).*/\1/p'`
ln -s /usr/local/$MYSQL_DIR /usr/local/mysql
chown -R root.root /usr/local/mysql/
id mysql &> /dev/null '' { useradd -s /sbin/nologin -r mysql ; action "创建mysql用户"; }

echo 'PATH=/usr/local/mysql/bin/:$PATH' > /etc/profile.d/mysql.sh
. /etc/profile.d/mysql.sh
ln -s /usr/local/mysql/bin/* /usr/bin/
cat > /etc/my.cnf <<-EOF
[mysqld]
server-id=1
log-bin
datadir=/data/mysql
socket=/data/mysql/mysql.sock
log-error=/data/mysql/mysql.log
pid-file=/data/mysql/mysql.pid
[client]
socket=/data/mysql/mysql.sock
EOF
mysqld --initialize --user=mysql --datadir=/data/mysql
cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
chkconfig --add mysqld
chkconfig mysqld on
service mysqld start
[ $? -ne 0 ] && { $COLOR"数据库启动失败,退出!"$END;exit; }
MYSQL_OLDPASSWORD=`awk '/A temporary password/{print $NF}' /data/mysql/mysql.log`
mysqladmin -uroot -p$MYSQL_OLDPASSWORD password $MYSQL_ROOT_PASSWORD &>/dev/null
action "数据库安装完成"
}

check

install_mysql

mysq一键备份

完全备份 分库备份 增量备份 多种功能

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
#!/bin/bash
# **********************************************************
# * Author : Mr.yang
# * Email : 1419946323@qq.com
# * URL: https://www.yanghongtao.cn
# * Create time : 2021-05-10 22:12
# * Filename : backup_mysql.sh
# * Description : backup_mysql
# **********************************************************
PATH=/app/cmatrix/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
. /etc/init.d/functions
TIME=`date +%F`
INCTIME=`date -d -1day`
NAME=`$HOSTNAME`
DIRDATA=/data/backup
DB=hellodb
PASSWD=

backup_mysqlDB(){
[ -d $DIRDATA ] '' mkdir $DIRDATA
mysqldump -uroot -p"$PASSWD" -F -A --single-transaction --master-data=1 ' gzip >$DIRDATA_Backup_$TIME.sql.zip
action "$DIRDATA_Backup_$TIME.sql.zip 备份成功"
}

backup_mysqlDB_Sub-library(){
[ -d $DIRDATA ] '' mkdir $DIRDATA
mysqldump -uroot -p"$PASSWD" -F -E -R --single-transaction --master-data=1 --default-character-set=uft8 -q -B $DB' gzip >$DIRDATA_Backup_$DB_$TIME.sql.zip
action "$DIRDATA_Backup_$DB_$TIME.sql.zip 备份成功"
}

#增量备份
backup_mysqlDB_Increment(){

rpm -qi wget ' yum install wget -y
package=Percona-XtraDB-Cluster-server-57-5.7.33-31.49.1.el7.x86_64.rpm
yum install -y $package
[ -d $DIRDATA ] ' mkdir $DIRDATA
complete(){
xtrabackup -uroot -p"$PASSWD" --backup --target-dir=$DIRDATA/$NAME_$TIME #完全备份
}
one_inc(){
xtrabackup -uroot -p"$PASSWD" --backup --target-dir=$DIRDATA/$NAME_Increment_$TIME --increment-basedir=$DIRDATA/$NAME_$INCTIME
}
two_inc(){
xtrabackup -uroot -p"$PASSWD" --backup --target-dir=DIRDATA/$NAME_Increment_$TIME --increment-basedir=$DIRDATA/$NAME_Increment_$INCTIME
}

}
PS3="请输入需要备份的菜单(1-5):"
select NEMU in 完全备份 分库备份 增量备份;do
case $REPLY in
1)
backup_mysqlDB
;;
2)

backup_mysqlDB_Sub-library
;;
3)
backup_mysqlDB_Increment
;;
4)
function_openvpn.remove
;;
*)
echo "Please enter the correct parameters (0-6) "
esac
done

mysql分库备份

选择指定的DB 数据库

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
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-06-22
#FileName: mysq_backup.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
TIME=`date +%F_%H-%M-%S`
DIR=/backup
DB=hellodb
PASS=magedu
[ -d $DIR ] '' mkdir $DIR
mysqldump -uroot -p "$PASS" -F -E -R --triggers --single-transaction --master-data=2 --default-character-set=utf8 -q -B $DB ' gzip > ${DIR}/${DB}_${TIME}.sql.gz

#生产中略有不同只供参考
chmod +x mysql_backup.sh
#生产建议添加计划任务脚本
crontable -e
* * * * * /root/mysql_backup.sh

#执行成功后我们可以解开查看是否可以还原,生产中可以拷贝到新的数据库测试
set sql_log_bin=0; #先关闭二进制日志
souce /backup/*
#后续在启用二进制日志
set sql_logbin=1;

编译安装redis

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
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2020-02-22
#FileName: install_redis_for_centos.sh
#URL: http://www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2020 All rights reserved
#********************************************************************
. /etc/init.d/functions
VERSION=redis-4.0.14
PASSWORD=123456
INSTALL_DIR=/apps/redis

install() {
yum -y install gcc jemalloc-devel '' { action "安装软件包失败,请检查网络配置" false ; exit; }

wget http://download.redis.io/releases/${VERSION}.tar.gz '' { action "Redis 源码下载失败" false ; exit; }

tar xf ${VERSION}.tar.gz
cd ${VERSION}
make -j 4 PREFIX=${INSTALL_DIR} install && action "Redis 编译安装完成" '' { action "Redis 编译安装失败" false ;exit ; }

ln -s ${INSTALL_DIR}/bin/redis-* /usr/bin/
mkdir -p ${INSTALL_DIR}/{etc,log,data,run}
cp redis.conf ${INSTALL_DIR}/etc/

sed -i -e 's/bind 127.0.0.1/bind 0.0.0.0/' -e "/# requirepass/a requirepass $PASSWORD" -e "/^dir .*/c dir ${INSTALL_DIR}/data/" -e "/logfile .*/c logfile ${INSTALL_DIR}/log/redis-6379.log" -e "/^pidfile .*/c pidfile ${INSTALL_DIR}/run/redis_6379.pid" ${INSTALL_DIR}/etc/redis.conf

if id redis &> /dev/null ;then
action "Redis 用户已存在" false
else
useradd -r -s /sbin/nologin redis
action "Redis 用户创建成功"
fi

chown -R redis.redis ${INSTALL_DIR}

cat >> /etc/sysctl.conf <<EOF
net.core.somaxconn = 1024
vm.overcommit_memory = 1
EOF
sysctl -p

echo 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' >> /etc/rc.d/rc.local
chmod +x /etc/rc.d/rc.local
/etc/rc.d/rc.local

cat > /usr/lib/systemd/system/redis.service <<EOF
[Unit]
Description=Redis persistent key-value database
After=network.target

[Service]
ExecStart=${INSTALL_DIR}/bin/redis-server ${INSTALL_DIR}/etc/redis.conf --supervised systemd
ExecStop=/bin/kill -s QUIT \$MAINPID
#Type=notify
User=redis
Group=redis
RuntimeDirectory=redis
RuntimeDirectoryMode=0755

[Install]
WantedBy=multi-user.target

EOF
systemctl daemon-reload
systemctl enable --now redis &> /dev/null && action "Redis 服务启动成功,Redis信息如下:" '' { action "Redis 启动失败" false ;exit; }

redis-cli -a $PASSWORD INFO Server 2> /dev/null

}

install

编译安装nginx

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
#!/bin/bash                                                                                                                                                                
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2020-12-01
#FileName: install_nginx.sh
#URL: http://www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
SRC_DIR=/usr/local/src
NGINX_URL=http://nginx.org/download/
NGINX_FILE=nginx-1.18.0
TAR=.tar.gz
NGINX_INSTALL_DIR=/apps/nginx
CPUS=`lscpu 'awk '/^CPU\(s\)/{print $2}'`

color () {
RES_COL=60
MOVE_TO_COL="echo -en \\033[${RES_COL}G"
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_WARNING="echo -en \\033[1;33m"
SETCOLOR_NORMAL="echo -en \E[0m"
echo -n "$1" && $MOVE_TO_COL
echo -n "["
if [ $2 = "success" -o $2 = "0" ] ;then
${SETCOLOR_SUCCESS}
echo -n $" OK "
elif [ $2 = "failure" -o $2 = "1" ] ;then
${SETCOLOR_FAILURE}
echo -n $"FAILED"
else
${SETCOLOR_WARNING}
echo -n $"WARNING"
fi
${SETCOLOR_NORMAL}
echo -n "]"
echo
}

os_type () {
awk -F'[ "]' '/^NAME/{print $2}' /etc/os-release
}

os_version () {
awk -F'"' '/^VERSION_ID/{print $2}' /etc/os-release
}

check () {
[ -e ${NGINX_INSTALL_DIR} ] && { color "nginx 已安装,请卸载后再安装" 1; exit; }
cd ${SRC_DIR}
if [ -e ${NGINX_FILE}${TAR} ];then
color "相关文件已准备好" 0
else
color '开始下载 nginx 源码包' 0
wget ${NGINX_URL}${NGINX_FILE}${TAR}
[ $? -ne 0 ] && { color "下载 ${NGINX_FILE}${TAR}文件失败" 1; exit; }
fi
}

install () {
color "开始安装 nginx" 0
if id nginx &> /dev/null;then
color "nginx 用户已存在" 1
else
useradd -s /sbin/nologin -r nginx
color "创建 nginx 用户" 0
fi
color "开始安装 nginx 依赖包" 0
if [ `os_type` == "CentOS" -a `os_version` == '8' ] ;then
yum -y -q install make gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed
elif [ `os_type` == "CentOS" -a `os_version` == '7' ];then
yum -y -q install make gcc pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed
else
apt update &> /dev/null
apt -y install make gcc libpcre3 libpcre3-dev openssl libssl-dev zlib1g-dev &> /dev/null
fi
cd $SRC_DIR
tar xf ${NGINX_FILE}${TAR}
NGINX_DIR=`echo ${NGINX_FILE}${TAR}' sed -nr 's/^(.*[0-9]).*/\1/p'`
cd ${NGINX_DIR}
./configure --prefix=${NGINX_INSTALL_DIR} --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
make -j $CPUS && make install
[ $? -eq 0 ] && color "nginx 编译安装成功" 0 '' { color "nginx 编译安装失败,退出!" 1 ;exit; }
echo "PATH=${NGINX_INSTALL_DIR}/sbin:${PATH}" > /etc/profile.d/nginx.sh
cat > /lib/systemd/system/nginx.service <<EOF
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=${NGINX_INSTALL_DIR}/logs/nginx.pid
ExecStartPre=/bin/rm -f ${NGINX_INSTALL_DIR}/logs/nginx.pid
ExecStartPre=${NGINX_INSTALL_DIR}/sbin/nginx -t
ExecStart=${NGINX_INSTALL_DIR}/sbin/nginx
ExecReload=/bin/kill -s HUP \$MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
ln -s /apps/nginx/sbin/nginx /usr/sbin/
systemctl daemon-reload
systemctl enable --now nginx &> /dev/null
systemctl is-active nginx &> /dev/null '' { color "nginx 启动失败,退出!" 1 ; exit; }
color "nginx 安装完成" 0
}

check
install

安装tomcat和JDK

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
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-03-15
#FileName: install_tomcat.sh
#URL: http://www.yhtzjy.com
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************

DIR=`pwd`
JDK_FILE="jdk-8u281-linux-x64.tar.gz"
TOMCAT_FILE="apache-tomcat-8.5.68.tar.gz"
JDK_DIR="/usr/local"
TOMCAT_DIR="/usr/local"

color () {
RES_COL=60
MOVE_TO_COL="echo -en \\033[${RES_COL}G"
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_WARNING="echo -en \\033[1;33m"
SETCOLOR_NORMAL="echo -en \E[0m"
echo -n "$2" && $MOVE_TO_COL
echo -n "["
if [ $1 = "success" -o $1 = "0" ] ;then
${SETCOLOR_SUCCESS}
echo -n $" OK "
elif [ $1 = "failure" -o $1 = "1" ] ;then
${SETCOLOR_FAILURE}
echo -n $"FAILED"
else
${SETCOLOR_WARNING}
echo -n $"WARNING"
fi
${SETCOLOR_NORMAL}
echo -n "]"
echo
}

install_jdk(){
if ! [ -f "$DIR/$JDK_FILE" ];then
color 1 "$JDK_FILE 文件不存在"
exit;
elif [ -d $JDK_DIR/jdk ];then
color 1 "JDK 已经安装"
exit
else
[ -d "$JDK_DIR" ] '' mkdir -pv $JDK_DIR
fi
tar xvf $DIR/$JDK_FILE -C $JDK_DIR
cd $JDK_DIR && ln -s jdk1.8.* jdk

cat > /etc/profile.d/jdk.sh <<EOF
export JAVA_HOME=$JDK_DIR/jdk
export JRE_HOME=\$JAVA_HOME/jre
export CLASSPATH=\$JAVA_HOME/lib/:\$JRE_HOME/lib/
export PATH=\$PATH:\$JAVA_HOME/bin
EOF
. /etc/profile.d/jdk.sh
java -version && color 0 "JDK 安装完成" '' { color 1 "JDK 安装失败" ; exit; }

}

install_tomcat(){
if ! [ -f "$DIR/$TOMCAT_FILE" ];then
color 1 "$TOMCAT_FILE 文件不存在"
exit;
elif [ -d $TOMCAT_DIR/tomcat ];then
color 1 "TOMCAT 已经安装"
exit
else
[ -d "$TOMCAT_DIR" ] '' mkdir -pv $TOMCAT_DIR
fi
tar xf $DIR/$TOMCAT_FILE -C $TOMCAT_DIR
cd $TOMCAT_DIR && ln -s apache-tomcat-*/ tomcat
echo "PATH=$TOMCAT_DIR/tomcat/bin:"'$PATH' > /etc/profile.d/tomcat.sh
id tomcat &> /dev/null '' useradd -r -s /sbin/nologin tomcat

cat > $TOMCAT_DIR/tomcat/conf/tomcat.conf <<EOF
JAVA_HOME=$JDK_DIR/jdk
EOF

chown -R tomcat.tomcat $TOMCAT_DIR/tomcat/

cat > /lib/systemd/system/tomcat.service <<EOF
[Unit]
Description=Tomcat
#After=syslog.target network.target remote-fs.target nss-lookup.target
After=syslog.target network.target

[Service]
Type=forking
EnvironmentFile=$TOMCAT_DIR/tomcat/conf/tomcat.conf
ExecStart=$TOMCAT_DIR/tomcat/bin/startup.sh
ExecStop=$TOMCAT_DIR/tomcat/bin/shutdown.sh
RestartSec=3
PrivateTmp=true
User=tomcat
Group=tomcat

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now tomcat.service &> /dev/null
systemctl is-active tomcat.service &> /dev/null && color 0 "TOMCAT 安装完成" '' { color 1 "TOMCAT 安装失败" ; exit; }

}

install_jdk

install_tomcat

一键搭建LNMP

  • 未避免网络相关问题,此脚本基于离线安装
  • 脚本只对nginx、php-fpm做了基础优化,还请根据自己的需求修改相关配置文件
  • 重新登陆后可以使用nginx,mysql,php-fpm等命令
  • 关于https,nginx配置文件中已经做了全站https的代码,只是被注释了,请根据自己的域名、证书修改以下配置文件:
  • /apps/nginx/conf/nginx.conf

系统环境要求:

  1. 没有安装过nginx、mysql、php软件以及apache、mariadb
  2. 没有相关软件生成的文件残留
  3. 未创建nginx,mysql用户

建议

脚本跑完后,第一次使用域名访问以完成wordpress安装,域名会被记录到数据库中,以后如果更换域名,只要重新做域名解析即可。若第一次使用IP访问,浏览器地址会显示IP地址而不是域名,更换域名及IP都需要手动对数据库修改,因此不建议使用IP访问安装wordpress。

下载源码包
nginx –1.18.0
mysql–5.7.34
php–7.4.21
openssl–1.1.1k
wordpress–5.7.2

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
#!/bin/bash
SRC_DIR='/usr/local/src/'
NGINX='nginx-1.18.0.tar.gz'
MYSQL='mysql-5.7.34-linux-glibc2.12-x86_64.tar.gz'
PHP='php-7.4.21.tar.xz'
APP='wordpress-5.7.2-zh_CN.tar.gz'
OPENSSL='openssl-1.1.1k.tar.gz'
COLOR="echo -e \\033[01;31m"
END='\033[0m'
MYSQL_ROOT_PASSWORD=RedHat@123
MYSQL_WORDPRESS_PASSWORD=wordpress
CPU=`lscpu' awk '/^CPU\(s\):/{print $NF}'`

${COLOR}'开始安装基于LNMP的wordpress'$END
sleep 1

check_file(){
yum repolist ' grep -i epel &> /dev/null;
[ $? -ne 0 ] && { ${COLOR}'需要开启epel源'$END;exit; }
$COLOR"请将相关文件放在${SRC_DIR}目录下"$END
cd $SRC_DIR
if [ ! -e $NGINX ];then
$COLOR"缺少${NGINX}文件"$END
exit
elif [ ! -e $MYSQL ];then
$COLOR"缺少${MYSQL}文件"$END
exit
elif [ ! -e $PHP ];then
$COLOR"缺少${PHP}文件"$END
exit
elif [ ! -e $APP ];then
$COLOR"缺少${APP}文件"$END
exit
elif [ ! -e $OPENSSL ];then
$COLOR"缺少${OPENSSL}文件"$END
exit
else
$COLOR"相关文件已准备好"$END
fi
}
install_mysql(){
$COLOR"开始安装MySQL数据库"$END
tar xf $MYSQL -C $SRC_DIR
if [ -e /usr/local/mysql ];then
$COLOR"数据库已存在,安装失败"$END
exit
fi
local MYSQL_DIR=`echo $MYSQL' sed -nr 's/^(.*[0-9]).*/\1/p'`
ln -s ${SRC_DIR}${MYSQL_DIR} /usr/local/mysql
id mysql &> /dev/null '' { groupadd -g 306 mysql;useradd -u 306 -s /sbin/nologin -g mysql -r mysql;$COLOR"创建mysql用户"$END; }
yum -y -q install numactl-libs ncurses-compat-libs libaio &> /dev/null
echo 'PATH=/usr/local/mysql/bin/:$PATH' > /etc/profile.d/mysql.sh
source /etc/profile.d/mysql.sh
mkdir /etc/my.cnf.d
cat > /etc/my.cnf <<EOF
[mysqld]
server-id=1
basedir=/usr
datadir=/data/mysql
socket=/data/mysql/mysql.sock
log-error=/data/mysql/mysql.log
pid-file=/data/mysql/mysql.pid
character-set-server=utf8mb4
log-bin

[mysql]
default-character-set=utf8mb4

[client]
socket=/data/mysql/mysql.sock

!includedir /etc/my.cnf.d
EOF
cat > /usr/lib/systemd/system/mysqld.service <<EOF
[Unit]
Description=MySQL Server
Documentation=man:mysqld(8)
After=network.target
After=syslog.target

[Install]
WantedBy=multi-user.target

[Service]
User=mysql
Group=mysql
Type=forking
TimeoutSec=0
PermissionsStartOnly=true
ExecStart=/usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --daemonize
LimitNOFILE = 65536
Restart=on-failure
RestartPreventExitStatus=1
PrivateTmp=true
EOF
[ -d /data/ ] '' mkdir /data
/usr/local/mysql/bin/mysqld --initialize-insecure --user=mysql --datadir=/data/mysql
systemctl daemon-reload && systemctl enable --now mysqld
[ $? -ne 0 ] && { $COLOR"数据库启动失败,退出!"$END;exit; }
mysqladmin -uroot password $MYSQL_ROOT_PASSWORD &>/dev/null
$COLOR"数据库安装完成"$END
}

install_nginx(){
${COLOR}"开始安装NGINX"$END
cd $SRC_DIR
id nginx &> /dev/null '' { groupadd -g 80 nginx;useradd -u 80 -s /sbin/nologin -g 80 -r nginx;$COLOR"创建nginx用户"$END; }
$COLOR"安装nginx相关包"$END
yum -q -y install gcc gcc-c++ pcre pcre-devel pcre pcre-devel zlib zlib-devel automake make &> /dev/null

tar xf $NGINX -C $SRC_DIR
NGINX_DIR=`echo $NGINX' sed -nr 's/^(.*[0-9]).*/\1/p'`
tar xf $OPENSSL -C $SRC_DIR
OPENSSL_DIR=`echo $OPENSSL ' sed -nr 's/^(.*).tar.gz/\1/p'`
cd $NGINX_DIR
./configure --prefix=/apps/nginx \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-pcre \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module \
--with-file-aio \
--with-threads \
--with-openssl=${SRC_DIR}${OPENSSL_DIR}
make -j $CPU && make install
[ $? -eq 0 ] && $COLOR"NGINX编译安装成功"$END '' { $COLOR"NGINX编译安装失败,退出!"$END;exit; }
[ -d /data/nginx ] '' mkdir -pv /data/nginx/
cat > /apps/nginx/conf/nginx.conf <<EOF
user nginx nginx;

#工作进程数量,与cpu核心一致
worker_processes auto;
#CPU亲缘性绑定
worker_cpu_affinity auto;

error_log /apps/nginx/logs/error.log error;

pid logs/nginx.pid;

worker_priority 0;
#打开的最大文件数,应与`ulimit -n`一致
worker_rlimit_nofile 65536;

#线程池
thread_pool pool1 threads=32 max_queue=65536;

events {
#单个工作进程的最大并发连接数
worker_connections 65536;

#使用epoll事件驱动
use epoll;

#同一时刻一个请求轮流由work进程处理,避免"惊群"
accept_mutex on;

#工作进程开启同时接受多个新的网络连接
multi_accept on;
}

http {
include mime.types;
default_type application/octet-stream;

#自定义json日志格式
log_format access_json '{"@timestamp":"\$time_iso8601",'
'"host":"\$server_addr",'
'"clientip":"\$remote_addr",'
'"size":\$body_bytes_sent,'
'"responsetime":\$request_time,'
'"upstreamtime":"\$upstream_response_time",'
'"upstreamhost":"\$upstream_addr",'
'"http_host":"\$host",'
'"uri":"\$uri",'
'"domain":"\$host",'
'"xff":"\$http_x_forwarded_for",'
'"referer":"\$http_referer",'
'"tcp_xff":"\$proxy_protocol_addr",'
'"http_user_agent":"\$http_user_agent",'
'"status":"\$status"}';

#零拷贝,加快静态文件传输
sendfile on;
#合并请求后统一发送给客户端,需开启sendfile
tcp_nopush on;

#异步IO
aio threads=pool1;
directio 4m;
directio_alignment 512;

#开启与客户端长连接
keepalive_timeout 65;
keepalive_requests 500;
#立即发送相应报文
tcp_nodelay on;
#开启与后端fastcgi服务器长连接
fastcgi_keep_conn on;

#开启压缩
gzip on;
gzip_comp_level 9;
gzip_min_length 1k;
gzip_types text/plain application/javascript application/x-javascript
text/cssapplication/xml text/javascript application/x-httpd-php image/jpeg
image/gif image/png;
gzip_vary on;

#响应报文隐藏后端服务器
fastcgi_hide_header X-Powered-By;
#响应报文隐藏nginx版本
server_tokens off;

server {
server_name www.75j.xyz;
listen 80;
root /data/nginx/wordpress;
index index.php;
charset utf-8;
access_log /apps/nginx/logs/access_json.log access_json;
client_max_body_size 20m;

##ssl证书相关
#listen 443 ssl;
#ssl_certificate /apps/nginx/www.75j.xyz.pem;
#ssl_certificate_key /apps/nginx/www.75j.xyz.key;
#ssl_session_cache shared:SSL:10m;
#ssl_session_timeout 5m;

##HSTS 浏览器自己改写http请求为https,而不是先发送http,然后重定向到https
#add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";
##非http请求重写为https请求
#if (\$scheme = http){
# rewrite ^/(.*)$ https://www.75j.xyz/\$1 permanent;
#}

##防盗链
#valid_referers none blocked server_names
# *.75j.xyz www.75j.xyz\/*
# ~\.baidu\.;
#if (\$invalid_referer) {
# return 403;
#}

#仅允许GET
location / {
limit_except GET {
deny all;
}
}

#动静分离
location ~ .*\.(gif'jpg'jpeg'png'bmp'swf'js'css'tiff'tif'wmf'ico)$ {
#root /data/static
expires 365d;
}

#与php服务器使用fastcgi连接
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_send_timeout 30;
fastcgi_read_timeout 30;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
include fastcgi_params;
}

location = /favicon.ico {
root /data/nginx/wordpress;
}

#禁止访问密码等敏感数据文件
location ~ ^/(\.user.ini'\.htaccess'\.git'\.svn'\.project'LICENSE'README.md) {
return 404;
}

#nginx状态页
location /nginx_status {
access_log off;
allow 127.0.0.1;
stub_status;
}

#php状态页
location ~ ^/(pm_status'ping)$ {
access_log off;
allow 127.0.0.1;
deny all;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param PATH_TRANSLATED \$document_root\$fastcgi_script_name;
include fastcgi_params;
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
EOF
echo 'PATH=/apps/nginx/sbin:$PATH' >> /etc/profile.d/nginx.sh
cat > /usr/lib/systemd/system/nginx.service <<EOF
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/apps/nginx/logs/nginx.pid
ExecStartPre=/usr/bin/rm -f /apps/nginx/logs/nginx.pid
ExecStartPre=/apps/nginx/sbin/nginx -t
ExecStart=/apps/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=mixed
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now nginx
systemctl is-active nginx &> /dev/null '' { $COLOR"NGINX 启动失败,退出!"$END ; exit; }
$COLOR"NGINX安装完成"
}

install_php(){
${COLOR}"开始安装PHP"$END
yum -y install gcc openssl-devel libxml2-devel bzip2-devel libmcrypt-devel sqlite-devel oniguruma-devel autoconf libpng-devel libjpeg-devel
cd $SRC_DIR
tar xf $PHP
PHP_DIR=`echo $PHP' sed -nr 's/^(.*[0-9]).*/\1/p'`
cd $PHP_DIR
./configure \
--prefix=/apps/php \
--with-fpm-user=nginx \
--with-fpm-group=nginx \
--enable-mysqlnd \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
--with-openssl \
--with-zlib \
--enable-mbstring \
--enable-xml \
--enable-sockets \
--enable-fpm \
--enable-maintainer-zts \
--with-jpeg \
--disable-fileinfo \
--enable-opcache \
--enable-gd \
--with-config-file-path=/apps/php/etc
make -j $CPU && make install
[ $? -eq 0 ] && $COLOR"PHP编译安装成功"$END '' { $COLOR"PHP编译安装失败,退出!"$END;exit; }
cat > /apps/php/etc/php-fpm.d/www.conf<<EOF
[www]
user = nginx
group = nginx
listen = 127.0.0.1:9000
listen.allowed_clients = 127.0.0.1
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 1
pm.max_spare_servers = 20
pm.max_requests = 1000
pm.status_path = /pm_status
ping.path = /ping
ping.response = pong
EOF
cp php.ini-production /apps/php/etc/php.ini
sed -i -r 's/(upload_max_filesize =).*/\1 20M/' /apps/php/etc/php.ini
sed -i -r 's/^(expose_php =) On/\1 Off/' /apps/php/etc/php.ini
echo -e 'opcache.enable=1\nzend_extension=opcache.so' >> /apps/php/etc/php.ini
echo 'PATH=/apps/php/bin/:/apps/php/sbin/:$PATH' > /etc/profile.d/php-fpm.sh
cp sapi/fpm/php-fpm.service /usr/lib/systemd/system/
cp /apps/php/etc/php-fpm.conf.default /apps/php/etc/php-fpm.conf
systemctl daemon-reload
systemctl start php-fpm
systemctl is-active php-fpm &> /dev/null '' { $COLOR"PHP-FPM 启动失败,退出!"$END ; exit; }
$COLOR"PHP安装完成"
}

install_wordpress(){
cd $SRC_DIR
tar xf $APP -C /data/nginx
chown -R nginx.nginx /data/nginx
cd /data/nginx/wordpress
cp wp-config-sample.php wp-config.php

mysql -uroot -p"$MYSQL_ROOT_PASSWORD" \
-e "create database wordpress;\
create user wordpress@'127.0.0.1' identified by '$MYSQL_WORDPRESS_PASSWORD';\
grant all on wordpress.* to wordpress@'127.0.0.1';" &>/dev/null

sed -i -e 's/database_name_here/wordpress/' \
-e 's/username_here/wordpress/' \
-e "s/password_here/$MYSQL_WORDPRESS_PASSWORD/" \
-e 's/localhost/127.0.0.1/' wp-config.php
$COLOR"WORDPRESS安装完成"
}

check_file

install_mysql

install_nginx

install_php

install_wordpress

PXE_centos一键安装

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
vim install_PXE.sh
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-07-12
#FileName: auto_install_centos678_PXE.sh
#URL: www.yhtzjy.com
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************

ReleaseNo=`cat /etc/redhat-release 'sed -rn 's/.* ([[:digit:]]+)\..*/\1/p'`
PXEinstall(){
setenforce 0
systemctl stop firewalld
rpm -q net-tools ''yum -y install net-tools &> /dev/null
ifconfig 'grep eth0
if [ "$?" -ne "0" ];then
echo "请将网卡更名为eth0;才能继续运行本脚本;更改过程中会强制重启;您是否还要继续执行?"
read -p " 请按y继续运行: " ipsure
[ "${ipsure}" == "y" ] && sed -ir '/GRUB_CMDLINE_LINUX=/s/"$/ net.ifnames=0"/p' /etc/default/grub && grub2-mkconfig -o /etc/grub2.cfg &>/dev/null
read -p "请输入eth0的IP: " ip
read -p "请输入要设置的子网掩码(prefix)如 24: " prefix
read -p "请输入要设置的网关: " gateway
cat >/etc/sysconfig/network-scripts/ifcfg-eth0 <<EOF
DEVICE="eth0"
BOOTPROTO="static"
ONBOOT="yes"
TYPE="Ethernet"
IPADDR=$ip
PREFIX=$prefix
GATEWAY=$gateway
DNS1=114.114.114.114
EOF
echo "请重启系统;然后重新执行本脚本"
echo "重启后如果无法联网 请执行service network restart 或者 nmcli con reload; nmcli con up eth0"
reboot
fi
ipeth0=`ifconfig eth0'sed -rn '/inet\>/s/[^0-9]+([0-9.]+).*/\1/p'`
neteth0=`ifconfig eth0'sed -rn '/inet\>/s/[^0-9]+([0-9.]+).*/\1/p''cut -d. -f1-3`
route=`ip route'grep default'grep eth0'sed -rn 's/[^0-9]+([0-9.]+).*/\1/p'`
route6=`ip route'grep default'sed -rn 's/[^0-9]+([0-9.]+).*/\1/p'`
srinfo6=`lsblk'awk '/sr/{print $1}'`
srinfo=`lsblk'egrep -o 'sr[^ ]*'`
for scan in /sys/class/scsi_host/host*/scan;do echo "- - -" >$scan;done
if [ "$ReleaseNo" -eq "8" ];then
rpm -q dhcp-server tftp-server httpd syslinux-nonlinux'' dnf -y install dhcp-server tftp-server httpd syslinux-nonlinux
cat >/etc/dhcp/dhcpd.conf <<-EOF
option domain-name "example.org";
option domain-name-servers 180.76.76.76,114.114.114.114;
default-lease-time 600;
max-lease-time 7200;
log-facility local7;
subnet ${neteth0}.0 netmask 255.255.255.0 {
range ${neteth0}.100 ${neteth0}.200;
option routers ${route};
next-server ${ipeth0};
filename "pxelinux.0";
}
EOF
systemctl enable --now httpd tftp dhcpd
fi
if [ "$ReleaseNo" -eq "7" ];then
rpm -q httpd tftp-server dhcp syslinux''yum -y install httpd tftp-server dhcp syslinux
cat >/etc/dhcp/dhcpd.conf <<-EOF
option domain-name "example.org";
option domain-name-servers 180.76.76.76,114.114.114.114;
default-lease-time 600;
max-lease-time 7200;
log-facility local7;
subnet ${neteth0}.0 netmask 255.255.255.0 {
range ${neteth0}.100 ${neteth0}.200;
option routers ${route};
next-server ${ipeth0};
filename "pxelinux.0";
}
EOF
systemctl enable --now httpd tftp dhcpd
fi
if [ "$ReleaseNo" -eq "6" ];then
rpm -q httpd tftp-server dhcp syslinux''yum -y install httpd tftp-server dhcp syslinux
service httpd start
sed -i '/disable/s/yes/no/' /etc/xinetd.d/tftp
service xinetd restart
cat >/etc/dhcp/dhcpd.conf <<EOF
option domain-name "example.org";
option domain-name-servers 180.76.76.76,114.114.114.114;
default-lease-time 600;
max-lease-time 7200;
log-facility local7;
subnet ${neteth0}.0 netmask 255.255.255.0 {
range ${neteth0}.100 ${neteth0}.200;
option routers ${route6};
next-server ${ipeth0};
filename "pxelinux.0";
}
EOF
service dhcpd start
fi
mkdir /var/www/html/centos/{6,7,8}/isos/x86_64/ -pv &>/dev/null
if [ "$ReleaseNo" -eq "7" -o "$ReleaseNo" -eq "8" ];then
srinfo6=${srinfo}
fi
for sr in ${srinfo6};do
mkdir /mnt/${sr} -p &>/dev/null
mount /dev/${sr} /mnt/${sr}
if [ -d /mnt/${sr}/AppStream ];then
mount /dev/${sr} /var/www/html/centos/8/isos/x86_64/ &>/dev/null
mkdir /var/www/html/ksdir -p &>/dev/null
mkdir /var/lib/tftpboot/8 -p &> /dev/null
\cp -a /mnt/${sr}/isolinux/{vmlinuz,initrd.img} /var/lib/tftpboot/8/
\cp /mnt/${sr}/isolinux/{ldlinux.c32,libcom32.c32,libutil.c32} /var/lib/tftpboot/
cat >/var/www/html/ksdir/ks8.cfg <<-EOF
#version=RHEL8
ignoredisk --only-use=sda
zerombr
text
reboot
# Partition clearing information
clearpart --all --initlabel
selinux --disabled
firewall --disabled

# Use graphical install
url --url=http://${ipeth0}/centos/8/isos/x86_64/
#repo --name="AppStream" --baseurl=file:///run/install/repo/AppStream
# Use CDROM installation media
#cdrom
# Keyboard layouts
keyboard --vckeymap=us --xlayouts='us'
# System language
lang en_US.UTF-8

# Network information
network --bootproto=dhcp --device=ens160 --onboot=yes --ipv6=auto --no-activate
network --hostname=localhost.localdomain
# Root password
rootpw --iscrypted \$1\$jb2QI2x8\$wWAOeOxXerdfYXyVwV0890
# Run the Setup Agent on first boot
firstboot --enable
# Do not configure the X Window System
skipx
# System services
#services --disabled="chronyd"
# System timezone
timezone Asia/Shanghai --isUtc --nontp
# Disk partitioning information
part / --fstype="xfs" --ondisk=sda --size=102400
part /data --fstype="xfs" --ondisk=sda --size=51200
part swap --fstype="swap" --ondisk=sda --size=2048
part /boot --fstype="ext4" --ondisk=sda --size=1024
%addon com_redhat_kdump --disable --reserve-mb='auto'
%end

%packages
@^minimal-environment
kexec-tools
%end

%anaconda
pwpolicy root --minlen=6 --minquality=1 --notstrict --nochanges --notempty
pwpolicy user --minlen=6 --minquality=1 --notstrict --nochanges --emptyok
pwpolicy luks --minlen=6 --minquality=1 --notstrict --nochanges --notempty
%end
EOF
fi
if [ -e /mnt/${sr}/RPM-GPG-KEY-CentOS-6 ];then
mount /dev/${sr} /var/www/html/centos/6/isos/x86_64/ &>/dev/null
mkdir /var/www/html/ksdir -p &>/dev/null
mkdir /var/lib/tftpboot/6 -p &>/dev/null
\cp -a /mnt/${sr}/isolinux/{vmlinuz,initrd.img} /var/lib/tftpboot/6/ &>/dev/null
cat >/var/www/html/ksdir/ks6.cfg <<EOF
#ckstart file automatically generated by anaconda.
#version=DEVEL
install
url --url=http://${ipeth0}/centos/6/isos/x86_64/
lang en_US.UTF-8
keyboard us
network --onboot yes --device eth0 --bootproto dhcp --noipv6
rootpw --iscrypted \$1\$jb2QI2x8\$wWAOeOxXerdfYXyVwV0890
firewall --disabled
authconfig --enableshadow --passalgo=sha512
selinux --disabled
timezone Asia/Shanghai
bootloader --location=mbr --driveorder=sda --append="crashkernel=auto rhgb quiet"
# The following is the partition information you requested
# Note that any partitions you deleted are not expressed
# here so unless you clea:r all partitions first, this is
# not guaranteed to work
clearpart --all
zerombr
reboot
text
part /boot --fstype=ext4 --size=1024
part / --fstype=ext4 --size=100000
part /data --fstype=ext4 --size=50000
part swap --size=2048

%packages
@core
autofs
%end
EOF
fi
if [ -e /mnt/${sr}/RPM-GPG-KEY-CentOS-7 ];then
mount /dev/${sr} /var/www/html/centos/7/isos/x86_64/ &>/dev/null
mkdir /var/www/html/ksdir -p &>/dev/null
mkdir /var/lib/tftpboot/7 -p &>/dev/null
\cp -a /mnt/${sr}/isolinux/{vmlinuz,initrd.img} /var/lib/tftpboot/7/
cat >/var/www/html/ksdir/ks7.cfg <<EOF
#platform=x86, AMD64, or Intel EM64T
#version=DEVEL
# Install OS instead of upgrade
install
# X Window System configuration information
xconfig --startxonboot
# Keyboard layouts
# old format: keyboard us
# new format:
keyboard --vckeymap=us --xlayouts='us'
# Root password
rootpw --iscrypted \$1\$jb2QI2x8\$wWAOeOxXerdfYXyVwV0890
# Use network installation
url --url="http://${ipeth0}/centos/7/isos/x86_64"
# System language
lang en_US
# System authorization information
auth --useshadow --passalgo=sha512
# Use text mode install
text
# Run the Setup Agent on first boot
firstboot --enable
# SELinux configuration
selinux --disabled
# Do not configure the X Window System
skipx

# System services
#services --disabled="chronyd"
ignoredisk --only-use=sda
# Firewall configuration
firewall --disabled
# Network information
network --bootproto=dhcp --device=ens33
# Reboot after installation
reboot
# System timezone
timezone Asia/Shanghai --nontp
# System bootloader configuration
bootloader --append="crashkernel=auto" --location=mbr --boot-drive=sda
# Clear the Master Boot Record
zerombr
# Partition clearing information
clearpart --all --initlabel
# Disk partitioning information
part swap --fstype="swap" --ondisk=sda --size=2048
part / --fstype="xfs" --ondisk=sda --size=100000
part /boot --fstype="xfs" --ondisk=sda --size=1024
part /data --fstype="xfs" --ondisk=sda --size=50000

%packages
@core
%end

EOF
fi
done
\cp /usr/share/syslinux/{pxelinux.0,menu.c32} /var/lib/tftpboot/
mkdir /var/lib/tftpboot/pxelinux.cfg/ -p
cat >/var/lib/tftpboot/pxelinux.cfg/default <<EOF
default menu.c32
timeout 600

menu title CentOS Linux

label linux8
menu label Auto Install CentOS Linux ^8.0 Mini
kernel 8/vmlinuz
append initrd=8/initrd.img ks=http://${ipeth0}/ksdir/ks8.cfg

label linux7
menu label Auto Install CentOS Linux ^7 Mini
kernel 7/vmlinuz
append initrd=7/initrd.img ks=http://${ipeth0}/ksdir/ks7.cfg

label linux6
menu label Auto Install CentOS Linux ^6 Mini
kernel 6/vmlinuz
append initrd=6/initrd.img ks=http://${ipeth0}/ksdir/ks6.cfg

label local
menu default
menu label Boot from ^local drive
localboot 0xffff
EOF
}

echo "**********************************************************************************************"
echo "***********************************请确保在nat网卡模式下运行***********************************"
echo "**********************************************************************************************"
echo "1..这是一个pxe 自动化安装的脚本;兼容centos6、7、8系统,需要将网卡同一设置为eth0;会自动更改网卡eth0"
echo "2..需要你至少挂载一个光盘;支持cenos6、7、8的光盘"
echo "3..新建虚拟机建议20G 2G内存以上 不然容易报错;"
echo "4..如果运行中有错误请与我联系!谢谢"
echo "5..如果网卡更改后重启了,务必确认是否能ping百度或查看是否有默认网关"
echo "6..如果执行本脚本后发现没有挂载光盘,请执行 yum remove dhcp'dhcp-server httpd tftp-server 清理环境"
echo "7..运行脚本需要在当前shell运行,不要开启子shell,否则无法使用自动更改网卡名功能"
echo "**************************************************************************************"
echo "**************************************************************************************"
echo "虚拟机默认密码为123"
j=5
for i in `seq 5`;do
echo "${j}s后自动开始运行"
let j--
sleep 1
done
PXEinstall

基于key验证通用脚本

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
#
#********************************************************************
#Author: Mr.yang
#QQ: 29308620
#Date: 2020-11-15
#FileName: ssh_keygen.sh
#URL: http://www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2020 All rights reserved
#********************************************************************
PASS=123456
#设置网段最后的地址,4-255之间,越小扫描越快
END=254

IP=`ip a s eth0 ' awk -F'[ /]+' 'NR==3{print $3}'`
NET=${IP%.*}.

rm -f /root/.ssh/id_rsa
[ -e ./SCANIP.log ] && rm -f SCANIP.log
for((i=3;i<="$END";i++));do
ping -c 1 -w 1 ${NET}$i &> /dev/null && echo "${NET}$i" >> SCANIP.log &
done
wait

ssh-keygen -P "" -f /root/.ssh/id_rsa
rpm -q sshpass '' yum -y install sshpass
sshpass -p $PASS ssh-copy-id -o StrictHostKeyChecking=no $IP

AliveIP=(`cat SCANIP.log`)
for n in ${AliveIP[*]};do
sshpass -p $PASS scp -o StrictHostKeyChecking=no -r /root/.ssh root@${n}:
done

#把.ssh/known_hosts拷贝到所有主机,使它们第一次互相访问时不需要输入回车
for n in ${AliveIP[*]};do
scp /root/.ssh/known_hosts ${n}:.ssh/
done

Centos 最小化安装命令

1
2
3
4
yum install  vim iotop bc gcc gcc-c++ glibc glibc-devel pcre \
pcre-devel openssl openssl-devel zip unzip zlib-devel net-tools \
lrzsz tree ntpdate telnet lsof tcpdump wget libevent libevent-devel \
bc systemd-devel bash-completion traceroute -y

Ubuntu 最小化安装命令

1
2
3
sudo apt-get install build-essential cmake pkg-config qt4- qmake libqt4-dev desktop-file-utils \
libavformat-dev libavcodec-dev libavutil-dev libswscale- dev libasound2-dev libpulse-dev libjack-jackd2-dev \
libgl1-mesa-dev libglu1-mesa-dev libx11-dev libxfixes-dev libxext-dev libxi-dev libxinerama-dev selinux-utils -y

创建单个用户

1
2
3
4
5
#!/bin/bash
[ $# -eq 0 ] && { echo "usage:createuser.sh USERNAME ..." ; exit 1 ; }
for user ;do
id $user &> /dev/null && echo $user is exist '' { useradd $user ; echo $user is created; }
done

批量创建用户

批量设置账号并设置随机密码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-06-27
#FileName: userfor.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
for i in {1..10};do
useradd user$i
PASS=`cat /dev/urandom ' tr -dc '[:alnum:]' 'head -c 12`
echo $PASS ' passwd --stdin user$i & > /dev/null
echo user$i:$PASS >> /data/user.log
echo "user$i is create"
done

创建用户-1

通过位置变量创建 Linux 系统账户及密码

#!/bin/bash
#
#********************************************************************
#Author:            Mr.yang                                                                                                                                             
#QQ:                1419946323
#Date:              2021-07-08
#FileName:         user.sh
#URL:               www.yanghongtao.cn
#Description:      The test script
#Copyright (C):     2021 All rights reserved
#********************************************************************
useradd "$1"
echo "$1" 'passwd --stdin "$2"

创建用户-2

编写脚本:提示用户输入用户名和密码,脚本自动创建相应的账户及配置密码。如果用户不输入账户名,则提示必须输入账户名并退出脚本;如果用户不输入密码,则统一使用默认的 123456 作为默认密码。

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
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-07-10
#FileName: user.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
read -p "请输入用户名: " user
#使用‐z 可以判断一个变量是否为空,如果为空,提示用户必须输入账户名,并退出脚本,退出码为 2
#没有输入用户名脚本退出后,使用$?查看的返回码为 2
if [ -z $user ];then
echo "您不需输入账户名"
exit 2
fi
#使用 stty ‐echo 关闭 shell 的回显功能
#使用 stty echo 打开 shell 的回显功能
stty -echo
read -p "请输入密码:" pass
stty echo
pass=${pass:-123456}
useradd "$user"
echo "$pass" 'passwd --stdin "$user"

统计可登录用户

统计当前 Linux 系统中可以登录计算机的账户有多少个

#!/bin/bash
#
#********************************************************************
#Author:            Mr.yang
#QQ:                1419946323
#Date:              2021-07-11
#FileName:         user.sh
#URL:               www.yanghongtao.cn
#Description:      The test script
#Copyright (C):     2021 All rights reserved
#********************************************************************
#方法 1:
grep "bash$" /etc/passwd 'wc -l

批量创建目录 *

问题: 将目录YYYY-MM-DD/中所有文件,移动到YYYY-MM/DD/下

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
#先创建YYYY-MM-DD格式的目录,当前日期一年前365天到目前共365个目录,里面有10个文件.log后缀的文件
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-06-27
#FileName: for_dir.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
PDIR=/data/test
for i in {1..365};do
DIR=`date -d "-$i day" +%F`
mkdir -pv $PDIR/$DIR
cd $PDIR/$DIR
for j in {1..10};do
touch $RANDOM.log
done
done

#2 .将上面的目录移动到YYYY-MM/DD/下
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-06-27
#FileName: dir.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
DIR=/data/test
cd $DIR '' { echo 无法进入 $DIR;exit 1 ; }
for subdir in * ;do
YYYY_MM=`echo $subdir 'cut -d"-" -f1,2`
DD=`echo $subdir 'cut -d"-" -f3`
[ -d $YYYY_MM/$DD ] '' mkdir -p $YYYY_MM/$DD &> /dev/null
mv $subdir/* $YYYY_MM/$DD
done
rm -rf $DIR/*-*-*

创建文件*

在/etcdir目录下创建10个html文件,文件名格式为数字N(从1到10)加随机8个字母

#!/bin/bash
[ -d /etcdir ] '' mkdir /etcdir
cd /etcdir
for i in {1..10};do                                                       
touch ${i}`cat /dev/urandom 'tr -dc '[[:alnum:]]''head -c8`.html
done

批量修改文件名

将指定目录下的文件所有文件的后缀改名为 bak 后缀

#!/bin/bash
# 
#********************************************************************
#Author:            Mr.yang                                                                   
#QQ:                1419946323
#Date:              2021-06-27
#FileName:         for_rename.sh
#URL:               www.yanghongtao.cn
#Description:      The test script
#Copyright (C):     2021 All rights reserved
#********************************************************************
DIR=/data/test
cd $DIR '' { echo 无法进入 $DIR;exit 1; }
for FILE in * ;do
    PRE=`echo $FILE 'grep -Eo ".*\."`
    mv $FILE ${PRE}bak
#   PRE=`echo $FILE'rev'cut -d. -f 2-'rev`
#   PRE=`echo $FILE ' sed -nr 's/(.*)\.([^.]+)$/\1/p'
#   PRE=`echo $FILE ' sed -nr 's/(.*)\.([^.]+)$/\2/p'`
#   mv $FILE $PRE.bak
done

九九乘法表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash                                                                                   
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-06-28
#FileName: 9x9.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
for i in {1..9};do
for (( j=1;j<=i;j++ ));do
printf "${j}x${i}=$[i*j]\t"
done
printf "\n"
done

九九彩色乘法表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-06-28
#FileName: 9x9_for.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
for i in {1..9};do
for j in `seq $i`;do
printf "\E[1;$[RANDOM%7+31]m${j}x${i}=$[i*j]\t"
done
printf "\n"
done

倒装九九彩色乘法表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-06-28
#FileName: 9x9_for.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
for ((i=1;i<=9;i++));do
for j in $(seq `echo $[10-$i]`);do
printf "\E[1;$[RANDOM%7+31]m${j}x`echo $[10-i]`=$(((10-i)*j))\E[0m\t"
done
printf "\n"
done

计算1…+100 总和

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-06-29
#FileName: user.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
sum=0;for i in {1..100};do
let sum+=i;
done
echo sum=$sum

打印三角形闪亮的小星星

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-06-29
#FileName: for_star.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
for j in {1..6};do
for i in `seq $j`;do
echo -e "\E[5;1;$[RANDOM%7+31]m*\E[0m\c"
done
echo
done

rm的安全实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-06-30
#FileName: rm.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
WARNING_COLOR="echo -e \E[1;31m"
END="\E[0m"
DIR=/tmp/`date +%F_%H-%M-%S`
mkdir $DIR
mv $* $DIR
${WARNING_COLOR}Move $* to $DIR $END
[root@centos8 ~]#chmod a+x /data/scripts/rm.sh
[root@centos8 ~]#alias rm='/data/scripts/rm.sh'
[root@centos8 ~]#touch {1..10}.txt
[root@centos8 ~]#rm *.txt
Move 10.txt 1.txt 2.txt 3.txt 4.txt 5.txt 6.txt 7.txt 8.txt 9.txt to /tmp/2020-
04-01_15-15-28

运维菜单实现

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
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-06-30
#FileName: work_menu.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
echo -en "\E[$RANDOM%7+31];1m"
cat <<EOF
请选择:
1) 备份数据库
2) 清理日志
3) 软件升级
4) 软件回滚
5) 删库跑路
EOF
echo -en '\E[0m'
read -p "请输入上面的数字1-5:" MENU
case $MENU in
1)
echo "执行备份数据库"
#./backup.sh
;;
2)
echo "清理日志"
;;
3)
echo "软件升级"
;;
4)
echo "软件回滚"
;;
5)
echo "删库跑路"
;;
*)
echo "INPUT FALSE!"
esac

显示主机系统信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-07-01
#FileName: system_info.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
RED="\E[1;31m"
GREEN="\E[1;32m"
END="\E[0m"
echo -e "$GREEN----------------------Host systeminfo--------------------$END"
echo -e "HOSTNAME: $RED`hostname`$END"
echo -e "IPADDR: $RED` ifconfig eth0|grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' |head -n1`$END"
echo -e "OSVERSION: $RED`cat /etc/redhat-release`$END"
echo -e "KERNEL: $RED`uname -r`$END"
echo -e "CPU: $RED`lscpu|grep 'Model name'|tr -s ' '|cut -d : -f2`$END"
echo -e "MEMORY: $RED`free -h|grep Mem|tr -s ' ' : |cut -d : -f2`$END"
echo -e "DISK: $RED`lsblk |grep '^sd' |tr -s ' ' |cut -d " " -f4`$END"
echo -e "$GREEN---------------------------------------------------------$END"

每天备份文件

每天备份/etc/到/backup/etcYYYY-mm-dd中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-07-02
#FileName: backup.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
COLOR='echo -e \E[1;35m'
END='E[0m'
BACKUP=/backup
SRC=/etc
DATE=`date +%F`

${COLOR}Staring backup ...$END
sleep 2
cp -av $SRC ${BACKUP}/${SRC}_$DATE
${COLOR}------Backup is finished-----$END

取磁盘使用率

编写脚本 disk.sh,显示当前硬盘分区中空间利用率最大的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-07-05
#FileName: disk.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
CL="\033[1;33m"
END="\033[0m"
TLN=`df | tr -s ' ' %|cut -d% -f5 |sort -hr|head -n1`
echo -e "The largest rate used of disk partition is :${CL}${TLN}${END}"

磁盘邮件告警-1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-07-07
#FileName: Disk_alarm.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
WARNINFO="`df 'grep -E '^/dev/sd*' 'tr -s ' ' 'cut -d ' ' -f1,5,6 'sort -nr -k2 'head -n3`"
#LARSET="`df 'grep -E '^/dev/sd*' 'tr -s ' ' 'cut -d ' ' -f1,5,6 'sort -nr -k2 'head -n1`"
#LARSET="`echo ${WARNINF} 'tr -s ' ' '%' 'cut -d% -f2 'sort -nr'head -n1`"
VALURE="`echo $WARNINFO 'tr -s '%' ' ''sort -nr 'head -n1'cut -d ' ' -f2 `"
if
[[ $VALURE -ge 10 ]]
then
echo -e "Your host's disk rate is more than 10%\n${WARNINFO}" 'mail -v -s "disk_rate " 949786521@qq.com
echo "The rate is ${VAlURE} "
else
echo "正常"
fi

磁盘邮件告警-2

实时监控本机内存和硬盘剩余空间,剩余内存小于 500M、根分区剩余空间小于 1000M时,发送报警邮件给 root 管理员

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-07-08
#FileName: waring_disk.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
#提取根分区剩余空间
disk_size=`df -m / 'awk '/\//{print $4}'`
mem_size=`free -m 'awk '/Mem/{print $4}'`
#注意内存和磁盘提取空间的大小都是以kb为单位
if [ $disk_size -le 512000 -a $mem_size -le 1024000 ];then
mail -s Waring root << EOF
Insufficient resources ,资源不足
EOF
fi

显示本机连接数

编写脚本 links.sh,显示正连接本主机的每个远程主机的IPv4地址和连接数,并按连接数从大到小排

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-07-05
#FileName: links.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
BEGIN="\e[1;35m"
END="\e[0m"
echo -e "${BEGIN}`netstat -nat'grep 'ESTAB' 'tr -s ' ' ':' 'cut -d: -f6'sort'uniq -c'sort -nr`${END}"

探测IP是否正常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-07-05
#FileName: Network_Testing.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
read -p "please input the adress :" ADDRESS

if
ping -c2 -w2 ${ADDRESS} &> /dev/null
then
echo "${ADDRESS} is up"
elif
grep -q "${ADDRESS}" ~/maintenance.txt
then
echo "${ADDRESS} is undergoing maintenance"
else
echo "station is unexpecedly DOWN!"
fi

if,else嵌套性试验

(检测用户是否存在,存在即显示信息,否则询问是否创建此用户)

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
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-07-07
#FileName: if_user.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
read -p "Please input the username :" NAME
INFO="echo `id ${NAME}`"
if
id ${NAME} &> /dev/null
then
echo -e "\033[1;32mThe user ${NAME} is exist,and ${NAME}'s information:\n${INFO}\033[0m"
else
echo -e "The user ${NAME} dont exist "
echo -e "\033[1;31mI will crate the account ${NAME},please choice "yes" or "no" \033[0m"

read -p "Please choice :" YN
if
[[ ${YN} =~ ^([Yy]'[Ee]'[Ss])$ ]];
then
useradd ${NAME};
echo "${NAME}:123456" 'chpasswd
chage -d1 ${NAME}
echo "The default password is 123456 ,you must change your passwd next login (force)"
else
echo -e "\033[1;33mwill leave and exit!!!\033[0m"
fi
fi

定时备份

每周5凌晨3点使用 tar 命令备份/var/log 下的所有日志文件

1
2
3
4
5
6
7
8
9
10
11
12
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-07-08
#FileName: logbak.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
tar -czf log-`date +%F_%H_%M_%S`.tar.gz /var/log/
#crontab -e 编写计划任务,执行备份脚本
#00 02 * * 5 /root/logbak.sh

判断当前用户

检测本机当前用户是否为超级管理员,如果是管理员,则使用 yum 安装 vsftpd,如果不是,则提示您非管理员

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-07-10
#FileName: vsftpd.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
if [ $UID -eq 0 ];then
yum -y install vsftpd
else
echo "Your are not an adminstartator,No Permissions to install software"
fi

ping 网段-1

编写脚本测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机状态(for 版本)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-07-11
#FileName: ping.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
for i in {1..254};
do
ping -f254 -c2 -i0.3 -w1 192.168.4.$i &>/dev/null
if [ $? -eq 0 ];then
echo "192.168.0.$i is up"
else
echo "192.168.0.$i is down"
fi
done

ping 网段-2

编写脚本测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机状态(while 版本)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/bin/bash
#
#********************************************************************
#Author: Mr.yang
#QQ: 1419946323
#Date: 2021-07-11
#FileName: while.sh
#URL: www.yanghongtao.cn
#Description: The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
i=1
while [ $i -le 254 ]
do
ping -f254 -c2 -i0.3 -w1 192.168.4.$i &>/dev/null
if [ $? -eq 0 ];then
echo "192.168.4.$i is up"
else
echo "192.168.4.$i is down"
fi
let i++
done

统计apache访问量

统计 13:30 到 14:30 所有访问 apache 服务器的请求有多少个

#URL:               www.yanghongtao.cn
#********************************************************************
#Author:            Mr.yang
#QQ:                1419946323
#Date:              2021-07-11
#FileName:         apache.sh
#URL:               www.yanghongtao.cn
#Description:      The test script
#Copyright (C):     2021 All rights reserved
#********************************************************************
#awk 使用‐F 选项指定文件内容的分隔符是/或者: 
#条件判断$7:$8 大于等于 13:30,并且要求,$7:$8 小于等于 14:30
#最后使用 wc ‐l 统计这样的数据有多少行,即多少个
#日志文档内容里面,第 1 列是远程主机的 IP 地址,使用 awk 单独显示第 1 列即可
awk -F "[ /:]" '$7":"$8>="13:30" && $7":"$8<="14:30"{print $1}' /var/log/httpd/access_log 

检测网站的健康性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[17:16:13 root@aliyun script]#vim curl.sh 
#!/bin/bash
usage(){
echo "Usage:$0 url"
exit 1
}
checkurl(){
local num=`curl -I -m 5 -s -w "%{http_code}\n" -o /dev/null $1 'egrep "(200'301'302)"'wc -l`
if [ $num -eq 1 ]
then
echo "$1 (Website It's ok)"
else
echo "$1i (Website It's failed)"
fi
}
main(){
if [ $# -ne 1 ]
then
usage
fi
checkurl $1
}
main $*

定时清理sleep进程

linux定时杀掉 “mysql sleep”进程

1
2
3
4
5
6
7
#!/bin/bash
echo "`date` killing mysql sleep process..." >> /tmp/crontab.log
for id in `mysql -u root -pYourPassword, -e "show processlist"|grep -i -E 'sleep'locked' | awk '{if($6>100){print $1}}'`
do
echo "killing pid $id" >> /tmp/crontab.log
echo `mysql -u root -pYourPassword, -e "kill $id"`
done

Nginx 访问日志分析脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash
# 日志格式: $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"
LOG_FILE=$1
echo "统计访问最多的10个IP"
awk '{a[$1]++}END{print "UV:",length(a);for(v in a)print v,a[v]}' $LOG_FILE |sort -k2 -nr |head -10
echo "----------------------"

echo "统计时间段访问最多的IP"
awk '$4>="[01/Dec/2018:13:20:25" && $4<="[27/Nov/2018:16:20:49"{a[$1]++}END{for(v in a)print v,a[v]}' $LOG_FILE |sort -k2 -nr|head -10
echo "----------------------"

echo "统计访问最多的10个页面"
awk '{a[$7]++}END{print "PV:",length(a);for(v in a){if(a[v]>10)print v,a[v]}}' $LOG_FILE |sort -k2 -nr
echo "----------------------"

echo "统计访问页面状态码数量"
awk '{a[$7" "$9]++}END{for(v in a){if(a[v]>5)print v,a[v]}}'

查看网卡实时流量脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#!/bin/bash
NIC=$1
echo -e " In ------ Out"
while true; do
OLD_IN=$(awk '$0~"'$NIC'"{print $2}' /proc/net/dev)
OLD_OUT=$(awk '$0~"'$NIC'"{print $10}' /proc/net/dev)
sleep 1
NEW_IN=$(awk '$0~"'$NIC'"{print $2}' /proc/net/dev)
NEW_OUT=$(awk '$0~"'$NIC'"{print $10}' /proc/net/dev)
IN=$(printf "%.1f%s" "$((($NEW_IN-$OLD_IN)/1024))" "KB/s")
OUT=$(printf "%.1f%s" "$((($NEW_OUT-$OLD_OUT)/1024))" "KB/s")
echo "$IN $OUT"
sleep 1
done

监控 100 台服务器磁盘利用率脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

#!/bin/bash
HOST_INFO=host.info
for IP in $(awk '/^[^#]/{print $1}' $HOST_INFO); do
USER=$(awk -v ip=$IP 'ip==$1{print $2}' $HOST_INFO)
PORT=$(awk -v ip=$IP 'ip==$1{print $3}' $HOST_INFO)
TMP_FILE=/tmp/disk.tmp
ssh -p $PORT $USER@$IP 'df -h' > $TMP_FILE
USE_RATE_LIST=$(awk 'BEGIN{OFS="="}/^\/dev/{print $NF,int($5)}' $TMP_FILE)
for USE_RATE in $USE_RATE_LIST; do
PART_NAME=${USE_RATE%=*}
USE_RATE=${USE_RATE#*=}
if [ $USE_RATE -ge 80 ]; then
echo "Warning: $PART_NAME Partition usage $USE_RATE%!"
fi
done
done

实战:数据备份并且邮件告警

  • 邮件告警

    1
    2
    3
    4
    5
    6
    7
    8
    9
    `使用阿里企业邮箱发送邮件`
    yum -y install mail postfix
    systemctl start postfix && systemctl enable --now postfix
    echo "set from=***@yingqidm.com" >>/etc/mail.rc #自己的邮箱 *.com
    echo "set smtp=smtp.qiye.aliyun.com" >>/etc/mail.rc # 阿里邮箱地址
    echo "set smtp-auth-user=*****@yingqidm.com" >>/etc/mail.rc #登录用户
    echo "set smtp-auth-password=******" >>/etc/mail.rc # 登录密码
    # 测试是否可以发送成功
    mail -s "Zabbix-server Automatically Backup Log Information" 1419946323@qq.com < /data/backup/backup_zabbix.log
  • 备份数据库脚本,最终实现每次备份可以看到备份时间以及备份状态,方便每次分析

    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
    #!/bin/bash
    Backup_mysql () {
    TIME=`date +%F`
    INCTIME=`date -d -1day`
    DIR=/data/backup
    DB=zabbix
    PASSWD=woxihuan123.
    Log=/data/backup/log/backup_zabbix_${TIME}.log
    [ -f ${Log} ] && touch ${Log}
    echo "=========== zabbix-server 数据库本地备份开始===========" >> ${Log}
    starttime=`date +'%Y-%m-%d %H:%M:%S'`
    echo "自动备份开始Begin Timestamp:$starttime" >> ${Log}
    #mysqldump -uroot -p"$PASSWD" -F -E -R --triggers --single-transaction --master-data=2 --default-character-set=utf8 -q -B $DB| gzip > ${DIR}/${DB}_${TIME}.sql.gz
    [ $? -eq 0 ] && echo " ✅✅ zabbix 数据库本地备份成功 ✅✅" >> ${Log} || echo " ❌❌ zabbix 数据库本地备份失败 ❌❌" >> ${Log}

    endtime=`date +'%Y-%m-%d %H:%M:%S'`
    echo "本地备份End Timestamp: $endtime" >> ${Log}
    start_seconds=$(date --date="$starttime" +%s);
    end_seconds=$(date --date="$endtime" +%s);
    time=$((end_seconds-start_seconds))
    diftime=`echo "scale=2;$time / 60" |bc`
    echo "zabbix本地备份脚本运行时间: "$diftime" min" >> ${Log}

    ls -lh ${DIR}/${DB}_${TIME}.sql.gz >> ${Log}
    cd ${DIR} && ls -1t zabbix* | awk 'NR>3 {print "rm -rf "$0}' |bash
    echo "================== Backup stop ======================" >> ${Log}
    }

    send_mail () {
    user=(yanghongtao@yingqidm.com 1419946323@qq.com) #有几个联系人需要发送就写几个,注意空格
    for i in ${user[*]};do
    mail -s "Zabbix-server Automatically Backup Log Information" $i < ${Log}
    done
    }

    main () {
    Backup_mysql
    send_mail
    }
    main

实战:备份本地cron以及用户目录脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
cat backup_cron_script.sh
#!/bin/bash

exec &>/dev/null
set -e

REMOTE_BAK_DIR="172.17.201.21:/filecoin/workdir/backup/cicd/"
dt=`date +"%F"`
cd /root
tar zcf "${dt}.tar.gz" `find godaner/ -type f|egrep -v "(\.gz|\.zip|package/|execCommandLog|log$)"` $(for i in `crontab -l|egrep -o "[^ |;]+\.(sh|py)" `;do [ -f $i ] && echo $i;done)

timeout -s 9 2m scp "${dt}.tar.gz" $REMOTE_BAK_DIR
mv "${dt}.tar.gz" /root/backup/cicd/