通用脚本

域名证书到期时间

监控证书到期时间并告警发送到飞书

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/bin/bash
export LANG="en_US.UTF-8"

CheckDate () {
caEnd=`curl -v -s -o /dev/null --stderr - $1 | grep expire|awk -F ': ' '{print $2}'`
epochCa=`date +%s -d "$caEnd"`
epochNow=`date +%s`

seconds_to_expire=`expr $epochCa - $epochNow`
days_to_expire=`expr $seconds_to_expire / 86400`
if [ $days_to_expire -lt 15 ];then
curl -X POST 'https://open.feishu.cn/open-apis/bot/v2/hook/1d4ec947-141d-4b39-a2ab-8f4cxxxxxx' -H "Content-Type: application/json" -d '{"msg_type":"text","content":{"text":"告警:'"$1"'域名证书不足'"$days_to_expire"'天"}}'
fi
}

CheckDate https://www.baidu.com/

获取Harbor镜像仓库tag

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
#获取harbor镜像tag

USER="admin"
PASS="Harbor12345"
HURL="http://10.0.1.120:8000"
MTAG="moxi-pre/"$1""

ttoken=$(curl -iksL -X GET -u $USER:$PASS $HURL/service/token?account=${USER}\&service=harbor-registry\&scope=repository:${MTAG}:pull|grep "token" |awk -F '"' '{print $4}')

#echo $ttoken

tlist=$(curl -ksL -X GET -H "Content-Type: application/json" -H "Authorization: Bearer $ttoken" ${HURL}/v2/${MTAG}/tags/list|awk -F '[' '{print $2}'|awk -F ']' '{print $1}'|sed 's/"//g')

echo $tlist|sed 's/,/\n/g'|sort -nr|head -n 10

nginx自动获取k8s svc创建规则

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
# 自动生成nginx配置,代理k8s中的svc
source /etc/profile
desconf="/etc/nginx/conf.d/k8s-extend"

echo "" > $desconf
IFS=$'\n\n'
for i in `/usr/bin/kubectl get svc -A|egrep -v "(kube-system)|(default)|(istio-system)|(None)|(center)|(grpc-game)"|awk '{print $1" "$2" "$4" "$6}'|awk -F '/' '{print $1}'|awk -F ':' 'NR>1{print $1}'`
do
namespace=`echo $i|cut -d ' ' -f1`
name=`echo $i|cut -d ' ' -f2`
ip=`echo $i|cut -d ' ' -f3`
port=`echo $i|cut -d ' ' -f4`

cat >>$desconf<<EOF
location /$namespace-$name/{
proxy_pass http://$ip:$port/;
}
EOF
done

nginx -t
[ $? -eq 0 ] && nginx -s reload || exit 502

k8s证书到期

1
2
3
4
5
6
#!/bin/bash

Days=`kubeadm alpha certs check-expiration|grep admin.conf|awk '{print $7}'|awk -F 'd' '{print $1}'`
if [ $Days -lt 30 ];then
curl -X POST 'https://open.feishu.cn/open-apis/bot/v2/hook/1d4ec947-141d-4b39-a2ab-xxxxxx' -H "Content-Type: application/json" -d '{"msg_type":"text","content":{"text":"告警:k8s证书不足'"$Days"'天"}}'
fi

k8s节点内存监控

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash
set -xe
node_ip="192.168.0.53 192.168.0.128 192.168.0.238 192.168.0.176"

for i in $node_ip
do
num=`ssh root@$i free -b|awk 'NR=1{printf $7}'`
if [ $num -lt 5368709120 ];then
/usr/local/bin/kubectl cordon $i
elif [ $num -gt 8589934592 ];then
/usr/local/bin/kubectl uncordon $i
fi
done

k8s定时扩容

1
2
3
#!/bin/bash
source /etc/profile
/usr/local/bin/kubectl scale deployment/play-mall --replicas=$1 -n moxi-center

