详解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
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
1、检查nginx基本依赖包是否安装pcre-devel openssl-devel
rpm -qa pcre-devel pcre
rpm -qa openssl-devel openssl
若没有执行以下命令安装
yum -y install pcre-devel pcre
yum -y install openssl-devel openssl
yum -y install gcc-c++
2、安装nginx
[ ! -d /home/ropon/tools ] && mkdir -p /home/ropon/tools
cd /home/ropon/tools
id -u www >/dev/null 2>&1
[ $? -ne 0 ] && useradd www -s /sbin/nologin -M -g www #创建普通用户www及www组不指定家目录
wget -c http://nginx.org/download/nginx-1.10.3.tar.gz
tar xvf nginx-1.10.3.tar.gz
cd nginx-1.10.3
./configure --user=www --group=www --prefix=/usr/local/nginx-1.10.3/ \
--with-http_stub_status_module --with-http_ssl_module
make
make install
ln -s /usr/local/nginx-1.10.3 /usr/local/nginx 便于后期升级nginx版本,及快速获取nginx版本号
--prefix=设置安装路径
--user=进程用户权限
--group=进程用户组权限
--with-http_stub_status_module 激活状态信息
--with-http_ssl_module 激活ssl功能
3、nginx.conf配置文件说明
worker_processes 4; #worker进程数量
events {
worker_connections 10240; #每个worker进程支持的最大连接数
}
http {
include mime.types; #nginx支持的媒体类型库文件
default_type application/octet-stream; #默认的媒体类型
sendfile on; #开启高效传输模式
keepalive_timeout 65; #链接超时时间
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location /ropon_ngx_status {
stub_status on; #开启nginx status
access_log off;
allow 1.1.1.1; #仅允许某个IP查看
deny all;
}
}
}
Active connections: 4 #正在处理的活动连接数
server accepts handled requests
209 209 34 启动共处理多少连接;启动共创建多少次握手(请求丢失数(握手数-连接数)); 共处理多少次请求
Reading: 0读取客户端header信息数 Writing: 1返回客户端header信息数 Waiting: 3等待下次请求驻留连接
error_log logs/error.log warnerrorcrit; #错误日志配置
可放置标签段:main,http,server,location
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
$remote_addr #记录访问网站的客户端IP
$http_x_forwarded_for #使用CDN记录真实客户端IP
$remote_user #
$time_local #访问时间
$request #请求页面
$status #访问状态码
$body_bytes_sent #响应body的大小,单位字节
$http_referer #
$http_user_agent #客户端UA信息
access_log logs/access.log main(默认日志记录格式); #配置访问日志
可放置标签段:http,server,location,if in location,limit_except
1.1.1.1 - - [23/Nov/2017:10:37:45 +0800] "GET /ropon.html HTTP/1.1" 404 571 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36" "-"
remote_addr 1.1.1.1
remote_user -
time_local 23/Nov/2017:10:37:45 +0800
request GET /ropon.html HTTP/1.1
status 404
body_bytes_sent 57字节
http_referer 直接访问故记录-
http_user_agent Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
http_x_forwarded_for 没有使用CDN故记录-
深入了解日志参数[高并发避免日志频繁写入影响IO性能]
access_log path format gzip [=level] [buffer=size] [flush=time] [if=condition];
access_log logs/access.gz main gzip buffer=32k flush=5s;
4、nginx日志切割
mkdir -p /usr/local/script
vi cut_del_logs.sh
#!/bin/bash
LOGS_PATH=/home/wwwlogs/default.gz
YESTERDAY=$(date -d "yesterday" +%Y-%m-%d)
mv ${LOGS_PATH}/access.gz ${LOGS_PATH}/access_${YESTERDAY}.gz
kill -USR1 `ps axu grep "nginx: master process" grep -v grep awk '{print $2}'`
#kill USR1 指告诉应用程序重载配置文件相当于reload
cd ${LOGS_PATH}
find . -mtime +7 -name "*20[1-9][3-9]*" xargs rm -f
exit 0
crontab -e
1 0 * * * /usr/local/script/cut_del_logs.sh
5、配置nginx虚拟主机
mkdir /usr/local/nginx/conf/vhost
mkdir -p /home/wwwroot/default
include vhost/*.conf;
cd /usr/local/nginx/conf/vhost && vi 000default.conf
server {
listen 80;
server_name 1.1.1.1
location / {
root /home/wwwroot/default;
index index.html;
}
}
6、location的使用
location [ = ~ ~* ^~ ] uri {
}
~ 区分大小写
~* 不区分大小写
!~ !~* 取反
^~ 做常规字符串检查,不做正则匹配。
location = / {
[ configuration A ]
}
location / {
[ configuration B ]
}
location /files/ {
[ configuration C ]
}
location ^~ /images/ {
[ configuration D ]
}
location ~* \.(gifjpg)$ {
[ configuration E ]
}
eg:
location = / {
return 401;
}
location /files/ {
return 402;
}
location ^~ /images/ {
return 403;
}
location ~* \.(jpg)$ {
return 405;
}
访问http://1.1.1.1 或http://1.1.1.1/ 出现401状态码
访问http://1.1.1.1/files/ 出现402状态码
访问http://1.1.1.1/images/ssfasdfsda或http://1.1.1.1/images/ 都会出现403状态码
访问http://1.1.1.1/dfasfsdfsd/sfdasdfsd.jpg或http://1.1.1.1/324123423.jpg 都会出现405状态码
=/是精确匹配优先级最高与放置顺序无关
/是默认匹配,指没有匹配上其他location,最后匹配默认
/files/是路径匹配
^~ /images/也是路径匹配,加了特殊字符^~,/files/11.jpg 优先匹配路径
~* \.(jpg)$是扩展名匹配
7、Nginx rewrite
语法:rewrite regex(正则表达式) replacement [flag];
可放置标签段:server,location,if
rewrite ^/(.*) http://1.1.1.1/$1 permanent;
^/(.*)匹配所有 匹配成功后跳转到http://1.1.1.1/$1 $1代表前面^/(.*)具体内容 permanent是永久重定向标记
\ 转义字符 \\ \$
^匹配字符串起始位置
$匹配字符串结束位置
*匹配前面字符零次或多次,比如ro* 可匹配r、roo,*相当于{0,}
+匹配前面字符一次或多次,比如ro+可匹配ro、roo,但不能匹配r,+相当于{1,}
?匹配前面字符零次或一次,比如lp(ro)?可匹配lp、lpro中lp,?相当于{0,1}
.匹配除“\n”之外的任何单字符,若要匹配\n,可使用[.\n]
(pattern)匹配括号内的pattern,并且后面可获取对应匹配,用$0,$1..$9
若要匹配括号字符,使用\( \)
last 本条规则匹配完,继续匹配下条location uri规则
break 本条规则匹配完,就终止不再继续匹配
redirect 返回302临时重定向
permanent 返回301永久重定向
例子
if ( $http_host ~* "^(.*)\.idiyrom\.com$") {
set $temp $1;
rewrite ^(.*) http://www.idiyrom.com/$temp/ropon.html;
break;
}
实现的是xxx.idiyrom.com 跳转到 www.idiyrom.com/xxx/ropon.html
8、try_files最核心的功能是可以替代rewrite
语法: try_files file ... uri 或 try_files file ... = code
try_files $uri $uri/ /?$args;
按顺序检查文件或文件夹是否存在,返回第一个找到的文件或文件夹。
结尾的斜线表示为文件夹 比如$uri/
如果所有的文件或文件夹都找不到,会进行一个内部重定向到最后一个参数/?$args
eg:
location / {
try_files $uri $uri/ /?$args;
}
比如访问http://west.idiyrom.com/imgaes/
$uri 指的是文件,比如images文件,$uri=/imgaes/
$uri/ 指的是文件夹,比如images文件夹
如果文件或文件夹都不存在,就会内部重定向到/?$args,其中$args是get方法获取的参数,比如images/test?testcanshu
日志格式:'[$cookie_customerID_cookie_flag] [$args]' '($uri)'
[-] [testcanshu](/index.html)
$args=testcanshu
9、Nginx访问认证
auth_basic
语法:auth_basic stringoff;
可放置标签段:http,server,location,limit_except
auth_basic_user_file file;
可放置标签段:http,server,location,limit_except
htpasswd -bc /usr/local/nginx/conf/htpasswd ropon 123456
chmod 400 /usr/local/nginx/conf/htpasswd
chown www /usr/local/nginx/conf/htpasswd
location = /ropon/ {
auth_basic ropon_test;
auth_basic_user_file /usr/local/nginx/conf/htpasswd;
}
10、添加启动项
cat /etc/init.d/nginx
……
nginx_install_dir=/usr/local/nginx
[ -z "`grep ^'export PATH=' /etc/profile`" ] && echo "export PATH=$nginx_install_dir/sbin:\$PATH" >> /etc/profile
[ -n "`grep ^'export PATH=' /etc/profile`" -a -z "`grep $nginx_install_dir /etc/profile`" ] && sed -i "s@^export PATH=\(.*\)@export PATH=$nginx_install_dir/sbin:\1@" /etc/profile
. /etc/profile
wget -O /etc/init.d/nginx http://mirrors.ropon.top/shell/lnmp/init.d/Nginx-init-CentOS.txt
chmod +x /etc/init.d/nginx
chkconfig --add nginx
chkconfig nginx on
自动安装shell脚本:http://mirrors.ropon.top/shell/lnmp/nginx.sh
附Rewriterule参数详解
1) R 强制外部重定向,后面可以代301或302跳转。
2) F 禁用URL,返回403HTTP状态码。
3) G 强制URL为GONE,返回410HTTP状态码。
4) P 强制使用代理转发。
5) L 表明当前规则是最后一条规则,停止分析以后规则的重写。
6) N 重新从第一条规则开始运行重写过程。
7) C 与下一条规则关联。
8) T=MIME-type(force MIME type) 强制MIME类型。
9) NS 只用于不是内部子请求。
10) NC 不区分大小写。
11) QSA 追加请求字符串。
12) NE 不在输出转义特殊字符。

更新nginx1.22.0 并安装支持lua

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
#安装所需
yum -y install pcre-devel pcre
yum -y install openssl-devel openssl
yum -y install gcc-c++

#创建普通用户及组
groupadd www && useradd www -s /sbin/nologin -M -g www

#下载所需文件
echo-nginx-module-0.62.tar.gz
luajit2-2.1-20220915.tar.gz
lua-nginx-module-0.10.22.tar.gz
lua-resty-core-0.1.24.tar.gz
lua-resty-lrucache-0.13.tar.gz
nginx-1.22.0.tar.gz
ngx_devel_kit-0.3.1.tar.gz

wget https://nginx.org/download/nginx-1.22.0.tar.gz
wget https://github.com/openresty/luajit2/archive/refs/tags/v2.1-20220915.tar.gz
wget https://github.com/openresty/lua-nginx-module/archive/refs/tags/v0.10.22.tar.gz

#批量解压
ls *.tar.gzxargs -n 1 tar -xzvf

#编译所需库
cd luajit2-2.1-20220915
make install PREFIX=/usr/local/luajit2-2.1-20220915
设置环境变量到/etc/profile
export LUAJIT_LIB=/usr/local/luajit2-2.1-20220915/lib/
export LUAJIT_INC=/usr/local/luajit2-2.1-20220915/include/luajit-2.1
source /etc/profile
ln -sf /usr/local/luajit2-2.1-20220915/lib/libluajit-5.1.so.2 /lib64/libluajit-5.1.so.2

cd ../lua-resty-core-0.1.24
make install PREFIX=/usr/local/lua_core
cd ../lua-resty-lrucache-0.13
make install PREFIX=/usr/local/lua_core

#安装nginx
cd ../nginx-1.22.0
./configure --prefix=/usr/local/nginx --user=www --group=www --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-http_ssl_module --with-stream --with-stream_ssl_preread_module --with-stream_ssl_module --with-http_gzip_static_module --with-http_realip_module --with-http_flv_module --with-http_mp4_module --add-module=../ngx_devel_kit-0.3.1 --add-module=../lua-nginx-module-0.10.22 --add-module=../echo-nginx-module-0.62
make -j 4
make install

nginx.conf http节加
lua_package_path "/usr/local/lua_core/lib/lua/?.lua;;";
nginx -t

nginx 安装https正向代理

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
#下载所需库
https://github.com/chobits/ngx_http_proxy_connect_module

#打补丁 看介绍不同版本补丁不一样
#这里是nginx-1.22.0
patch -p1 < ../ngx_http_proxy_connect_module-0.0.3/patch/proxy_connect_rewrite_102101.patch
#如果之前已安装nginx,查看之前编译参数nginx -V
--add-module=../ngx_http_proxy_connect_module-0.0.3
make && make install

#新建proxy.conf配置文件
server {
listen 1443;
charset utf-8;
#DNS解析(核心配置)
resolver 10.2.1.10;
client_max_body_size 50m;
access_log logs/access_proxy.log;

#need ngx_proxy module
proxy_connect;
proxy_connect_allow 443 80;
proxy_connect_connect_timeout 10s;
proxy_connect_read_timeout 10s;
proxy_connect_send_timeout 10s;

location / {
proxy_pass $scheme://$http_host$request_uri;
proxy_connect_timeout 10;
proxy_send_timeout 10;
proxy_read_timeout 10;
proxy_redirect off;
proxy_set_header Host $http_host;
proxy_buffers 256 4k;
proxy_next_upstream error timeout invalid_header http_502;
proxy_max_temp_file_size 0k;
proxy_ssl_server_name on;
}
}

之前是通过yum安装升级

1
2
3
4
5
6
yum -y install gcc-c++ pcre-devel pcre openssl-devel openssl
yum -y install libxslt-devel libxml2 libxml2-dev gd-devel perl-devel perl-ExtUtils-Embed gperftools

./configure --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/run/nginx.pid --lock-path=/run/lock/subsys/nginx --user=nginx --group=nginx --with-compat --with-debug --with-file-aio --with-google_perftools_module --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_degradation_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_image_filter_module=dynamic --with-http_mp4_module --with-http_perl_module=dynamic --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-http_xslt_module=dynamic --with-mail=dynamic --with-mail_ssl_module --with-pcre --with-pcre-jit --with-stream=dynamic --with-stream_ssl_module --with-stream_ssl_preread_module --with-threads --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4' --add-module=/usr/local/ngx_devel_kit-0.3.1 --add-module=/usr/local/lua-nginx-module-0.10.22 --add-module=/usr/local/echo-nginx-module-0.62
make
make install

wdcpv2升v3的全自动脚本

#!/bin/bash
#功能描述:
#1、一键升级wdcp为v3.2.2
#2、自动导入原v2.5的站点信息
#3、备份原v2.5配置文件到/home/wddata2,若需还原v2.5

恢复备份,然后将现在wddata改名,将/home/wddata2改名为/home/wddata

#注意事项:
#1、升级时,请暂停网站,以免数据不同步
#2、升级后,所有FTP用户都需要重新设置密码,也可在使用时再重设。
#3、之前部署ssl,若证书文件存放根分区,请注意备份证书文件。

PATH=”/sbin:/bin:/usr/sbin:/usr/bin”
serviceall(){
service nginxd $1
service httpd $1
service mysqld $1
service memcached $1
service pureftpd $1
}

install_ftp(){
service pureftpd stop
wget -c http://dl.wdlinux.cn/files/ftp/pure-ftpd-1.0.42.tar.gz
tar zxvf pure-ftpd-1.0.42.tar.gz
cd pure-ftpd-1.0.42
./configure –prefix=/www/wdlinux/pureftpd-1.0.42 \
–with-puredb \
–with-quotas \
–with-cookie \
–with-virtualhosts \
–with-virtualchroot \
–with-diraliases \
–with-sysquotas \
–with-ratios \
–with-altlog \
–with-paranoidmsg \
–with-shadow \
–with-welcomemsg \
–with-throttling \
–with-uploadscript \
–with-rfc2640 \
–with-ftpwho \
–with-language=simplified-chinese
make
make install
rm -f /www/wdlinux/pureftpd
ln -sf /www/wdlinux/pureftpd-1.0.42 /www/wdlinux/pureftpd
cp configuration-file/pure-config.pl /www/wdlinux/pureftpd/sbin/
chmod 755 /www/wdlinux/pureftpd/sbin/pure-config.pl
mkdir /www/wdlinux/pureftpd/etc -p
touch /www/wdlinux/pureftpd/etc/{pureftpd.passwd,pureftpd.pdb}
rm -f /www/wdlinux/etc/pure-ftpd.conf
wget -c http://www.wdlinux.cn/conf/ftp/pure-ftpd.conf -O /www/wdlinux/etc/pure-ftpd.conf
}

update_wdcp(){
ind=”/www/wdlinux/wdcp”
if [ -f $ind/data/db.inc.php ];then
if [ -d /www/wdlinux/wdcp/phpmyadmin ];then
cp -pR /www/wdlinux/wdcp/phpmyadmin /www/web/default/pma_*****
fi
sed -i ‘s#/wdcp#/wdcp2#’ /www/wdlinux/wdapache/conf/httpd.conf
service wdapache stop
mv $ind /www/wdlinux/wdcp2
wport=`grep “Listen “ /www/wdlinux/wdapache/conf/httpd.confawk ‘NR==4{print}’awk ‘{print $2}’`
grep “$wport” /www/wdlinux/wdapache/conf/httpd.conf
if [ $? == 0 ];then
sed -i “s/$wport/8090/g” /www/wdlinux/wdapache/conf/httpd.conf
iptables -I INPUT -p tcp –dport 8090 -j ACCEPT
else
iptables -I INPUT -p tcp –dport $wport -j ACCEPT
fi
iptables-save > /etc/sysconfig/iptables
fi
if [ ! -d $ind ];then
mkdir -p $ind
fi
pushd $ind
filename=”wdcp_v3.2.2_64.tar.gz”
wget -c http://dl.wdlinux.cn/files//wdcp/$filename
if [ $? == 0 ];then
tar zxvf $filename
mkdir {logs,tmp,rewrite}
ln -sf bin/wdcp_v3.2.2_64 wdcp
if [ ! -f /bin/mysql ];then
ln -s /www/wdlinux/mysql/bin/mysql /bin/mysql
fi
chown root.root bin favicon.ico html static shell conf -R
chmod 700 data conf shell bin html
ln -sf /www/wdlinux/wdcp/wdcp.sh /etc/rc.d/init.d/wdcp
chkconfig –add wdcp
chkconfig –level 35 wdcp on
pushd $ind
rm -f $filename
fi
}

wdcp_modified(){
serviceall “stop”
mv /home/wddata/ /home/wddata2
mkdir -p /home/wddata
mkdir -p /home/wddata/vhost
mkdir -p /home/wddata/wdcp
pushd /home/wddata/
mv /www/wdlinux/wdcp/etc.tar.gz ./
tar xvzf etc.tar.gz
mv /www/wdlinux/pureftpd/etc /home/wddata/etc/pureftpd_etc
ln -sf /home/wddata/etc/pureftpd_etc /www/wdlinux/pureftpd/etc
cp -pR /home/wddata2/vhost /home/wddata/vhost/apache_vhost
rm -f /www/wdlinux/apache/conf/vhost
ln -sf /home/wddata/vhost/apache_vhost /www/wdlinux/apache/conf/vhost
cp -pR /www/wdlinux/nginx/conf/vhost /home/wddata/vhost/nginx_vhost
mv /www/wdlinux/nginx/conf/vhost/ /home/wddata2/nginx_vhost
ln -sf /home/wddata/vhost/nginx_vhost /www/wdlinux/nginx/conf/vhost
rm -f /www/wdlinux/mysql/var
ln -sf /home/wddata2/var /www/wdlinux/mysql/var
rm -f /www/wdlinux/wdcp2/data
ln -sf /home/wddata2/data /www/wdlinux/wdcp2/data
mv /www/wdlinux/wdcp/conf /home/wddata/wdcp/conf
ln -sf /home/wddata/wdcp/conf /www/wdlinux/wdcp/conf
mv /www/wdlinux/wdcp/data /home/wddata/wdcp/data
ln -sf /home/wddata/wdcp/data /www/wdlinux/wdcp/data
serviceall “start”
service wdcp start
ip=`ifconfig eth0 grep “inet addr” awk ‘{ print $2}’ awk -F: ‘{print $2}’`
sh /www/wdlinux/wdcp/shell/mysqlrootchp.sh
cp -pR /home/wddata2/var /home/wddata/mysql_data
echo -e “\033[40;32mimport v2.5 data …\033[40;37m”
echo
sleep 2
curl -c ./cookie_c.txt -F “username=admin” -F “passwd=wdlinux.cn” “http://${ip}:8080/login”
sleep 2
curl -b ./cookie_c.txt “http://${ip}:8080/index?act=import”
echo
sh /www/wdlinux/wdcp/shell/wdcploginchp.sh
}

main(){
bit=`getconf LONG_BIT`
if [ $bit == ‘32’ ] ;then
echo -e “\033[1;40;31m32bit is not support!\033[0m”
exit
fi
if [ ! -d /www/wdlinux/pureftpd-1.0.42 ];then
install_ftp
fi
if [ ! -d /www/wdlinux/wdcp2 ];then
update_wdcp
fi
if [ ! -d /home/wddata2 ];then
wdcp_modified
fi
}
main
echo -e “\033[1;40;31mPlease retain the data reinstall system\033[0m”
echo
echo -e “\033[1;40;31mchown mysql.mysql -R /home/wddata/mysql_data\033[0m”
echo -e “\033[1;40;31mupdate success!\033[0m”
echo

windows2008、2012及以上一键安装php5.6、7.0

:: $Name: php56-70.bat
:: $Version: v1.1
:: $Function: 一键安装php5.6、7.0
:: $Author: Ropon
:: $organization: west.cn
:: $Create Date: 2017-4-18
:: $Description: 1、一键安装php5.6、7.0
:: 2、支持预装环境及纯净版
::#v1.1
::优化php5.6 zend、op加速组件
::优化php7.0缓存目录,安装时做了智能判断目录是否存在,权限是否正确
::
@echo off&setlocal enabledelayedexpansion
set baseurl=http://download.myhostadmin.net
if not exist %cd%\wget.exe (
echo.
echo 缺少wget.exe程序
explorer.exe %baseurl%/wget.exe
echo 正在下载wget.exe必要程序,请保存到当前目录下
echo 下载完成后按任意键继续
pause
)
if not exist %cd%\wget.exe (
echo.
echo 自动头下载失败请访问 %baseurl%/wget.exe 手动下载
echo 并保存到当前目录
echo.
pause
exit
)
echo.
:menu
echo.
echo 一键安装php5.6、7.0
echo.
echo 请选择php版本:

echo 1 php5.6
echo 2 php7.0
echo 0 退出

set /p first=

if %first% ==1 call:phpinstall 5.6
if %first% ==2 call:phpinstall 7.0
if %first% ==0 goto exit

:download
echo.
echo 正在下载所需组件
echo.
%cd%\wget.exe %1 -O %2
goto:eof

:phpinstall
echo.
if not exist D:\SOFT_PHP_PACKAGE (
echo 请输入安装路径
echo 比如:d:\php
set /p “a=:”
) else set a=D:\SOFT_PHP_PACKAGE
echo 检查 php%1 缓存目录是否存在 ……
echo.
if not exist D:\SOFT_PHP_PACKAGE\phptmp (
md D:\SOFT_PHP_PACKAGE\phptmp
echo YC:\Windows\system32\cacls D:\SOFT_PHP_PACKAGE\phptmp /T /C /P administrators:F everyone:F
)
set b=%a%\php%
1
echo 开始安装php%1 ……
if not exist %cd%\php%
1.rar (
call:download %baseurl%/php/php%1.rar %cd%\php%1.rar
)
“C:\Program Files\WinRAR\rar.exe” x -inul -o+ %cd%\php%1.rar %a% -y
cls
echo YC:\Windows\system32\cacls %b% /T /C /P administrators:F everyone:R
if not exist %cd%\vcx86php%
1.exe (
call:download %baseurl%/php/vcx86php%1.exe %cd%\vcx86php%1.exe
)
echo 正在安装VC组件 ……
%cd%\vcx86php%~1.exe /install /quiet /norestart

C:\Windows\System32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi /+”[fullPath=’%b%\php-cgi.exe’,monitorChangesTo=’%b%\php.ini’,maxInstances=’100’,instanceMaxRequests=’3000’]“ /commit:apphost
C:\Windows\System32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi /+”[fullPath=’%b%\php-cgi.exe’,monitorChangesTo=’%b%\php.ini’,maxInstances=’100’,instanceMaxRequests=’3000’].environmentVariables.[name=’PHP_FCGI_MAX_REQUESTS’,value=’1000’]“ /commit:apphost
C:\Windows\System32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi /+”[fullPath=’%b%\php-cgi.exe’,monitorChangesTo=’%b%\php.ini’,maxInstances=’100’,instanceMaxRequests=’3000’].environmentVariables.[name=’PHPRC’,value=’%b%’]“ /commit:apphost

goto end

:end
echo.
echo 需要重启iis才能生效,正在重启中……
C:\Windows\system32\iisreset
echo.
echo 已成功安装php%~1
echo.
echo 请使用建站助手创建站点,创建时请选择php5.3或5.4或5.5
echo.
echo 创建完成后请到iis管理器-找到对应站点-处理程序映射-找到php-可执行文件-5.6或7.0所在路径
echo.
echo.
echo 1 继续安装其他版本
echo 2 清理下载文件并退出
echo 0 退出
echo.
set /p choice=
if %choice% ==1 goto menu
if %choice% ==2 goto del
if %choice% ==0 goto exit

:del
echo.
echo 正在清理之前下载文件及文件夹……
echo.
for /f “delims=” %%i in (‘dir /b /a-d “php*“.rar’) do del %%i
for /f “delims=” %%i in (‘dir /b /a-d “vcx86php*“.exe’) do del %%i
pause
exit

:exit
exit

windows一键开启php_ioncube加密扩展

:: $Name: iocube.bat
:: $Version: v1.0
:: $Function: 一键安装ionCube加密扩展
:: $Author: Ropon
:: $organization: west.cn
:: $Create Date: 2017-3-10
:: $Description: 1、一键安装ionCube加密扩展
:: 2、支持预装环境及纯净版
:: 3、支持php5.2-php7.0
::
::
@echo off&setlocal enabledelayedexpansion
set base=http://download.myhostadmin.net/php/ioncube
if not exist %cd%\wget.exe (
echo.
echo 缺少wget.exe程序
explorer.exe http://download.myhostadmin.net/wget.exe
echo 正在下载wget.exe必要程序,请保存到当前目录下
echo 下载完成后按任意键继续
pause
)
if not exist %cd%\wget.exe (
echo.
echo 自动头下载失败请访问 http://download.myhostadmin.net/wget.exe 手动下载
echo 并保存到当前目录
echo.
pause
exit
)
echo.
if not exist %cd%\sed.rar (
call:download http://download.myhostadmin.net/memcache/sed.rar %cd%\sed.rar
“C:\Program Files\WinRAR\rar.exe” x -inul -o+ %cd%\sed.rar %cd% -y
cls
)

:menu
echo.
echo 请选择php版本:

echo 1 php5.2
echo 2 php5.3
echo 3 php5.4
echo 4 php5.5
echo 5 php5.6
echo 6 php7.0
echo 0 退出

set /p first=

if %first% ==1 goto php52
if %first% ==2 call:phpbase 5.3
if %first% ==3 call:phpbase 5.4
if %first% ==4 call:phpbase 5.5
if %first% ==5 call:phpbase 5.6
if %first% ==6 call:phpbase 7.0
if %first% ==0 goto exit

:download
echo.
echo 正在下载所需组件
echo.
%cd%\wget.exe %1 -O %2
goto:eof

:existfloder
echo.
echo 检查是否安装对应版本php环境
if not exist %1 (
echo.
echo 核实当前服务器没有安装php%
2
pause
goto exit
)
goto:eof

:php52
echo 请输入PHP安装路径:
echo 比如:d:\php
set path=
set /p “path=若使用建站助手,请直接回车:”
if defined path (
set a=%path%
) else set a=D:\SOFT_PHP_PACKAGE\php\
call:existfloder %a% 5.2
set url=%base%/ioncube_loader_win_5.2_ts.dll
echo 一键安装ionCube加密扩展v6.0.9
if not exist %a%ext\ioncube_loader_win_5.2_ts.dll (
call:download %url% %a%ext\ioncube_loader_win_5.2_ts.dll
cls
)
C:\Windows\system32\cacls.exe “%a%ext\ioncube_loader_win_5.2_ts.dll” /e /g everyone:r
set b=D:/\SOFT_PHP_PACKAGE/\php/\ext/\ioncube_loader_win_5.2_ts.dll
copy “%a%php.ini” “%a%php_bak.ini” >nul 2>nul
%cd%\sed\sed.exe -i “/^\[Zend/a\zend_extension_ts=%b%” %a%php.ini
goto end

:phpbase
echo 请输入PHP安装路径:
echo 比如:d:\php
set path=
set /p “path=若使用建站助手,请直接回车:”
if defined path (
set a=%path%
) else set a=D:\SOFT_PHP_PACKAGE\php%1\
call:existfloder %a% %
1
set url=%base%/ioncube_loader_win_%1.dll
set b=D:/\SOFT_PHP_PACKAGE/\php%
1/\ext/\ioncube_loader_win_%1.dll
echo 一键安装ionCube加密扩展v6.0.9
if not exist %a%ext\ioncube_loader_win_%
1.dll (
call:download %url% %a%ext\ioncube_loader_win_%1.dll
cls
)
C:\Windows\system32\cacls.exe “%a%ext\ioncube_loader_win_%
1.dll” /e /g everyone:r
copy “%a%php.ini” “%a%php_bak.ini” >nul 2>nul
%cd%\sed\sed.exe -i “/^\[Zend.loader/a\zend_extension=%b%” %a%php.ini
goto end

:end
echo.
echo 需要重启iis才能生效,正在重启中……
C:\Windows\system32\iisreset
echo.
echo 安装完成,请关闭窗口
echo.
echo.
echo 1 继续安装其他版本
echo 2 清理下载文件并退出
echo 0 退出
echo.
set /p choice=
if %choice% ==1 goto menu
if %choice% ==2 goto del
if %choice% ==0 goto exit

:del
echo.
echo 正在清理之前下载文件及文件夹……
echo.
for /f “delims=” %%i in (‘dir /b /a-d /s “sed*“‘) do del %%i
rd /s/q %cd%\sed
pause
exit

:exit
exit

Nginx反向代理IIS一键部署https

Nginx反向代理IIS 一键部署多个https站点

  • nginx反向代理IIS一键部署https
  • 支持预装环境及纯净版使用iis web环境
  • 部署后nginx配置文件推荐放到d:/nginx/conf/vhost/目录下
  • 证书路径d:/nginx/ssl 以域名命名ropon.top.crt ropon.top.key
  • 部署后nginx站点配置文件名为ropon.top.conf

具体代码

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
@echo off&setlocal enabledelayedexpansion
color 2f
set ver=1.9
set port=443
set suser=nginx
set sname=Nginxd
set sslpath=d:\ssl
set nginxpath=d:\nginx
title IIS+NGINX反向代理环境部署程序v%ver%
set vhostpath=d:\nginx\conf\vhost
set nginxconf=d:\nginx\conf\nginx.conf
set vhosttemppath=d:\nginx\conf\temp.conf
set winrarfile="C:\Program Files\WinRAR\winrar.exe"
set appcmdfile=c:\Windows\System32\inetsrv\appcmd.exe
set updateurl=http://downinfo.myhostadmin.net/vps
set baseurl=http://download.myhostadmin.net/win-ssl
set downdir=C:\Users\Administrator\Downloads
set wgetfile=C:\Users\Administrator\Downloads\wget.exe
set sedfile=C:\Users\Administrator\Downloads\sed.rar
set sedexe=C:\Users\Administrator\Downloads\sed\sed.exe

if not exist %wgetfile% (
echo.
echo 缺少wget.exe程序
::pause
echo 正在下载wget.exe必要程序
bitsadmin.exe /transfer wget /Download /Priority FOREGROUND %baseurl%/wget.exe %downdir%\wget.exe >nul 2>nul
)
if not exist %wgetfile% (
echo.
echo 自动下载失败请访问 %baseurl%/wget.exe 手动下载
echo 并保存到默认下载目录[%downdir%]
echo.
pause
exit
)

if not exist %winrarfile% (
echo.
echo 缺少WinRAR解压程序
echo 请检查安装解压程序后重新运行脚本
echo.
pause
exit
)

:update
cls
%wgetfile% %baseurl%/version.txt -O version.txt >nul 2>nul
title IIS+NGINX反向代理环境部署程序v%ver%
set /p newver=<version.txt
if %newver% gtr %ver% (
%wgetfile% %baseurl%/updatelog.txt -O updatelog.txt >nul 2>nul
title IIS+NGINX反向代理环境部署程序v%ver%
echo.
echo 当前版本v%ver%,最新版本v%newver%
echo.
echo -- 更新日志 --
for /f "delims=" %%i in (updatelog.txt) do set "updatelog=%%i"&call :logecho !updatelog!
echo.
echo 请按任意键更新...
pause >nul
%wgetfile% %updateurl%/win-ssl.bat -O win-ssl_v%newver%.bat
title IIS+NGINX反向代理环境部署程序v%ver%
cls
del /f /q "version.txt"
attrib -h -s -r -a "v%newver%log.txt"
del /f /q "updatelog.txt"
attrib -h -s -r -a "%0"
start win-ssl_v%newver%.bat
del /f /q "%0"
)
if %newver% equ %ver% (
cls
del /f /q "version.txt"
echo 已是最新版本v%newver%
)

set tmp=0123456789abcdefghijklmnopqrstuvwxyz
for /l %%a in (1,1,8) do (
set /a "n=!random!%%36"
for %%z in (!n!) do set webpasswd=!passwd!!tmp:~%%z,1!
)

echo.
echo -- 温馨提示 --
echo.
echo 1、部署前请退出服务器内安装的杀毒软件
echo 安全狗、云锁、360、金山、等安全软件有可能导致SSL证书部署出错
echo 2、主要针对我司申请的SSL证书,如还没有SSL证书,请先申请
echo 其它公司申请的证书可能有所出入,
echo 若部署失败需要自行排查,或提交正确工单我司收费排查。
echo 3、部署之前请做好相关备份,若自行部署失败不承担相关风险和责任。
echo 4、部署前请检查IIS上是否有泛域名绑定,若有请临时取消。
echo 5、推荐将证书文件解压后上传到对应站点目录下,运行脚本自动搜索部署。
echo.
echo 请阅读以上温馨提示,5秒后按任意键继续。
choice /t 5 /d y /n >nul
pause

call :menu

:menu
findstr "listen \[::\]:443 ssl http2;" %vhosttemppath% >nul 2>nul && set ipv6title=关闭IPV6 set ipv6title=开启IPV6
echo __________________________________________________________
echo ^ ^
echo ^ IIS+NGINX反向代理环境部署程序 v%ver% ^
echo ^ ^
echo ^ 1 - 安装 2 - 卸载 ^
echo ^ 3 - 部署ssl 4 - 更新ssl ^
echo ^ 5 - %ipv6title% 6 - 退出 ^
echo ^ ^
echo ^__________________________________________________________^
set /p choice=-^> 请选择:
if %choice% ==1 call :install
if %choice% ==2 call :uninstall
if %choice% ==3 call :newsetssl
if %choice% ==4 call :updatessl
if %choice% ==5 call :enableipv6
if %choice% ==6 call :exit
echo.
echo 不能输入除了1、2、3、4、5、6之外的其他字符!& choice /t 1 /d y /n >nul & cls & goto menu

:install
cls
if exist %nginxpath%\%sname%.exe (
echo.
echo 核实已安装Nginx环境,请检查服务是否启动,2s后返回主菜单。
choice /t 2 /d y /n >nul & cls & goto menu
)
if not exist %nginxpath% (
mkdir %nginxpath%
echo 创建目录:%nginxpath%成功
)
if not exist %sslpath% (
mkdir %sslpath%
echo 创建目录:%sslpath%成功
)
if not exist %vhostpath% (
mkdir %vhostpath%
echo 创建目录:%vhostpath%成功
)
if not exist %nginxpath%\%suser%.rar (
%wgetfile% %baseurl%/%suser%.rar -O %nginxpath%\%suser%.rar >nul 2>nul
title IIS+NGINX反向代理环境部署程序v%ver%
echo 下载文件:%nginxpath%\%suser%.rar成功
)
%winrarfile% x -inul -o+ %nginxpath%\%suser%.rar %nginxpath% -y >nul 2>nul
net user %suser% %webpasswd% /add /active:yes >nul 2>nul
sc create %sname% binPath= %nginxpath%\%sname%.exe >nul 2>nul
sc config %sname% start= auto type= share obj= .\%suser% password= %webpasswd% >nul 2>nul
%nginxpath%\ntrights.exe -u %suser% +r SeServiceLogonRight >nul 2>nul

cacls d:\ /G %suser%:R /E >nul 2>nul
cacls C:\Windows\System32\cmd.exe /G %suser%:R /E >nul 2>nul
echo ycacls %sslpath% /P administrators:F %suser%:F /T >nul 2>nul
echo ycacls %nginxpath% /P administrators:F %suser%:F /T >nul 2>nul
echo 创建用户:%suser%,创建服务:成功
iisreset /stop >nul 2>nul
netsh http add iplisten ipaddress=127.0.0.1 >nul 2>nul

netsh advfirewall firewall show rule name="allow443" verbose>tempfw.txt
for /f "delims=" %%a in (tempfw.txt) do (
for /f "tokens=1* delims=:" %%i in ('call echo %%a^find /i "本地端口:"') do (
echo %%a>"tempfwch.txt"
)
)
del /s /q tempfw.txt >nul 2>nul
if exist tempfwch.txt ( del /s /q tempfwch.txt >nul 2>nul ) else (
netsh advfirewall firewall add rule name="allow%port%" protocol=TCP dir=in localport=%port% action=allow >nul 2>nul
)
regedit /s %nginxpath%\good.reg >nul 2>nul
echo 调整IIS监听,放行443端口,导入优化方案成功
net start %sname%
iisreset /start >nul 2>nul
echo 服务:%sname%启动成功,IIS服务启动成功
echo 安装完成
goto menu
goto:eof

:uninstall
if not exist %nginxpath%\%sname%.exe (
echo.
echo 没有安装Nginx环境,不需要卸载,2s后返回主菜单。
choice /t 2 /d y /n >nul & cls & goto menu
)
cls
net stop %sname%
sc delete %sname%
echo 停止删除:%sname%服务成功
cacls d:\ /e /c /r %suser% >nul 2>nul
cacls %nginxpath% /t /e /c /r %suser% >nul 2>nul
cacls %sslpath% /t /e /c /r %suser% >nul 2>nul
net user %suser% /delete
::sc config IISADMIN start= auto
echo 还原:%nginxpath%,%sslpath%权限成功
iisreset /stop
netsh http delete iplisten ipaddress=127.0.0.1
iisreset /start
echo 还原IIS监听成功
rd /s /q %nginxpath% >nul 2>nul
rd /s /q %sslpath% >nul 2>nul
echo 清理:%nginxpath%,%sslpath%目录成功
echo 卸载完成
goto menu
goto:eof

:newsetssl
set domain=
set crt1path=
set crt2path=
set keypath=
set /p domain=-^> 请输入域名:
::检查输入是否为空
call :isnul domain, newsetssl
if exist %vhostpath%\%domain%.conf (
echo 核实已存在对应配置文件,请检查%domain%是否已部署SSL。
pause >nul
exit
)
echo 正在部署SSL证书的域名是%domain%...
call :forbiddenip %domain%
goto:eof

::检查是否禁止phpmyadmin被反向代理函数
:forbiddenip
if not exist %nginxpath%\%sname%.exe (
echo.
echo 没有安装Nginx环境,2s后返回主菜单,请选1安装。
choice /t 2 /d y /n >nul & cls & goto menu
)
if not exist %sedexe% (
%wgetfile% %baseurl%/sed.rar -O %sedfile% >nul 2>nul
%winrarfile% x -inul -o+ %sedfile% %downdir% -y >nul 2>nul
title IIS+NGINX反向代理环境部署程序v%ver%
echo 下载解压文件:%sedfile%成功
)
::%1就是表示批处理的第一个参数
::%~1表示删除参数外面的引号
for /f "delims=" %%a in (%nginxconf%) do set "a=%%a"&if not "!a!"=="!a:if=!" if not "!a!"=="!a:($host ~* "\d+\.\d+\.\d+\.\d+")=!" call :setssl %~1
echo.
echo 程序检测未禁止IP访问,为加固安全将自动添加以下规则禁止。
echo.
echo if ($host ~* "\d+\.\d+\.\d+\.\d+") {
echo return 403;
echo }
echo.
%sedexe% -i "/listen/a\ if ($host ~* \"\\d+\\.\\d+\\.\\d+\\.\\d+\") {" %nginxconf%
%sedexe% -i "/if/a\ return 403;" %nginxconf%
%sedexe% -i "/return 403;/a\ }" %nginxconf%
::C:\Windows\system32\net stop %sname%
::C:\Windows\system32\net start %sname%
::安装后一起重载nginx服务
for /f "delims=" %%j in ('dir /b /a-d "sed*"') do del %%j
call :setssl %~1
goto:eof

::一键更新SSL证书函数
:updatessl
set domain=
set crt1path=
set crt2path=
set keypath=
set /p domain=-^> 请输入域名:
call :isnul domain, updatessl
if not exist %vhostpath%\%domain%.conf (
echo 核实不存在%domain%配置文件,请检查是否已部署SSL。
pause >nul
exit
)
echo 正在更新SSL证书的域名是%domain%...
call :setssl %domain%

::新安装ssl证书函数
:setssl
set domain=%~1
echo %domain%
for /f "tokens=2 delims= " %%a in ('%appcmdfile% list site http://%domain%') do (set "ftpnametemp=%%a")
set ftpname=%ftpnametemp:~1,-1%
for /f %%i in ('%appcmdfile% list vdirs /app.name:%ftpname%/ /text:physicalPath') do @set webpath=%%i

:crtflg
if not exist %webpath%\%domain%.crt (
echo 请输入证书文件[%domain%.crt]的绝对路径
set /p crtpath=-^>
call :isnul crtpath,crtflg
call :crtpath
) else (
echo.
echo 在%domain%网站根目录找到证书文件
echo [%webpath%\%domain%.crt]
set crtpath=%webpath%\%domain%.crt
)
set crtpathtemp=%crtpath:~0,-4%
set keypathtemp=%crtpathtemp%.key

:keyflg
if not exist %keypathtemp% (
echo 请输入秘钥文件[%domain%.key]的绝对路径
set /p keypath=-^>
call :isnul keypath,keyflg
call :keypath
) else (
echo.
echo 在证书文件1的目录找到秘钥文件
echo [%keypathtemp%]
set keypath=%keypathtemp%
echo.
)
C:\Windows\system32\more "%crtpath%" > "%sslpath%\%domain%.crt"
copy "%keypath%" "%sslpath%\%domain%.key" >nul 2>nul
if not exist %vhosttemppath% (
echo 找不到nginx模板配置文件%vhosttemppath%,程序将自动退出。
pause >nul
exit
)
copy "%vhosttemppath%" "%vhostpath%\%domain%.conf" >nul 2>nul
set sslvhostpath=%vhostpath%\%domain%.conf
set sslpathtemp=d:/ssl
set crt=%sslpathtemp%/%domain%.crt
set key=%sslpathtemp%/%domain%.key

%sedexe% -i "/listen/a\ server_name %domain%;" %sslvhostpath%
%sedexe% -i "/server_name/a\ ssl_certificate %crt%;" %sslvhostpath%
%sedexe% -i "/ssl_certificate/a\ ssl_certificate_key %key%;" %sslvhostpath%
C:\Windows\system32\net stop %sname%
C:\Windows\system32\net start %sname%
for /f "delims=" %%j in ('dir /b /a-d "sed*"') do del %%j
echo 安装完成,请关闭窗口
echo 站点配置文件:%sslvhostpath%
echo 证书文件路径:%sslpath%\%domain%.crt
echo %sslpath%\%domain%.key
goto menu
::goto:eof cmd返回并将等待下一命令
goto:eof

:crtpath
if not exist %crtpath% (
echo %crtpath% 不是有效证书文件
set /p crtpath=-^>
call :crtpath
)
goto:eof

:keypath
if not exist %keypath% (
echo %keypath% 不是有效秘钥文件
set /p keypath=-^>
call :keypath
)
goto:eof

:logecho
echo %1
goto:eof

:isnul
if not defined %~1 (
echo 输入为空,请重新输入。
goto %~2
)
goto:eof

:enableipv6
%sedexe% -i "/listen/a\ listen [::]:80;" %nginxconf%
%sedexe% -i "/listen/a\ listen [::]:443 ssl http2;" %vhosttemppath%
echo 开启IPV6成功
goto menu
goto:eof

:exit
exit

1分钟教会你标准的shell脚本

#!/bin/bash
#######################################################

$Name: shell_template.sh

$Version: v1.0

$Function: Introduce Function Template Script

$Author: Ropon

$organization: https://www.west.cn

$Create Date: 2016-1-20

$Description: You know what i mean,hehe

#######################################################

Shell Env

SHELL_NAME=”shell_template.sh”
SHELL_DIR=”/root”
SHELL_LOG=”${SHELL_DIR}/${SHELL_NAME}.log”
LOCK_FILE=”/tmp/${SHELL_NAME}.lock”
#Write Log
shell_log(){
LOG_INFO=$1
echo “$(date “+%Y-%m-%d”) $(date “+%H-%M-%S”) : ${SHELL_NAME} : ${LOG_INFO}” >> ${SHELL_LOG}
}

Shell Usage

shell_usage(){
echo $”Usage: $0 {backup}”
}
shell_lock(){
touch ${LOCK_FILE}
}
shell_unlock(){
rm -f ${LOCK_FILE}
}

Backup MySQL All Database with mysqldump or innobackupex

funcname(){
if [ -f “$LOCK_FILE” ];then
shell_log “${SHELL_NAME} is running”
echo “${SHELL_NAME}” is running && exit
fi
shell_log “mysql backup start”
shell_lock
sleep 10
shell_log “mysql backup stop”
shell_unlock
}

Main Function

main(){
case $1 in
backup)
funcname
;;
*)
shell_usage;
esac
}
#Exec
main $1

wdcp一键开启php_ioncube加密扩展

# 1、一键开启 # 2、自适应php5.2-php7.0 # 3、自适应apache、nginx及系统版本

#!/bin/bash
#######################################################

$Name: ioncube.sh

$Version: v1.0

$Function: wdcp一键开启php_ioncube加密扩展

$Author: Ropon

$organization: west.cn

$Create Date: 2017-3-10

$Description: 1、一键开启

2、自适应php5.2-php7.0

3、自适应apache、nginx及系统版本

#######################################################

php_install_dir=/www/wdlinux/php
PHP_version=`$php_install_dir/bin/php -r ‘echo PHP_VERSION;’`
Ver=${PHP_version%.*}

if [ “$(getconf WORD_BIT)” == “32” ] && [ “$(getconf LONG_BIT)” == “64” ]; then
OS_BIT=64
else
OS_BIT=32
fi
inifile=`$php_install_dir/bin/php -inigrep ‘php.ini’awk ‘{print $6}’`/php.ini
temp=`grep -E ‘\[ionCube Loader\]‘ $inifile`

if [ ! -n “$temp” ] ;then
if [ ! -f ioncube_loader_lin.so ];then
case “${OS_BIT}” in
64)
wget -O ioncube_loader_lin.so -c http://download.myhostadmin.net/php/ioncube/ioncube\_loader\_lin\_${Ver}.so
;;
32)
wget -O ioncube_loader_lin.so -c http://download.myhostadmin.net/php/ioncube/ioncube\_loader\_lin\_x86\_${Ver}.so
;;
*)
echo “Error!”
exit 1
;;
esac
fi
[ ! -d “`$php_install_dir/bin/php-config –extension-dir`“ ] && mkdir -p `$php_install_dir/bin/php-config –extension-dir`
/bin/cp ioncube_loader_lin.so `$php_install_dir/bin/php-config –extension-dir`
zend_extension=”`$php_install_dir/bin/php-config –extension-dir`/ioncube_loader_lin.so”
rm -rf ioncube_loader_lin.so
sed -i “/^\[PHP/i\[ionCube Loader]“ $inifile
sed -i “/^\[ionCube/a\zend_extension=$zend_extension” $inifile
num=`ps -efgrep -w “nginx”grep -v grepwc -l`
if [ ${num} -eq 0 ] ;then
service httpd restart
else
service httpd restart
service php-fpm restart
fi
echo
echo “ioncube install is OK”
echo
else
echo
echo “Error! ioncube install is OK?”
echo
exit 1
fi

基于Nginx一键部署https

基于Nginx一键部署https

  • 1、基于nginx自动部署https,自动设置301
  • 2、自动判断是否升级nginx和openssl
  • 3、支持wdcph环境或其他已安装好nginx环境
  • 4、部署后nginx配置文件推荐放到/home/nginx-vhost/目录下(可选)
  • 5、证书路径/home/ssl 以域名命名www.test.com.crt www.test.com.key
  • 6、部署后nginx站点配置文件名为test.com_ssl.conf

具体代码

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
SHELL_NAME="nginx-ssl.sh"
SHELL_DIR="/root"
SHELL_LOG="${SHELL_DIR}/${SHELL_NAME}.log"
LOCK_FILE="/tmp/${SHELL_NAME}.lock"
function myi18n(){
if [[ "$#" -ne 1 ]]
then
echo "demo"
fi
if [[ $LANG =~ [Uu][Tt][Ff] ]]
then
echo "$1"
else
echo "$1" iconv -f utf-8 -t gbk
fi
}
#Write Log
shell_log(){
LOG_INFO=$1
myi18n "$(date "+%Y-%m-%d") $(date "+%H-%M-%S") : ${SHELL_NAME} : ${LOG_INFO}" >> ${SHELL_LOG}
}
shell_lock(){
touch ${LOCK_FILE}
}
shell_unlock(){
rm -f ${LOCK_FILE}
}
end(){
shell_unlock
exit
}
shell_log "信息:脚本开始运行"
if [ -f "$LOCK_FILE" ];then
shell_log "${SHELL_NAME} 脚本正在运行中,若不是请使用 rm -rf /tmp/nginx-ssl.sh.lock 命令清理锁文件"
myi18n "${SHELL_NAME} 脚本正在运行中,若不是请使用 rm -rf /tmp/nginx-ssl.sh.lock 命令清理锁文件" && exit
fi
shell_lock
homeconfpath=/home/nginx-ssl/conf
if [ ! -d "$homeconfpath" ];then
myi18n "请输入nginx安装路径,比如:/usr/local/nginx"
myi18n "如果使用wdcp环境,请直接回车"
read -p ": " confpath
if [ -z "$confpath" ] ;then
confpath=/www/wdlinux/nginx
fi
confpath1=${confpath}/conf
while [ ! -d "$confpath1" ]
do
myi18n "您输入路径${confpath1}不存在,请重新输入"
shell_log "错误:您输入路径${confpath1}不存在,请重新输入"
read -p ": " confpath
if [ -z "$confpath" ] ;then
confpath=/www/wdlinux/nginx
fi
confpath1=${confpath}/conf
done
temp=`find $confpath1 -maxdepth 1 -name 'nginx.conf'`
while ([ -z $temp ] [ ! -f "$temp" ])
do
myi18n "nginx安装路径不对,请重新输入"
shell_log "错误:${confpath1} 路径下没有找到nginx.conf,请检查"
echo
read -p ": " confpath
if [ -z $confpath ] ;then
confpath=/www/wdlinux/nginx
wdcp=y
fi
confpath1=${confpath}/conf
temp=`find $confpath1 -maxdepth 1 -name 'nginx.conf'`
done
shell_log "信息:nginx配置文件路径 ${confpath1}"
myi18n "是否一键移动nginx配置文件到/home/nginx目录下并创建好软连接"
read -p "[y/n]: " conf_move
while [[ ! $conf_move =~ ^[y,n]$ ]]
do
echo "input error! Please only input 'y' or 'n'"
echo
read -p "[y/n]: " conf_move
done
if [ "$conf_move" == 'y' ] ;then
if [ ! -d "$homeconfpath" ];then
mkdir -p $homeconfpath
cp -rf ${confpath}/conf/* $homeconfpath
cd $confpath
mv conf/ conf-bak/
ln -sf $homeconfpath conf
if [ "$wdcp" == 'y' ] ;then
chown wdcpu.wdcpg $homeconfpath -R
fi
fi
else
homeconfpath=${confpath}/conf
fi
else
echo
myi18n "自动搜索到:nginx配置文件路径为 ${homeconfpath}"
shell_log "信息:自动搜索到:nginx配置文件路径为 ${homeconfpath}"
echo
fi
if [ -d "/www/wdlinux/nginx" ] ;then
wdcp=y
myi18n "使用wdcp环境,nginx版本为"
/www/wdlinux/nginx/sbin/nginx -v 2>&1awk -F '/' '{print $2}'
shell_log "信息:当前使用wdcp环境"
fi
shell_log "信息:nginx的vhost文件路径 ${homeconfpath}"
homesslpath=/home/ssl
[ ! -d "$homesslpath" ] && mkdir -p $homesslpath
shell_log "信息:ssl证书存放路径 ${homesslpath}"
pushd ${homeconfpath}/vhost/

myi18n "请输入需要安装证书站点绑定的域名,比如:www.test.com"
myi18n "如果二级域名有绑定到其他站点,请使用www.test.com,不要输入顶级域名"
read -p ": " domain
while [ -z $domain ]
do
myi18n "域名不能为空,请重新输入。"
echo
read -p ": " domain
done
files=`grep -l " ${domain}" *.confawk 'NR==1{print}'sed 's/\.conf//'`
if [ ! -n "$files" ] ;then
echo
echo ${domain}
myi18n "关联站点,没有找到!"
shell_log "警告:没有找到域名 ${domain} 对应配置文件"
echo
end 1
fi
files1=${homeconfpath}/vhost/${files}.conf
shell_log "信息:要部署域名 ${domain} 的配置文件是 ${files1}"
sslfile=${homeconfpath}/vhost/${files}_ssl.conf
if [ -f "$sslfile" ];then
crt=`grep -E 'ssl_certificate' ${sslfile}awk -F 'ssl_certificate ' '{print $2}'awk 'NR==1{print}'sed 's/\;//'`
key=`grep -E 'ssl_certificate_key' ${sslfile}awk -F 'ssl_certificate_key ' '{print $2}'sed 's/\;//'`
if [ -f "$crt" ] && [ -f "$key" ];then
echo
echo ${domain}
myi18n "关联站点证书已安装!"
shell_log "警告:域名 ${domain} 已成功部署"
echo
end 1
fi
echo
echo ${domain}
myi18n "关联站点ssl配置文件已存在,是否需要删除?"
read -p "[y/n]: " ssl_check
while [[ ! $ssl_check =~ ^[y,n]$ ]]
do
echo "input error! Please only input 'y' or 'n'"
echo
read -p "[y/n]: " ssl_check
done
if [ "$ssl_check" == 'y' ];then
rm -rf $sslfile
else
echo
echo ${domain}
myi18n "已存在ssl配置文件,请核实后重新运行程序。"
shell_log "警告:要部署域名 ${domain} 已存在部署后配置文件 ${sslfile}"
end 1
fi
fi
temp12=`grep -E 'https://' ${files1}`
if [ -n "$temp12" ] ;then
echo
echo ${domain}
myi18n "对应配置文件存在301转向(return 301),是否需要删除?"
read -p "[y/n]: " s_check
while [[ ! $s_check =~ ^[y,n]$ ]]
do
echo "input error! Please only input 'y' or 'n'"
echo
read -p "[y/n]: " s_check
done
if [ "$s_check" == 'y' ];then
sed -i '/^.*return.*301 https/d' $files1
else
echo
echo ${domain}
myi18n "域名 ${domain} 对应配置文件${files}存在301转向,请先删除对应行"
shell_log "警告:域名 ${domain} 对应配置文件${files}存在301转向,请先删除对应行"
end 1
fi
fi
crt1=${homesslpath}/${domain}.crt
key1=${homesslpath}/${domain}.key
if [ ! -f "$crt1" ];then
myi18n "我司申请在nginx上部署需要先合并,请输入y或者n?"
read -p "[y/n]: " crt_yn
while [[ ! $crt_yn =~ ^[y,n]$ ]]
do
echo "input error! Please only input 'y' or 'n'"
echo
read -p "[y/n]: " crt_yn
done
if [ "$crt_yn" == 'y' ] ;then
myi18n "请输入cer证书路径,比如 /root/test.com.cer"
myi18n "/root/test.com.cer"
read -p "Please reinput crtpath1 : " crtpath1
while ([ -z "$crtpath1" ] [ ! -f "$crtpath1" ])
do
myi18n "需要合并证书1不能为空或路径错误,请重新输入。"
shell_log "警告:需要合并证书1 ${crtpath1} 为空或路径错误"
echo
read -p ": " crtpath1
done
pathtemp=`echo $crtpath1awk -F '.cer' '{print $1}'`
crtpath2temp=${pathtemp}_ca.crt
keypathtemp=${pathtemp}.key
echo $crtpath2temp
echo $keypathtemp
if [ ! -f "$crtpath2temp" ];then
myi18n "/root/test.com_ca.crt"
read -p "Please reinput crtpath2 : " crtpath2
while ([ -z "$crtpath2" ] [ ! -f "$crtpath2" ])
do
myi18n "需要合并证书2不能为空或路径错误,请重新输入。"
shell_log "警告:需要合并证书2 ${crtpath2} 为空或路径错误"
echo
read -p ": " crtpath2
done
else
crtpath2=$crtpath2temp
echo
myi18n "自动搜索到:域名 ${domain} 证书cacrt文件路径为 ${crtpath2temp}"
myi18n "系统会自动补全合并为~/${domain}.crt"
shell_log "自动搜索到:域名 ${domain} 证书cacrt文件路径为 ${crtpath2temp}"
echo
fi
shell_log "信息:域名 ${domain} 需要合并证书1 ${crtpath1}"
shell_log "信息:域名 ${domain} 需要合并证书2 ${crtpath2}"
cat $crtpath1 $crtpath2 >> ~/$domain.crt
crtpath=~/${domain}.crt
else
myi18n "请输入需要安装证书路径:eg /root/test.com.crt"
read -p "Please reinput crtpath : " crtpath
while ([ -z "$crtpath" ] [ ! -f "$crtpath" ])
do
myi18n "crt证书路径不能为空或路径错误,请重新输入。"
shell_log "警告:crt证书路径 ${crtpath} 为空或路径错误"
echo
read -p ": " crtpath
done
fi
cp ${crtpath} ${homesslpath}/${domain}.crt
else
echo
myi18n "自动搜索到:域名 ${domain} 证书crt文件路径为 ${homesslpath}/${domain}.crt"
shell_log "信息:自动搜索到:域名 ${domain} 证书crt文件路径为 ${homesslpath}/${domain}.crt"
echo
fi
if [ ! -f "$key1" ] ;then
if [ ! -f "$keypathtemp" ] ;then
myi18n "请输入需要安装证书路径:eg /root/test.com.key"
read -p "Please reinput keypath : " keypath
while ([ -z "$keypath" ] [ ! -f "$keypath" ])
do
myi18n "key证书路径不能为空或路径错误,请重新输入。"
shell_log "警告:key证书路径 ${keypath} 为空或路径错误"
echo
read -p ": " keypath
done
else
keypath=$keypathtemp
echo
myi18n "自动搜索到:域名 ${domain} 证书key文件路径为 ${keypathtemp}"
shell_log "自动搜索到:域名 ${domain} 证书key文件路径为 ${keypathtemp}"
echo
fi
cp ${keypath} ${homesslpath}/${domain}.key
else
echo
myi18n "自动搜索到:域名 ${domain} 证书key文件路径为 ${homesslpath}/${domain}.key"
shell_log "信息:自动搜索到:域名 ${domain} 证书key文件路径为 ${homesslpath}/${domain}.key"
echo
fi
shell_log "信息:域名 ${domain} 证书crt文件路径为 ${homesslpath}/${domain}.crt"
shell_log "信息:域名 ${domain} 证书key文件路径为 ${homesslpath}/${domain}.key"
cp ${files}".conf" ${homeconfpath}/vhost/${files}"_ssl.conf"
shell_log "信息:域名 ${domain} 部署后 ssl配置文件为 ${homeconfpath}/${files}_ssl.conf"
if [ "$wdcp" == 'y' ] ;then
chown wdcpu.wdcpg * -R
shell_log "信息:核实为wdcp环境,设置${homeconfpath} 所有者及所属组为wdcpu.wdcpg"
fi

sed -i "s/80/443 ssl/g" ${sslfile}
sed -i "/root/a\ ssl_certificate $crt1;" ${sslfile}
sed -i "/ssl_certificate/a\ ssl_certificate_key $key1;" ${sslfile}
sed -i "/ssl_certificate_key/a\ ssl_protocols TLSv1 TLSv1.1 TLSv1.2;" ${sslfile}
sed -i "/ssl_protocols/a\ ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;" ${sslfile}
myi18n "是否需要一键设置301转向,请输入y或者n?"
read -p "[y/n]: " zx_yn
while [[ ! $zx_yn =~ ^[y,n]$ ]]
do
echo "input error! Please only input 'y' or 'n'"
echo
read -p "[y/n]: " zx_yn
done
if [ "$zx_yn" == 'y' ] ;then
myi18n "请输入跳转后地址比如:"
read -p "${domain}: " server_name1
if [ -z $server_name1 ] ;then
server_name1='$server_name'
fi
request_uri1='$request_uri'
sed -i "/server_name/a\ return 301 https://$server_name1$request_uri1;" ${files1}
shell_log "信息:域名 ${domain} 已设置301跳转到https://${server_name1}${request_uri1} ${files1}"
fi
service nginxd restart
iptables -L -n grep -w dpt:80 >/dev/null
if [ $? -eq 0 ] ;then
iptables -L -n grep -w dpt:443 >/dev/null
if [ $? -ne 0 ] ;then
echo
myi18n "正在放行443端口"
echo
sed -i "/dport 80 -j ACCEPT/a\-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT" /etc/sysconfig/iptables
service iptables restart
else
myi18n "核实已放行443端口"
fi
else
myi18n "iptables服务似乎没有运行"
fi
curl -I https://${domain}
echo
echo ${domain}
myi18n "关联站点证书已安装完成!"
myi18n "证书文件存放/home/ssl,以域名方式命名。"
echo
myi18n "域名 ${domain} 证书crt文件路径为 ${homesslpath}/${domain}.crt"
myi18n "域名 ${domain} 证书key文件路径为 ${homesslpath}/${domain}.key"
echo
cp -rf ${homeconfpath}/vhost /home/nginx-vhost-bak
myi18n "同时已备份当前nginx配置文件到/home/nginx-vhost-bak"
if [ "$wdcp" == 'y' ] ;then
myi18n "如果使用wdcp环境,请不要登录wdcp切换web引擎,否则配置文件将被覆盖!"
fi
shell_log "信息:${domain} 关联站点证书已安装完成"
pushd /root/
if [ "$wdcp" == 'y' ] && [ ! -d /www/wdlinux/nginx-1.10.2 ] ;then
myi18n "核实nginx和openssl版本较低,若要通过苹果ats认证,请升级"
function homemove(){
confpath=/www/wdlinux/nginx
if [ "${homeconfpath}" == "/www/wdlinux/nginx/conf" ] ;then
echo $homeconfpath;
myi18n "不需要移动配置文件"
else
cp -rf ${confpath}/conf/* $homeconfpath
cd $confpath
mv conf/ conf-bak/
ln -sf $homeconfpath conf
chown wdcpu.wdcpg $homeconfpath -R
fi
}
read -p "[y/n]: " update
while [[ ! $update =~ ^[y,n]$ ]]
do
echo "input error! Please only input 'y' or 'n'"
echo
read -p "[y/n]: " update
done
if [ "$update" == 'y' ];then
wget http://downinfo.myhostadmin.net/wdcp/nginx_up.sh
sh nginx_up.sh
homemove
shell_log "信息:核实为wdcp环境,已选择升级nginx和OpenSSL"
fi
fi
shell_log "信息:脚本正常退出"
shell_unlock

Centos7环境下全自动创建kvm虚拟机

主要功能

  • 自动配置外网、内网ip
  • 自动设置主机名
  • 自动扩容数据盘
  • 可预设定vnc、root密码

具体代码

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
#!/bin/bash
#centos6,7 模板数据盘都是10G

export PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin"

dateTime=$(date +%Y%m%d%H%M%S)
tmpDiskFile6_os="/vmdata/template/centos64_os"
tmpDiskFile6_data="/vmdata/template/centos64_data"
tmpDiskFile7_os="/vmdata/template/template_os.qcow2"
tmpDiskFile7_data="/vmdata/template/template_data.qcow2"
vmDir="/vmdata"
test -d $vmDir mkdir -p $vmDir
vncpasswd="ropon.top"
newpasswd="ropon.top"

help() {
cat >> /dev/stdout <<EOF
Usage: $(basename $0) vmname vcpu memory ip [TempleteDiskFile] -h
Example: ./$(basename $0) vmname=ebs-11 vcpu=1 memory=1024M datasize=20 ip=192.168.7.221 ostype=centos7
Example: ./$(basename $0) vmname=ebs-2 vcpu=1 memory=1024M datasize=20 ip=192.168.123.12 ostype=centos6
Example: ./$(basename $0) -h //print help infomations
EOF
}

error() {
echo -e "input parameter error: $1 \n please try again!"
}

if [[ "$#" -eq 0 "$1" == "-h" ]]; then
help
exit 0
fi

for line in $@
do
case $line in
vmname*)
vmName=$(echo $line awk -F "=" '{print $2}')
;;
vcpu*)
vCpu=$(echo $line awk -F "=" '{print $2}')
if ! echo $vCpu grep '^[0-9]$' > /dev/null; then
error $line
help
exit 1
fi
;;
memory*)
memTmp=$(echo $line awk -F "=" '{print $2}')
memNum=$(echo ${memTmp:0:${#memTmp}-1})
memUnit=$(echo ${memTmp:0-1} tr '[a-z]' '[A-Z]')
if ! echo $memNum grep '[0-9]' > /dev/null; then
error $line
help
exit 1
fi
if [[ "$memUnit" != "G" && "$memUnit" != "M" && "$memUnit" != "K" ]]; then
error $line
help
exit 1
fi
;;
datasize*)
datasize=$(echo $line awk -F "=" '{print $2}')
if ! echo $datasize grep '^[0-9]' > /dev/null; then
error $line
help
exit 1
fi
;;
ip*)
vmIp=$(echo $line awk -F "=" '{print $2}')
if ! echo $vmIp grep '[0-9]\{1,3\}\(\.[0-9]\{1,3\}\)\{3\}' > /dev/null; then
error $line
help
exit 1
fi
;;
ostype*)
ostype=$(echo $line awk -F "=" '{print $2}')
[ $ostype == "centos6" ] && echo "you chose centos6" && diskFile=$tmpDiskFile6_os && diskFile1=$tmpDiskFile6_data
[ $ostype == "centos7" ] && echo "you chose centos7" && diskFile=$tmpDiskFile7_os && diskFile1=$tmpDiskFile7_data
if [ ! -f "$diskFile" ] [ ! -f "$diskFile1" ] ; then
error $line
help
exit 1
fi
;;
*)
error $line
help
exit 1
;;
esac
done

if [ -z "$vmName" ] [ -z "$vCpu" ] [ -z "$memNum" ] [ -z "$vmIp" ];
then
echo -e "input parameter incomplete: $@"
help
exit 1
fi

#read -p "please input vnc passwd:" vncpasswd
if [ -z $vncpasswd ] ;then
vncpasswd=`echo $RANDOMmd5sumcut -c 1-6`
fi
create_config() {
memUnit="$memUnit"iB
cat > $vmDir/$vmName/$vmName.xml <<EOF
<domain type='kvm'>
<name>$vmName</name>
<uuid>$vmUuid</uuid>
<memory unit='$memUnit'>$memNum</memory>
<currentMemory unit='$memUnit'>$memNum</currentMemory>
<vcpu placement='static'>$vCpu</vcpu>
<cpu mode='host-passthrough'/>
<os>
<type arch='x86_64' machine='pc'>hvm</type>
<boot dev='cdrom'/>
<boot dev='hd'/>
<bootmenu enable='yes'/>
</os>
<features>
<acpi/>
<apic/>
</features>
<clock offset='utc'>
<timer name='rtc' tickpolicy='catchup'/>
<timer name='pit' tickpolicy='delay'/>
<timer name='hpet' present='no'/>
</clock>
<on_poweroff>destroy</on_poweroff>
<on_reboot>restart</on_reboot>
<on_crash>restart</on_crash>
<pm>
<suspend-to-mem enabled='no'/>
<suspend-to-disk enabled='no'/>
</pm>
<devices>
<emulator>/usr/bin/qemu-system-x86_64</emulator>
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2'/>
<source file='$vmDir/$vmName/$vmNameos'/>
<target dev='vda' bus='virtio'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x06' function='0x0'/>
</disk>
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2'/>
<source file='$vmDir/$vmName/$vmNamedata'/>
<target dev='vdb' bus='virtio'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x16' function='0x0'/>
</disk>
<disk type='file' device='cdrom'>
<driver name='qemu' type='raw'/>
<target dev='hda' bus='ide'/>
<readonly/>
<address type='drive' controller='0' bus='0' target='0' unit='0'/>
</disk>
<controller type='usb' index='0' model='ich9-ehci1'>
<address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x7'/>
</controller>
<controller type='usb' index='0' model='ich9-uhci1'>
<master startport='0'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0' multifunction='on'/>
</controller>
<controller type='usb' index='0' model='ich9-uhci2'>
<master startport='2'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x1'/>
</controller>
<controller type='usb' index='0' model='ich9-uhci3'>
<master startport='4'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x2'/>
</controller>
<controller type='pci' index='0' model='pci-root'/>
<controller type='ide' index='0'>
<address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>
</controller>
<controller type='virtio-serial' index='0'>
<address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
</controller>
<interface type='bridge'>
<mac address='$vmMac'/>
<source bridge='br0'/>
<model type='virtio'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
</interface>
<interface type='bridge'>
<mac address='$vmMac1'/>
<source bridge='br1'/>
<model type='virtio'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x13' function='0x0'/>
</interface>
<serial type='pty'>
<target port='0'/>
</serial>
<console type='pty'>
<target type='serial' port='0'/>
</console>
<channel type='unix'>
<target type='virtio' name='org.qemu.guest_agent.0'/>
<address type='virtio-serial' controller='0' bus='0' port='1'/>
</channel>
<input type='tablet' bus='usb'>
<address type='usb' bus='0' port='1'/>
</input>
<input type='mouse' bus='ps2'/>
<input type='keyboard' bus='ps2'/>
<graphics type='vnc' port='-1' autoport='yes' listen='0.0.0.0' passwd='$vncpasswd'>
<listen type='address' address='0.0.0.0'/>
</graphics>
<video>
<model type='cirrus' vram='16384' heads='1' primary='yes'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
</video>
<memballoon model='virtio'>
<address type='pci' domain='0x0000' bus='0x00' slot='0x07' function='0x0'/>
</memballoon>
</devices>
</domain>
EOF
}

create_mac() {
test -f /tmp/mac.py && rm -f /tmp/mac.py
cat > /tmp/mac.py <<EOF
#!/usr/bin/python
# macgen.py script to generate a MAC address for Red Hat Virtualization guests
#
import random
#
def randomMAC():
mac = [ 0x54, 0x52, 0x00,
random.randint(0x00, 0x7f),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff) ]
return ':'.join(map(lambda x: "%02x" % x, mac))
#
print randomMAC()
EOF
vmMac=$(python /tmp/mac.py)
vmMac1=$(python /tmp/mac.py)
}

create_uuid() {
vmUuid=$(uuidgen)
}

dots() {
sec=$1
while true
do
echo -e ".\c"
sleep $sec
done
}

define_kvm() {

virsh define $vmDir/$vmName/$vmName.xml
if [ $? -ne 0 ]; then
echo -e "virsh define $vmName.xml error!"
exit 1
fi
virsh start $vmName
if [ $? -ne 0 ]; then
echo -e "virsh start $vmName error!"
exit 1
fi
virsh list
vncPort=$(virsh vncdisplay $vmName)
vncIp=`ifconfig br0grep -w inetawk '{print $2}'`
echo -e "VNC IP and Port is: $vncIp$vncPort"
echo -e "$vmName vnc passwd:$vncpasswd \n"
}

modify_disk() {
#vmHostName=$(echo $vmIp awk -F "." '{print "YN-" $3 "-" $4}')
vmIpPri=172.16.$(echo $vmIp awk -F "." '{print $3 "." $4}')
#vmGy=${vmIp%.*}.1
vmGy=192.168.0.1
vmNm=255.255.248.0
vmNm1=255.255.255.0
mnttemp=/tmp/$vmName
[ ! -d $mnttemp ] && mkdir -p $mnttemp
guestmount -a $vmDir/$vmName/$vmNameos -m /dev/sda2 --rw $mnttemp
if [ $? -ne 0 ]; then
echo -e "mount $vmDir/$vmName/$vmNameos failed! "
exit 1
fi
tmpGy="$mnttemp/etc/sysconfig/network"
tmpIp1="$mnttemp/etc/sysconfig/network-scripts/ifcfg-eth0"
tmpIp2="$mnttemp/etc/sysconfig/network-scripts/ifcfg-eth1"
sed -i "/^127.0/a\127.0.0.1 $vmName" $mnttemp/etc/hosts
sed -i "s/GATEWAY=/GATEWAY=$vmGy/g" $tmpGy
sed -i "s/IPADDR=/IPADDR=$vmIp/g" $tmpIp1
sed -i "s/NETMASK=/NETMASK=$vmNm/g" $tmpIp1
sed -i "s/IPADDR=/IPADDR=$vmIpPri/g" $tmpIp2
sed -i "s/NETMASK=/NETMASK=$vmNm1/g" $tmpIp2
#read -p "please input root passwd:" newpasswd
if [ -z $newpasswd ] ;then
newpasswd=`echo $RANDOMmd5sumcut -c 7-12`
fi
sed -i "s/passwdtemp/$newpasswd/g" $mnttemp/root/set.sh
sed -i "s/vmnametemp/$vmName/g" $mnttemp/root/set.sh
sed -i "s/tempdisksize/$tempdisksize/g" $mnttemp/root/set.sh
sed -i "/^touch/a\/root/set.sh" $mnttemp/etc/rc.d/rc.local
sleep 1
umount $mnttemp
sleep 1
rm -rf $mnttemp
}

main() {
vmNameos="$vmName"_os.qcow2
vmNamedata="$vmName"_data.qcow2
test -d $vmDir/$vmName mkdir -p $vmDir/$vmName
if [ -f "$vmDir/$vmName/$vmName.xml" ]; then
mv $vmDir/$vmName/$vmName.xml $vmDir/$vmName/$vmName.xml.$dateTime
echo -e "$vmDir/$vmName/$vmName.xml exist, rename $vmDir/$vmName/$vmName.xml.$dateTime "
fi
echo -e "create virtual machine config file:"
[ -f "/etc/libvirt/qemu/$vmName.xml" ] && echo -e "$vmName is exist, Please check!" && exit 1
create_mac
create_uuid
create_config
echo -e "create config file($vmDir/$vmName/$vmName.xml) success"
if [ ! -f "$diskFile" ]; then
echo -e "$diskFile not found, Please try again!"
exit 1
fi
if [ ! -f "$diskFile1" ]; then
echo -e "$diskFile1 not found, Please try again!"
exit 1
fi
if [ -f "$vmDir/$vmName/$vmNameos" ]; then
mv $vmDir/$vmName/$vmNameos $vmDir/$vmName/$vmNameos.$dateTime
echo -e "$vmDir/$vmName/$vmName exist, rename $vmDir/$vmName/$vmName.$dateTime "
fi
echo -e "cow 写时复制新技术生成: $vmDir/$vmName/$vmNameos"
qemu-img create -f qcow2 -b $diskFile $vmDir/$vmName/$vmNameos
echo -e "cow 写时复制新技术生成: $vmDir/$vmName/$vmNamedata"
qemu-img create -f qcow2 -b $diskFile1 $vmDir/$vmName/$vmNamedata
[ $ostype == "centos7" ] && tempdisksize=$[datasize -10]
[ $ostype == "centos6" ] && tempdisksize=$[datasize -10]
if [ $tempdisksize -gt 0 ];then
echo -e "modify data_os size ..."
qemu-img resize $vmDir/$vmName/$vmNamedata +${tempdisksize}G
fi
}

startTime=`date +%s`
main
echo
echo -e "modify virtual machine IP and Hostname..."
modify_disk
echo -e "define virtual machine ..."
define_kvm
echo -e "$vmName ip: $vmIp\n"
echo -e "$vmName gy: $vmGy\n"
echo -e "$vmName nip: $vmIpPri\n"
echo -e "$vmName root passwd:$newpasswd \n"
echo -e "create KVM virtual machine:$vmName finish! \n"
endTime=`date +%s`
installTime=$[$endTime-$startTime]
echo "create kvm time: $installTime second"

Centos7环境下制作kvm模板

创建一个虚拟机安装模板系统

  • vnc密码:ropon.top
  • 不要使用lvm方式安装,使用标准分区,然后点击自动创建分区安

一键创建虚拟机

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
#!/bin/bash
# Author: Ropon
# Blog: https://www.ropon.top

LANG=en_US.UTF-8
export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
declare -A Colors
Colors=([failure]="31m" [success]="32m" [warning]="33m" [msg]="34m")
name=CreateKvm
ver=1.0
LogFile=/tmp/.$(basename $0).log

#格式输出及写日志
Echo() {
[ ! $1 ] && flag="34m" flag=$1
echo -e "\033[1;${Colors[${flag}]}${2}\033[0m"
echo "$(date "+%Y-%m-%d") $(date "+%H-%M-%S"):${name}:[$1] $2" >> $LogFile
}

Main() {
[ ! -d /vmdata ] && mkdir /vmdata
[ ! -d /vmdata/iso ] && mkdir -p /vmdata/iso
[ ! -d /vmdata/template ] && mkdir -p /vmdata/template
[ ! -f /vmdata/iso/centos7.iso ] && wget -O /vmdata/iso/centos7.iso http://mirrors.163.com/centos/7.7.1908/isos/x86_64/CentOS-7-x86_64-Minimal-1908.iso
[ ! -f /vmdata/template/centos7_os.qcow2 ] && qemu-img create -f qcow2 -o preallocation=metadata /vmdata/template/centos7_os.qcow2 10G
[ ! -f /vmdata/template/centos7_data.qcow2 ] && qemu-img create -f qcow2 -o preallocation=metadata /vmdata/template/centos7_data.qcow2 10G

virt-install --virt-type kvm --name=template --ram=2048 --vcpus=2 --cdrom=/vmdata/iso/centos7.iso \
--network bridge=br0 --network bridge=br1 --noautoconsole --os-type=linux --os-variant=rhel7 \
--disk path=/vmdata/template/centos7_os.qcow2,format=qcow2,bus=virtio,cache=writeback --disk path=/vmdata/template/centos7_data.qcow2,format=qcow2,bus=virtio,cache=writeback \
--graphics vnc,listen=0.0.0.0,password=ropon.top --boot cdrom,hd,menu=on --accelerate
[ $? -eq 0 ] && Echo "success" "kvm创建成功,请使用vnc客户端连接制作模板"
}

Main

模板一键优化脚本

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
#!/bin/bash
# Author: Ropon
# Blog: https://www.ropon.top

LANG=en_US.UTF-8
export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
declare -A Colors
Colors=([failure]="31m" [success]="32m" [warning]="33m" [msg]="34m")
name=CreateKvm
ver=1.0
LogFile=/tmp/.$(basename $0).log
eth0f="/etc/sysconfig/network-scripts/ifcfg-eth0"
eth1f="/etc/sysconfig/network-scripts/ifcfg-eth1"
hostname=template

#获取系统及版本
CheckOS() {
if [ -e /etc/redhat-release ]; then
OS=CentOS
[ -n "$(grep ' 7\.' /etc/redhat-release 2> /dev/null)" ] && CentOSVer=7
[ -n "$(grep ' 6\.' /etc/redhat-release 2> /dev/null)" ] && CentOSVer=6
elif [ -n "$(grep -i 'Debian' /etc/issue 2> /dev/null)" ]; then
OS=Debian
elif [ -n "$(grep -i 'Ubuntu' /etc/issue 2> /dev/null)" ]; then
OS=Ubuntu
else
OS=UnknownOS
fi
}

#格式输出及写日志
Echo() {
[ ! $1 ] && flag="34m" flag=$1
echo -e "\033[1;${Colors[${flag}]}${2}\033[0m"
echo "$(date "+%Y-%m-%d") $(date "+%H-%M-%S"):${name}:[$1] $2" >> $LogFile
}

Main() {
CheckOS
[ $CentOSVer -ne 7 ] && Echo "warning" "暂时仅支持Centos7.x" && exit
yum install -y wget
# 调整yum源及epel源
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
wget -O /etc/yum.repos.d/epel-7.repo http://mirrors.aliyun.com/repo/epel-7.repo
yum clean all
yum makecache
# 安装常用命令
yum install -y net-tools vim screen tcpdump ntp sysstat
# 优化配置及参数
# - 关闭禁用firewalld、NetworkManager服务、postfix服务
systemctl disable firewalld
systemctl stop firewalld
systemctl disable NetworkManager
systemctl stop NetworkManager
systemctl disable postfix
systemctl stop postfix

#优化You have new mail in /var/spool/mail/root 提示
echo "unset MAILCHECK" >> /etc/profile

# - 关闭禁用SELINUX
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
grep SELINUX=disabled /etc/selinux/config
setenforce 0
# 安装iptables服务
yum install -y iptables-services
cat > /etc/sysconfig/iptables <<EOF
*filter
# 配置几个链默认行为 比如INPUT链 默认丢弃
# [0:0] 第一个值表示丢弃包的个数
# 第二个值表示丢弃包的总字节,其他同理。
:INPUT DROP [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:syn-flood - [0:0]
# 本地回环
-A INPUT -i lo -j ACCEPT

-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
# 放行SSH端口
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT

# ICMP包控制
-A INPUT -p icmp -m limit --limit 1/sec --limit-burst 10 -j ACCEPT
-A INPUT -f -m limit --limit 100/sec --limit-burst 100 -j ACCEPT

# UDP控制
-A OUTPUT -d 119.29.29.29/32 -p udp -m udp --dport 53 -j ACCEPT
-A OUTPUT -d 114.114.114.114/32 -p udp -m udp --dport 53 -j ACCEPT
-A OUTPUT -p udp -m udp --dport 123 -j ACCEPT
-A OUTPUT -p udp -j DROP
COMMIT
EOF
service iptables reload
# 调整DNS配置
cat > /etc/resolv.conf <<EOF
nameserver 119.29.29.29
nameserver 114.114.114.114
EOF

# 调整时区
rm -rf /etc/localtime
ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

# 同步时间
sed -i '/ntpdate/d' /var/spool/cron/root
echo '*/10 * * * * /usr/sbin/ntpdate cn.pool.ntp.org ' >>/var/spool/cron/root
service crond restart
ntpdate -u cn.pool.ntp.org

