验证中...
本周日【珠海源创会】一起聊聊:PingCAP分布式事务、支付宝移动端实践、GSBN技术框架选型,点此报名占座
语言: Python
分类: 其他
最后更新于 2018-11-14 15:40
gistfile1.txt
原始数据 复制代码
# 更新镜像之前选择已有devops的服务器
# service一定要准确,否则会牵扯到其他服务更新
#
from requests.exceptions import ConnectionError
from json.decoder import JSONDecodeError
from configparser import NoOptionError
from paramiko import ssh_exception
from openpyxl import load_workbook
from openpyxl import Workbook
from socket import gaierror
import requests,json
import configparser
import paramiko
import time
import re
#服务名字
service = '2-19-police-biz.biz'
# service = '0-225-video-biz.biz-biz'
#==================================================================================================
Time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
wb = load_workbook(r'C:\Users\DGQ\Desktop\环境表格sng-qa.xlsx')
sheet = wb.sheetnames
sheet = wb[(sheet[0])] # 获取第一表单
result=[]
for i in range(sheet.max_column):#读取每条数据
result.append(sheet.cell(row=1,column=i+1).value)
print('\33[0;33;34m=\33[0m' * 85)
# 获取数据并且返回数据
while True:
Target = input('Please enter the IP:')
for i in range(sheet.max_row - 1):
dict = {}
for j in range(len(result)):#读取账户密码
dict[result[j]] = sheet.cell(row=i + 2, column=j + 1).value
if '/' in str(dict['账户密码']):
A = dict['账户密码'].split('/')
else:
pass
#判断数据的数据是否在表内IP中
if Target in str(dict['IP']):
# print('\33[0;33;34m ==============================================================\33[0m')
# print(' etc/hosts信息如下:')
try:
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(hostname=dict['IP'], username=A[0], password=A[1])
stdin, stdout, stderr = s.exec_command('cat /etc/hosts')
p = str(stdout.read())
s.close()
list = p.strip("b'").split('\\n')
#循环判断哪一条数据中含有devops信息
for i in list:
if 'devops-grafana devops-prometheus devops-manager' in i :
devops_IP = i
continue
print('\33[0;33;34m ==============================================================\33[0m')
print('________节点登录IP:%s 用户名:%s 密码:%s _________\n' % (dict['IP'],A[0], A[1]))
print(' devops账号,密码如下:')
print('\33[0;33;34m=\33[0m'*85)
#Python连接服务器操作
devops_data = paramiko.SSHClient()
devops_data.set_missing_host_key_policy(paramiko.AutoAddPolicy())
devops_data.connect(hostname=dict['IP'], username=A[0], password=A[1])
#执行Linux命令
stdin, stdout, stderr = devops_data.exec_command('sudo devops-manager -superuser')
# stdin, stdout, stderr = devops_data.exec_command('ll')
x = str(stdout.read())
devops_data.close()
# print(x)
list2 = x.strip("b'").split('\\n')
print('\33[0;33;34m ===== %s 节点的devops地址为 %s:5432 =====\33[0m' % (dict['IP'],devops_IP.split()[0]))
print('\33[0;33;34m ===== 当前devops超级账户以及密码 =====\33[0m')
user_list = []
#账户以及密码
for i in list2:
print(i)
user_list.append(i.split(':'))
if ('username' not in list2[0]) or ('password' not in list2[1]):
print('\33[0;33;34m =====此 %s 站点自身没有建设devops=====\33[0m'%dict['IP'])
url = dict['IP']
user = user_list[0][1].strip(' ')
pw = user_list[1][1].strip(' ')
# 登录部分
login_API = 'http://' + url + ':5432/api/v1/user/login'
# 登录密码
login_data = {'username': user, 'password': pw}
# 进行登录
value = requests.post(url=login_API, data=login_data)
#devops登陆状态
if str(value.status_code) == '403':
print('\33[0;33;34m ==========================\33[0m')
print('\33[0;33;34m ==== 登录状态:%s ====\33[0m' % value.status_code)
print('\33[0;33;34m =======需要更新登录密码=====\33[0m')
print('\33[0;33;34m ==========================\33[0m')
else:
print('\33[0;33;34m ==========================\33[0m')
print('\33[0;33;34m ==== 登录状态:%s ====\33[0m' % value.status_code)
print('\33[0;33;34m =======自己看状态! ! !=====\33[0m')
print('\33[0;33;34m ==========================\33[0m')
login_Cookie = value.cookies
url3 = 'http://' + url + ':5432/api/v1/instance/'
n = requests.get(url3)
m = n.json()
Time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
# =================================
# 可以获取到以下信息
# ---服务---
# ---镜像---
# =================================
# 写数据
Time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
try:
acquire_API = 'http://'+url+':5432/api/v1/instance'
# 请求
acquire_values = requests.get(acquire_API).json()
服务 = []
镜像 = []
for i in acquire_values:
J = (i['name'])
if service in J: # 只抓取2-38站点的信息,可配置信息
A = J.split('.')[1] + '.' + J.split('.')[2]
B = i['container_config']['image']
if 'infra' in A or 'exporters' in A:
pass
else:
服务.append(A)
镜像.append(B)
# print(A, '---', B)
old_image = 'ampregistry:' + B.rsplit(':')[-2] + ':'
url = 'http://10.201.102.123:5000/v2/%s/tags/list?'% B.rsplit(':')[-2].strip('5000/')
# print(url)
#开发仓库
result = requests.get(url).json()
try:
result_tags = result['tags']
image_time_list = []
for image_time in result_tags:
if 'dev' in image_time and 'toqa' in image_time:
value = re.compile('[0-9]{8,12}') # 判断新加入的时间戳位数以及是否是数字
result3 = value.findall(image_time)
for KF_time in result3:
Time_8=KF_time[:8]#取了所有时间戳前八位
image_time_list.append(KF_time)
elif 'dev' not in image_time or 'toqa' not in image_time:
pass
new_image_time = max(image_time_list)
# print(new_image_time)#最新可用时间戳
print('=========================')
print(result['name'])
for N_image in result_tags:
# #如果符合标准的镜像在列表里
if new_image_time in N_image :
image = 'ampregistry:5000/%s:%s' % (result['name'], N_image)
wb = Workbook()
wb = load_workbook(r'E:\旷世文件\4_D_KS_Conf\测试.xlsx')
sheet = wb.sheetnames
sheet = wb[(sheet[0])] # 获取第一表单
n = requests.get(url3)
m = n.json()
Time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
# 只要此站点内有相关镜像,都会更新
print('\33[0;31;23m=\33[0m' * 50)
New_I = image # 新镜像
# list = []
#旧版返回信息
for i in m:
OLDN_image = i['container_config']['image']
old_image = 'ampregistry:' + OLDN_image.rsplit(':')[-2] + ':'
# print(OLDN_image,'老老老老')
# break
old_time = OLDN_image.rsplit('.')[-1].rsplit('-')[0]
老版实例名 = ((i['container_config']['image']).split('/')[1]).split(':')[0]
old_suffix = OLDN_image.rsplit('.')[-1].rsplit('-')[-1]
# list.append(old_image)
new_image = 'ampregistry:' + New_I.rsplit(':')[-2] + ':'
new_time = New_I.rsplit('.')[-1].rsplit('-')[0]
new_suffix = New_I.rsplit('.')[-1].rsplit('-')[-1]
# print(new_image,new_image_time,new_suffix)
if new_suffix == old_suffix and 老版实例名 in new_image and new_time > old_time and len(old_time) == len(new_time):
# ========开始更新镜像========##
# ========开始更新镜像========##
# ========开始更新镜像========##
url = url3+i['name']
i['container_config']['image'] = New_I#赋值最新镜像
# print(i['container_config']['image'])
# r3 = requests.put(url, json=i, cookies=login_Cookie)
# ========开始更新镜像========##
# ========开始更新镜像========##
# ========开始更新镜像========##
server = i['name'].split('.')[1] + '.' + i['name'].split('.')[2]
print(
'\33[0;33;34m ==========================\33[0m')
print(
'\33[0;33;34m ==========更新成功=========\33[0m')
print(
'\33[0;33;34m ==========================\33[0m')
print('老镜像:%s' % B)
print('新镜像:%s' % New_I)
print('\33[0;31;23m=\33[0m' * 100)
print('\n')
# 写头部
header = ['服务', '原始数据', '新版数据', '更换时间'] # 首行头部信息作为变量可更改
for i in range(len(header)):
sheet.cell(row=1, column=i + 1).value = header[i]
try:
path = r'E:\旷世文件\4_D_KS_Conf\测试.xlsx' # 保存路径,变更机器时注意替换
sheet1 = wb.sheetnames
sheet1 = wb[(sheet1[0])] # 获取第一表单
cont = sheet1.max_row
cont += 1
sheet1['A%d' % cont] = server
sheet1['B%d' % cont] = OLDN_image
sheet1['C%d' % cont] = New_I
sheet1['D%d' % cont] = Time
wb.save(r'E:\旷世文件\4_D_KS_Conf\测试.xlsx')
except PermissionError:
print(
'\33[0;33;34===============================================================================\33[0m')
print(
'\33[0;33;34m=========把你打开的Excel关掉再玩!!!!本王把报错给你隐藏了,按照提示做就对了=========\33[0m')
print(
'\33[0;33;34m==============================================================================\33[0m')
except DeprecationWarning:
print('...')
elif new_suffix == old_suffix and 老版实例名 in N_image and new_time < old_time and len(
old_time) == len(new_time):
print(
'\33[0;33;34m =====================================================\33[0m')
print(
'\33[0;33;34m ==========当前镜像无需变更,新镜像时间早于旧版镜像========\33[0m')
print(
'\33[0;33;34m =====================================================\33[0m')
print('老镜像:%s' % B)
print('新镜像:%s' % New_I)
print('\33[0;31;23m=\33[0m' * 100)
print('\n')
pass
elif new_suffix == old_suffix and 老版实例名 in N_image and new_time == old_time and len(
old_time) == len(new_time):
print(
'\33[0;33;34m =========================================\33[0m')
print(
'\33[0;33;34m ==========当前镜像无需变更,数据一致========\33[0m')
print(
'\33[0;33;34m =========================================\33[0m')
print('老镜像:%s' % B)
print('新镜像:%s' % New_I)
print('\33[0;31;23m=\33[0m' * 100)
print('\n')
pass
elif new_suffix == old_suffix and 老版实例名 in N_image and len(
new_time) != len(old_time):
print(
'\33[0;33;34m =========================================\33[0m')
print(
'\33[0;33;34m ==========镜像中的时间戳长度不一致==========\33[0m')
print(
'\33[0;33;34m =========================================\33[0m')
print('老镜像:%s' % B)
print('新镜像:%s' % New_I)
print('\33[0;31;23m=\33[0m' * 100)
print('\n')
pass
elif 老版实例名 not in N_image:
pass
elif new_suffix != old_suffix:
print(
'\33[0;33;34m ============================\33[0m')
print(
'\33[0;33;34m ==========后缀不一致=========\33[0m')
print(
'\33[0;33;34m ============================\33[0m')
print('老镜像:%s' % B)
print('新镜像:%s' % New_I)
print('\33[0;31;23m=\33[0m' * 100)
print('\n')
elif new_image_time not in N_image:
continue
# print('没有当前时间')
# 获取所有捕获到的错误
except ValueError as p:
# print('\33[0;31;23m=\33[0m' * 100)
print(old_image,'此镜像跳过_____ 报错信息:%s'%p)
print(url)
# print('\33[0;31;23m=\33[0m' * 100)
except KeyError as a:
print('此镜像无法更换,请手动替换:', result['errors'][0]['detail']['name'])
finally:
pass
except JSONDecodeError as a:
print(a, '终于抓到你了,可能是配置信息有误哦,请使用放大镜检查!')
except ConnectionError as b:
print(b, '检查IP地址是否正确')
except configparser.NoOptionError as c:
print(c, '检查标签')
except configparser.ParsingError as d:
print(d, '检查选项')
except paramiko.ssh_exception.AuthenticationException as e:
print('\33[0;33;34m认证失败,检查服务器地址是否正确,账户密码是否正确. %s\33[0m'%e)
except gaierror as o:
print('该账号%s单元格内含有汉字等非法字符'%dict['IP'],o)
break
# 你体会过曾经认定了一辈子的那个人,现在却形同陌路的感受吗?
#
# 我们都曾经为了努力和一个人在一起,牺牲过很多的原则和事物,但爱情往往比我们想象中要脆弱得多,无论喜欢的时候两人有多亲密。几年的感情,一句分手就结束了。
#
# 我想没有一个人喜欢说再见,每段感情的开始,也不是为了某一天可以笑着说离开。
#
# 现在,只剩下过去那些美好的回忆,舍不得放手,也不甘心就此失去。
#
# 回不到过去是真的,但请相信,曾想和你过完余生也是真的。

评论列表( 0 )

你可以在登录后,发表评论

搜索帮助

12_float_left_people 12_float_left_close