zabbix性能报表

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
#!/bin/bash
#每周报表生成脚本

time=`date '+%Y%m%d%H%M%S'`
ntime=$(date '+%Y-%m-%d %H:%M:%S')
wtime=$(date -d "-1 week" '+%Y-%m-%d %H:%M:%S')

echo "
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>资源报表</title>
</head>
<body>
<h1 align="center">"$wtime" to "$ntime"</h1>
" > /scripts/${time}.html

SAVEIFS=$IFS
IFS=$(echo -en "\n")

# cpu
cpu=`zabbix_api --report "CPU utilization" "$wtime" "$ntime" --table --sort 5 --desc --hostgroupid "Linux servers"|egrep "[0-9]{5}"|sed "s/|//g"|sed "s/\.[0-9]*//g"`

#cpu=`cat /root/test|egrep "[0-9]{5}"|sed "s/|//g"|sed "s/\.[0-9]*//g"`

echo "<div><h1>CPU使用率</h1><table border=1 cellspacing=0 style='width:100%;font-size: 40px;'><tr><td>主机</td><td>最小值</td><td>最大值</td><td>平均值</td></tr>" >> /scripts/${time}.html
for i in $cpu
do
echo $i|awk '{print "<tr><td>"$2"</td><td>"$5" %</td><td>"$7" %</td><td>"$9" %</td></tr>"}' >> /scripts/${time}.html
done
echo "</table></div>" >> /scripts/${time}.html

# mem
mem=`zabbix_api --report "Memory utilization" "$wtime" "$ntime" --table --sort 5 --desc --hostgroupid "Linux servers"|egrep "[0-9]{5}"|sed "s/|//g"|sed "s/\.[0-9]*//g"`

echo "<div><h1>内存使用率</h1><table border=1 cellspacing=0 style='width:100%;font-size: 40px;'><tr><td>主机</td><td>最小值</td><td>最大值</td><td>平均值</td></tr>" >> /scripts/${time}.html
for i in $mem
do
echo $i|awk '{print "<tr><td>"$2"</td><td>"$5" %</td><td>"$7" %</td><td>"$9" %</td></tr>"}' >> /scripts/${time}.html
done
echo "</table></div>" >> /scripts/${time}.html

# disk
zabbix_api --report "/: Space utilization" "$(date -d "-4 hour" '+%Y-%m-%d %H:%M:%S')" "$(date -d "-2 hour" '+%Y-%m-%d %H:%M:%S')" --table --sort 5 --desc --hostgroupid "Linux servers"|egrep "[0-9]{5}"|sed "s/|//g"|sed "s/\.[0-9]*//g"|grep -v k8s > /tmp/k8s_disk
zabbix_api --report "/host: Space utilization" "$(date -d "-2 hour" '+%Y-%m-%d %H:%M:%S')" "$(date -d "-1 hour" '+%Y-%m-%d %H:%M:%S')" --table --sort 5 --desc --hostgroupid "Linux servers"|egrep "[0-9]{5}"|sed "s/|//g"|sed "s/\.[0-9]*//g" >> /tmp/k8s_disk

echo "<div><h1>磁盘使用率</h1><table border=1 cellspacing=0 style='width:100%;font-size: 40px;'><tr><td>主机</td><td>最小值</td><td>最大值</td><td>平均值</td></tr>" >> /scripts/${time}.html

for i in `cat /tmp/k8s_disk`
do
echo $i|awk '{print "<tr><td>"$2"</td><td>"$6" %</td><td>"$8" %</td><td>"$10" %</td></tr>"}' >> /scripts/${time}.html
done
echo "</table></div>" >> /scripts/${time}.html

IFS=$SAVEIFS

echo "
</body>
</html>
" >> /scripts/${time}.html

scp /scripts/${time}.html root@10.0.1.120:/data/nginxWebUI/html/baobiao/
ssh root@10.0.1.120 "chmod 777 /data/nginxWebUI/html/baobiao/${time}.html"
rm -f /scripts/${time}.html