# 优化历史命令history
[ -z "$(grep ^'export PROMPT_COMMAND=' /etc/bashrc)" ] && cat >> /etc/bashrc << EOF
export PROMPT_COMMAND='{ msg=\$(history 1 { read x y; echo \$y; });logger "[euid=\$(whoami)]":\$(who am i):[\`pwd\`]"\$msg"; }'
EOF
# 优化SSH配置
# - 关闭SSH反向查询,以加快SSH的访问速度
sed -i 's@.*UseDNS yes@UseDNS no@' /etc/ssh/sshd_config
# - 禁止空密码登录
sed -i 's@PermitEmptyPasswords no@PermitEmptyPasswords no@' /etc/ssh/sshd_config

# 内核参数优化
# - 表示套接字由本端要求关闭,这个参数决定了它保持在FIN-wAIT-2状态的时间,默认值是60秒,建议调整为2
echo 'net.ipv4.tcp_fin_timeout = 2' >> /etc/sysctl.conf
# -表示开启重用,允许TIME-wAIT sockets重新用于新的TCP链接,默认值为0,表示关闭
echo 'net.ipv4.tcp_tw_reuse = 1' >> /etc/sysctl.conf
# - 表示开启TCP链接中TIME_WAIT sockets的快速回收 默认为0 表示关闭,不建议开启,因为nat网络问题
echo 'net.ipv4.tcp_tw_recycle = 0' >> /etc/sysctl.conf

# - 表示开启SYN Cookies功能,当出现SYN等待队列溢出时,启用Cookies来处理,可防范少量SYN攻击
echo 'net.ipv4.tcp_syncookies = 1' >> /etc/sysctl.conf
# - 表示当keepalive启用时,TCP发送keepalive消息的频度,默认是2小时,建议更改为10分钟
echo 'net.ipv4.tcp_keepalive_time =600' >> /etc/sysctl.conf
# - 该选项用来设定允许系统打开的端口范围,即用于向外链接的端口范围
echo 'net.ipv4.ip_local_port_range = 32768 60999' >> /etc/sysctl.conf
# - 表示SYN队列的长度 默认为1024 建议加大队列的长度,为8182或更多
# 这样可以容纳更多等待链接的网络连接数,该参数为服务器端用于记录那些尚未收到客户端确认信息的链接请求的最大值
echo 'net.ipv4.tcp_max_syn_backlog = 8182' >> /etc/sysctl.conf
# - 该选项默认值是128,这个参数用于调节系统同时发起的TCP连接数,在高并发的请求中,默认的值可能会导致链接超时或重传,因此,需要结合并发请求数来调节此值
echo 'net.core.somaxconn = 1024' >> /etc/sysctl.conf
# - 表示系统同时保持TIME_WAIT套接字的最大数量,如果超过这个数值,TIME_WAIT套接字将立刻被清除并打印警告信息,默认为5000
# 对于Aapache,Nginx等服务器来说可以将其调低一点,如改为5000-30000,不用业务的服务器也可以给大一点,比如LVS,Squid
echo 'net.ipv4.tcp_max_tw_buckets = 5000' >> /etc/sysctl.conf
# - 表示内核放弃建立链接之前发送SYN包的数量 默认是6
echo 'net.ipv4.tcp_syn_retries = 1' >> /etc/sysctl.conf
# - 参数的值决定了内核放弃链接之前发送SYN+ACK包的数量 默认是2
echo 'net.ipv4.tcp_synack_retries = 1' >> /etc/sysctl.conf
# - 表示当每个网络接口接收数据包的速率比内核处理这些包的速率快时,允许发送到队列的数据包最大数 默认值为1000
echo 'net.core.netdev_max_backlog = 1000' >> /etc/sysctl.conf
# - 用于设定系统中最多有多少个TCP套接字不被关联到任何一个用户文件句柄上,如果超过这个数值,孤立链接将立即被复位并打印出警号信息
# 这个限制只是为了防止简单的DoS攻击,不能过分依靠这个限制甚至人为减小这个值,更多的情况是增加这个值,默认是4096,建议该值修改为2000
echo 'net.ipv4.tcp_max_orphans = 2000' >> /etc/sysctl.conf