curl -i -X POST \
'https://open.feishu.cn/open-apis/bot/v2/hook/1d4ec947-141d-4b39-a2ab-8f4c60e42f67' \
-H 'Content-type':'application/json' \
-d '
{
"msg_type": "post",
"content": {
"post": {
"zh_cn": {
"title": "性能报表",
"content": [
[
{
"tag": "text",
"text": "每周云服务器性能报表,按最大值降序排列"
},
{
"tag": "a",
"text": "请查看",
"href": "http://183.134.214.86:20001/'${time}'.html"
},
{
"tag": "at",
"user_id": "all",
"user_name": "所有人"
}
]
]
}
}
}
}
'

zabbix飞书告警

1
2
3
4
5
6
7
#!/bin/bash
to=$1
subject=$2
text=$3

#飞书报警脚本,发送到运维部门群
curl -X POST 'https://open.feishu.cn/open-apis/bot/v2/hook/1d4ec947-141d-4b39-a2ab-xxxxxx' -H "Content-Type: application/json" -d '{"msg_type":"text","content":{"text":"'"$text"'"}}'

zabbix钉钉告警

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/bin/bash
to=$1
subject=$2
text=$3

#钉钉报警脚本,发送到运维部门群
curl -i -X POST \
'https://oapi.dingtalk.com/robot/send?access_token=cb8ddfe0377c28a4294439e3a9b47588aaccbde11054a1f0163dd7a6xxxxxx' \
-H 'Content-type':'application/json' \
-d '
{
"msgtype": "text",
"text": {
"content": "'"$text"'"
},
"at":{
"atMobiles":[
"'"$1"'"
],
"isAtAll": "true"
}
}'

es查询指定索引字段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/bin/bash
# 安装邮件工具
if [ ! -e "/tmp/sendEmail-v1.56/sendEmail" ];then
cd /tmp && wget http://caspian.dotconf.net/menu/Software/SendEmail/sendEmail-v1.56.tar.gz && tar xf sendEmail-v1.56.tar.gz && chmod +x /tmp/sendEmail-v1.56/sendEmail
fi

# 获取elasticsearch指定索引,指向条件,指定时间的错误
data=`curl -s -H "Content-Type:application/json" -XPOST http://172.16.190.240:9200/err-dockerlogs-*/_search -d '{"query": {"bool": {"must": [{"bool": {"should": [{"match_phrase": {"message": "Cause: java.sql.SQLSyntaxErrorException:"}},{"match_phrase": {"message": "### Error updating database"}},{"match_phrase": {"message": "### Cause: java.sql"}},{"match_phrase": {"message": "message:### SQL"}},{"match_phrase": {"message": "SQLException"}}]}},{"range": {"@timestamp": {"gte": "now-5m/m","lte": "now/m","format": "epoch_millis"}}}]}},"from": 0,"size": 5}'`

# 转为可读json格式
jqdata=`echo $data|jq .`

# 获取错误总数
num=`echo $data|cut -d ":" -f 10|cut -d "," -f 1`

# 发送邮件报警
if [ "$num" -gt "0" ];then
echo $num
/tmp/sendEmail-v1.56/sendEmail -o message-charset="utf-8" -f 111@111.com -t 222@222.com -s smtp.111.com -u "elk-sql-err" -xu 111@111.com -xp 1111.1234 -m "$jqdata" -o tls=no
fi

根据目录下文件名生成文件列表

1
2
3
4
5
6
7
#!/bin/bash
dest_dir="/data/html/域名或ip/public-images"

for i in `ls -R $dest_dir | grep "^/" | awk -F ':' '{print $1}'`
do
find $i -maxdepth 1 -type f |sed "s#/data/html/域名或ip#https:\/\/game-cdn.moxigame.cn#g"|egrep -v "(上传说明|link_list.txt|public-images$)"|sort -n > $i/link_list.txt
done