# - 以下参数是对iptables防火墙的优化
# CentOS7.X系统中的模块名不是ip_conntrack,而是nf_conntrack
echo
'net.ipv4.nf_conntrack_max = 25000000
net.ipv4.netfilter.nf_conntrack_max = 25000000
net.ipv4.netfilter.nf_conntrack_tcp_timeout_established = 180
net.ipv4.netfilter.nf_conntrack_tcp_timeout_time_wait = 120
net.ipv4.netfilter.nf_conntrack_tcp_timeout_close_wait = 60
net.ipv4.netfilter.nf_conntrack_tcp_timeout_fin_wait = 120' >> /etc/sysctl.conf

sysctl –p

# - 优化文件描述符
echo ' * - nofile 100000 ' >>/etc/security/limits.conf

# 更新系统
yum update -y

# 修改主机名
hostnamectl --static set-hostname $hostname
NetMod
echo "#!/bin/bash
umount /home
fdisk -S 56 /dev/vdb << EOF
d
n
p
1

wq
EOF
resize2fs -f /dev/vdb1
mount -a" >> /root/disk.sh
cat > /root/set.sh <<EOF
#!/bin/bash
(echo "passwdtemp";sleep 1;echo "passwdtemp") passwd > /dev/null
hostnamectl --static set-hostname vmnametemp
sed -i "s/\/root\/set.sh//g" /etc/rc.d/rc.local
tempdata=tempdisksize
if [ \$tempdata -gt 0 ];then
/root/disk.sh
fi
rm -rf /root/disk.sh
rm /root/set.sh
reboot
EOF