批量添加指定字符串后面多行内容

1
2
3
4
5
6
7
#!/bin/bash
dir=/Users/mac/.jenkins/jobs

for i in `ls $dir|grep Release`
do
sed 's#<parameterDefinitions>#& \n <hudson.plugins.validating__string__parameter.ValidatingStringParameterDefinition plugin="validating-string-parameter@2.8">\n <name>输入:确认发布</name>\n <defaultValue></defaultValue>\n <regex>确认发布</regex>\n <failedValidationMessage>请确认是否发布生产</failedValidationMessage>\n </hudson.plugins.validating__string__parameter.ValidatingStringParameterDefinition>#' ${dir}/${i}/config.xml
done

监控目录执行脚本

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
#网盘目录<public-images>是同步线上cdn资源目录,运营使用
#监听<public-images>目录,当有文件创建时,自动生成线上域名路径列表<link_list.txt>,存储到文件当前目录
#该脚本使用后台&运行

dest_dir="/data/nextcloud/data/root/files/运营/public-images"

#<inotifywait>监听目录变化工具
inotifywait -rmq --format '%w %f %e' -e create,move $dest_dir |while read line
do
dir_path=`echo $line|awk '{print $1}'`
dir_name=`echo $line|awk '{print $2}'`
dir_event=`echo $line|awk '{print $3}'`
docker_path=`echo $line|awk '{print $1}'|sed 's#/data/nextcloud/data##g'`

if [ $dir_event == "CREATE,ISDIR" ];then
touch ${dir_path}${dir_name}/link_list.txt
#创建文件时,刷新网盘目录
docker exec -u33 nextcloud php occ files:scan --path=$docker_path &> /dev/null
elif [ $dir_event == "CREATE" ] || [ $dir_event == "MOVED_FROM" ] || [ $dir_event == "MOVED_TO" ];then
ls ${dir_path}* |sed "s#/data/nextcloud/data/root/files/运营#https:\/\/game-cdn.moxigame.cn#g"|egrep -v "(上传说明|link_list.txt|public-images$)"|sort -n > ${dir_path}link_list.txt
fi
done

python3 k8s触发器工具

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
from flask import Flask, request
import requests
from kubernetes import client, config
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

app = Flask(__name__)


@app.route(rule='/', methods=['POST'])
def replace_deployment():
# 获取body json数据
data = request.get_json()
name = data['name']
namespace = data['namespace']
update_image = data['update_image']
token = data['token']
host = data['host']

# 初始化k8s连接配置
configuration = client.Configuration()
configuration.host = host
configuration.verify_ssl = False
configuration.api_key = {"authorization": "Bearer " + token}
client.Configuration.set_default(configuration)

# 创建更新对象
api_instance = client.AppsV1Api()
body = api_instance.read_namespaced_deployment(name, namespace)
body.spec.template.spec.containers[0].image = update_image
try:
api_response = api_instance.replace_namespaced_deployment(
name, namespace, body)
print(" 33[0;32m{} 中deployment : {} {}更新完成 33[0m".format(
namespace, name, update_image))
except ApiException as e:
print("Exception when calling AppsV1Api->replace_namespaced_deployment: %sn" % e)
return update_image


if __name__ == '__main__':
app.run(host="0.0.0.0", port=8080)

python分析nginx日志

用于分析nginx日志,并返回html页面结果,index.html是在templates目录下

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
#!/usr/bin/python3
from collections import Counter
from flask import Flask,render_template
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import time,os

app=Flask(__name__)

# 日志文件路径
nginx_log_dir = os.getenv("nginx_log_dir", default="access.log1")

# 请求限制变量(1/second 1/minute)
nginx_log_qes = os.getenv("nginx_log_qes", default="2/minute")

# 排序字典,根据value排序,取前n个最大值
def top_n_scores(n, score_dict):
if len(score_dict)<10:
n = len(score_dict)
lot = [(k,v) for k, v in score_dict.items()]
nl = []
while len(nl)<n:
nl.append(max(lot, key=lambda x: x[1]))
lot.remove(nl[-1])
return nl[0:n]

# 时间提示
def time_tips(time_name):
print(time_name + ":" + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))

# 全局配置,限制客户端ip,每分钟请求一次
limiter = Limiter(app=app, key_func=get_remote_address, default_limits=["30/second"])

# flask路由
@app.route('/nginx/<query_time>')
def index(query_time):
time_tips("start")
# 处理日志文件,生成需要的列表
with open(nginx_log_dir, "r") as f:
url_list = []
log_time_list = []
requesttime_list = []
http_code_list = []
ip_list = []
for line in f:
if "HTTP" in line and "2023:" + query_time in line:
log_list = line.split()
url_list.append(line.split('"')[3].split()[1])
log_time_list.append(log_list[3].split('[')[1])
requesttime_list.append(float(log_list[9].split('"')[1]))
http_code_list.append(log_list[10])
ip_list.append(log_list[0])

time_tips("file over")

url_count = Counter(url_list)
log_time_count = Counter(log_time_list)
http_code_count = Counter(http_code_list)
ip_count = Counter(ip_list)

time_tips("uniq over")

# 列表去重统计,取前10个最大值
url_top10 = top_n_scores(10,url_count)
qps_top10 = top_n_scores(10,log_time_count)
http_code_top10 = top_n_scores(10,http_code_count)
ip_top10 = top_n_scores(10,ip_count)

time_tips("list sort over")

# 请求耗时平均值计算
url_req_avg = []
for i in url_top10:
num = 0.00
for index, value in enumerate(url_list):
if i[0] == value:
num += requesttime_list[index]
url_req_avg_tuple = (i[0],round(num/i[1],3))
url_req_avg.append(url_req_avg_tuple)

time_tips("url avg top10 over")

# 前10的url qps统计
url_qps_top10 = []
for i in url_top10:
time_list = []
for index, value in enumerate(url_list):
if i[0] == value:
time_list.append(log_time_list[index])
time_count = Counter(time_list)
time_count = top_n_scores(1,time_count)
time_tuple = (i[0],time_count[0][0],time_count[0][1])
url_qps_top10.append(time_tuple)

time_tips("url qps top10 over")

kwargs = {
"url_top10": url_top10,
"qps_top10": qps_top10,
"url_req_avg": url_req_avg,
"url_qps_top10": url_qps_top10,
"http_code_top10": http_code_top10,
"ip_top10": ip_top10
}

time_tips("over")

# 返回html页面
return render_template("index.html", **kwargs)

if __name__=="__main__":
app.run(port=8080,host="0.0.0.0")

index.html

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>welcome to 2023</title>
</head>

<body>
<div>
<h3>url 访问数统计 top10</h3>
<table border="1">
<tr><td>url</td><td>访问次数</td></tr>
{% for url_top10 in url_top10 %}
<tr><td>{{url_top10[0]}}</td><td>{{url_top10[1]}}</td></tr>
{% endfor %}
</table>

<h3>url 平均请求时间 top10</h3>
<table border="1"">
<tr><td>url</td><td>耗时</td></tr>
{% for url_req_avg in url_req_avg %}
<tr><td>{{url_req_avg[0]}}</td><td>{{url_req_avg[1]}}</td></tr>
{% endfor %}
</table>

<h3>url top10 的 qps</h3>
<table border="1"">
<tr><td>url</td><td>时间</td><td>请求次数</td></tr>
{% for url_qps_top10 in url_qps_top10 %}
<tr><td>{{url_qps_top10[0]}}</td><td>{{url_qps_top10[1]}}</td><td>{{url_qps_top10[2]}}</td></tr>
{% endfor %}
</table>