chmod +x /root/set.sh
chmod +x /root/disk.sh
chmod +x /etc/rc.d/rc.local
ls -la /root/set.sh
ls -la /etc/rc.d/rc.local

fdisk -S 56 /dev/vdb << EOF
n
p
1

wq
EOF
mkfs.ext4 /dev/vdb1
echo "/dev/vdb1 /home ext4 defaults 0 0" >> /etc/fstab
mount -a
df -vh
cat > /etc/sysconfig/grub <<EOF
GRUB_TIMEOUT=5
GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT="console"
GRUB_CMDLINE_LINUX="crashkernel=auto rhgb net.ifnames=0 biosdevname=0 quiet"
GRUB_DISABLE_RECOVERY="true"
EOF
grub2-mkconfig -o /boot/grub2/grub.cfg
rm -f /etc/udev/rules.d/*persistent-net.rules
history -c
[ $? -eq 0 ] && Echo "success" "KVM模板制作成功"
shutdown -h 0
}

NetMod() {
cat > /etc/sysconfig/network <<EOF
GATEWAY=
EOF
cat > $eth0f <<EOF
TYPE=Ethernet
BOOTPROTO=static
NAME=eth0
DEVICE=eth0
ONBOOT=yes
IPADDR=
NETMASK=
EOF
cat > $eth1f <<EOF
TYPE=Ethernet
BOOTPROTO=static
NAME=eth1
DEVICE=eth1
ONBOOT=yes
IPADDR=
NETMASK=
EOF
}

Main