<div style="float:left; width:16%;">
<h3>qps 访问数统计 top10</h3>
<table border="1">
<tr><td>时间</td><td>请求次数</td></tr>
{% for qps_top10 in qps_top10 %}
<tr><td>{{qps_top10[0]}}</td><td>{{qps_top10[1]}}</td></tr>
{% endfor %}
</table>
</div>

<div style="float:left;width:11%;">
<h3>http code top10</h3>
<table border="1"">
<tr><td>http状态码</td><td>次数统计</td></tr>
{% for http_code_top10 in http_code_top10 %}
<tr><td>{{http_code_top10[0]}}</td><td>{{http_code_top10[1]}}</td></tr>
{% endfor %}
</table>
</div>

<div style="float:left">
<h3>ip top10</h3>
<table border="1"">
<tr><td>ip</td><td>次数统计</td></tr>
{% for ip_top10 in ip_top10 %}
<tr><td>{{ip_top10[0]}}</td><td>{{ip_top10[1]}}</td></tr>
{% endfor %}
</table>
</div>
</div>
</body>
</html>

k8s 部署脚本

用于远程调用脚本执行

k8s_install.sh

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
#!/bin/bash

init (){
# 初始化服务器
bash -c "$(curl -SsL https://域名或ip/ops/k8s-init.sh)"
}

master (){
bash -c "$(curl -SsL https://域名或ip/ops/kubeadm-init.sh)" @ $1 $2 $3
echo "export KUBECONFIG=/etc/kubernetes/admin.conf" >> ~/.bash_profile
source ~/.bash_profile
kubeadm init --config kubeadm-init.yaml
sysctl -p
}

get_flannel (){
[ -e /opt/cni/bin/flannel ] || wget -O /opt/cni/bin/flannel https://域名或ip/ops/flannel
chmod +x /opt/cni/bin/flannel
}

flannel (){
source .bash_profile
bash -c "$(curl -SsL https://域名或ip/ops/kube-flannel.sh)" @ $1
kubectl apply -f kube-flannel.yml
}

health (){
sed -i '/--port=0/d' /etc/kubernetes/manifests/kube-controller-manager.yaml
sed -i '/--port=0/d' /etc/kubernetes/manifests/kube-scheduler.yaml
systemctl restart kubelet
}

kuboard (){
source .bash_profile
bash -c "$(curl -SsL https://域名或ip/ops/kuboard.sh)"
bash -c "$(curl -SsL https://域名或ip/ops/metrics-server.sh)"
kubectl apply -f kuboard.yaml
kubectl apply -f metrics-server.yaml
# 获取token
echo $(kubectl -n kube-system get secret $(kubectl -n kube-system get secret | grep kuboard-user | awk '{print $1}') -o go-template='{{.data.token}}' | base64 -d)
}

completion (){
yum install -y bash-completion
source /usr/share/bash-completion/bash_completion
source <(kubectl completion bash)
echo "source <(kubectl completion bash)" >> ~/.bashrc
}

istio (){
source ~/.bash_profile
[ -e $PWD/istio-1.9.9-edit.tar.gz ] || wget https://域名或ip/ops/istio-1.9.9-edit.tar.gz
tar xf istio-1.9.9-edit.tar.gz
$PWD/istio-1.9.9/bin/istioctl install --set profile=demo --set values.global.hub=registry.cn-zhangjiakou.aliyuncs.com/moxi-k8s --set values.global.proxy.holdApplicationUntilProxyStarts=true --set values.global.imagePullPolicy=IfNotPresent -y
kubectl apply -f $PWD/istio-1.9.9/samples/addons/prometheus.yaml
kubectl apply -f $PWD/istio-1.9.9/samples/addons/kiali.yaml
sleep 2
kubectl apply -f $PWD/istio-1.9.9/samples/addons/kiali.yaml
kubectl -n istio-system patch service istio-ingressgateway -p '{"spec":{"type":"NodePort"}}'
}

conf_istio (){
source .bash_profile
bash -c "$(curl -SsL https://域名或ip/ops/gateway.sh)"
bash -c "$(curl -SsL https://域名或ip/ops/virtualservice.sh)"
bash -c "$(curl -SsL https://域名或ip/ops/gateway-gzip.sh)"
kubectl apply -f gateway.yaml
kubectl apply -f virtualservice.yaml
kubectl apply -f gateway-gzip.yaml
}

limit (){
source .bash_profile
# 限制容器资源
bash -c "$(curl -SsL https://域名或ip/ops/limit.sh)" @ $1
kubectl create ns $1
kubectl apply -f limit.yaml
}

zabbix (){
[ -e $PWD/zabbix-agent-5.0.17-1.el7.x86_64.rpm ] || wget https://域名或ip/ops/zabbix-agent-5.0.17-1.el7.x86_64.rpm
bash -c "$(curl -SsL https://域名或ip/ops/zabbix.sh)" @ $1

}

alertmanager (){
source .bash_profile
bash -c "$(curl -SsL https://域名或ip/ops/alertmanager.sh)"
kubectl apply -f alertmanager.yaml
}

cert (){
[ -d /scripts ] || mkdir /scripts
wget -O /scripts/cert.sh https://域名或ip/ops/cert.sh
echo "0 3 * * * /usr/bin/bash /scripts/cert.sh "$1" &> /dev/null" >> /var/spool/cron/root
}

del_log (){
[ -d /scripts ] || mkdir /scripts
wget -O /scripts/clear_logs.sh https://域名或ip/ops/clear_logs.sh
echo "0 4 * * * /bin/bash /scripts/clear_logs.sh" >> /var/spool/cron/root
}

conf_yum (){
curl -o /etc/yum.repos.d/CentOS-Base.repo https://repo.huaweicloud.com/repository/conf/CentOS-7-reg.repo
yum clean all && yum makecache
}

conf_docker (){
bash -c "$(curl -SsL https://域名或ip/ops/docker.sh)"
}

hostname (){
hostnamectl set-hostname $1
}

function menu(){
cat <<-EOF
===================== List ========================
1)init ECS
2)install master
3)install flannel
4)get flannel file
5)install istio prometheus kiali
6)cinfig istio: gateway,virtualservice,compression
7)completion
8)repair k8s cs
9)install kuboard
10)limit pod and create namespace
11)install zabbix
12)install alertmanager
13)crontab check ssl cert
14)crontab delete log
15)config yum resoruce
16)install docker
17)set hostname
==================================================
EOF
}

while true
do
menu
read -p "input number: " i
case $i in
"1")
init
;;
"2")
read -p "input api_ip(192.168.40.101:6443): " api_ip
read -p "input pod_ip(10.244.0.0/16): " pod_ip
read -p "input svc_ip(10.96.0.0/12): " svc_ip
api_ip=${api_ip:-"192.168.40.101:6443"}
pod_ip=${pod_ip:-"10.244.0.0/16"}
svc_ip=${svc_ip:-"10.96.0.0/12"}
master $api_ip $pod_ip $svc_ip
;;
"3")
read -p "input pod_ip(10.244.0.0/16): " pod_ip
pod_ip=${pod_ip:-"10.244.0.0/16"}
flannel $pod_ip
;;
"4")
get_flannel
;;
"5")
read -p "Please add a node or remove the master taint before executing,Press Enter to continue" tishi
istio
;;
"6")
conf_istio
;;
"7")
completion
;;
"8")
health
;;
"9")
kuboard
;;
"10")
read -p "input namespace: " namespace
limit $namespace
;;
"11")
read -p "input local ip(jushita-192.168.0.1): " local_ip
zabbix $local_ip
;;
"12")
alertmanager
;;
"13")
read -p "input project name(xmty): " project
cert $project
;;
"14")
del_log
;;
"15")
conf_yum
;;
"16")
conf_docker
;;
"17")
read -p "input host name(k8s-master): " name
hostname $name
;;
*)
echo "input error"
;;
esac
done

k8s-init.sh

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
#!/bin/bash

# docker版本,k8s版本
DockerV='-18.09.9'
K8sV='-1.19.9'

yum install -y yum-utils device-mapper-persistent-data lvm2 epel-release vim screen bash-completion mtr lrzsz wget telnet zip unzip sysstat ntpdate libcurl openssl bridge-utils nethogs dos2unix iptables-service net-tools

wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo -O /etc/yum.repos.d/docker-ce.repo
yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

wget http://mirrors.aliyun.com/repo/epel-7.repo -O /etc/yum.repos.d/epel.repo

cat >>/etc/yum.repos.d/kubernetes.repo <<EOF
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF

#安装K8S组件
yum install -y kubelet${K8sV} kubeadm${K8sV} kubectl${K8sV} docker-ce${DockerV}

systemctl enable kubelet

mkdir -p /etc/docker

tee /etc/docker/daemon.json <<-'EOF'
{
"registry-mirrors": ["https://cf-workers-docker-io-470.pages.dev"],
"exec-opts": ["native.cgroupdriver=systemd"],
"log-opts": {
"max-size": "100m",
"max-file": "10"
}
}
EOF

systemctl restart docker && systemctl enable docker

#禁用防火墙与selinux

setenforce 0
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
sed -i 's/SELINUX=permissive/SELINUX=disabled/g' /etc/selinux/config

service firewalld stop
systemctl disable firewalld.service
service iptables stop
systemctl disable iptables.service

service postfix stop
systemctl disable postfix.service

wget http://mirrors.aliyun.com/repo/epel-7.repo -O /etc/yum.repos.d/epel.repo

echo '/etc/security/limits.conf 参数调优,需重启系统后生效'

cp -rf /etc/security/limits.conf /etc/security/limits.conf.back

cat > /etc/security/limits.conf << EOF
* soft nofile 655350
* hard nofile 655350
* soft nproc unlimited
* hard nproc unlimited
* soft core unlimited
* hard core unlimited
root soft nofile 655350
root hard nofile 655350
root soft nproc unlimited
root hard nproc unlimited
root soft core unlimited
root hard core unlimited
EOF

echo '/etc/sysctl.conf 文件调优'

cp -rf /etc/sysctl.conf /etc/sysctl.conf.back
cat > /etc/sysctl.conf << EOF

vm.swappiness = 0
net.ipv4.neigh.default.gc_stale_time = 120

# see details in https://help.aliyun.com/knowledge_detail/39428.html
net.ipv4.conf.all.rp_filter = 0
net.ipv4.conf.default.rp_filter = 0
net.ipv4.conf.default.arp_announce = 2
net.ipv4.conf.lo.arp_announce = 2
net.ipv4.conf.all.arp_announce = 2

# see details in https://help.aliyun.com/knowledge_detail/41334.html
net.ipv4.tcp_max_tw_buckets = 20000
net.ipv4.tcp_tw_recycle = 0
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 1024
net.ipv4.tcp_synack_retries = 2

net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1

kernel.sysrq = 1
kernel.pid_max=1000000

net.netfilter.nf_conntrack_max=2048576
net.netfilter.nf_conntrack_tcp_timeout_established=3600
EOF

echo "ipvs模块开启"
cat > /etc/sysconfig/modules/ipvs.modules <<EOF
#!/bin/bash
modprobe -- ip_vs
modprobe -- ip_vs_rr
modprobe -- ip_vs_wrr
modprobe -- ip_vs_sh
modprobe -- nf_conntrack_ipv4
EOF

echo "1">/proc/sys/net/bridge/bridge-nf-call-iptables

chmod 755 /etc/sysconfig/modules/ipvs.modules
bash /etc/sysconfig/modules/ipvs.modules

lsmod | grep -e ip_vs -e nf_conntrack_ipv4

echo "禁用swap"
swapoff -a
sed -i '/swap/d' /etc/fstab

sysctl -p

echo "init success"

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!