import easygui as g
import sys
import datetime
import uuid
import socket
import psycopg2
import uuid
nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')#现在
values = []
#执行人和执行需求的窗口
def per_message():
fields = ['*用户名', '*需求单号']
msg = '填写下面信息(*为必填项)'
title = '执行人信息'
fieldvalue = g.multenterbox(msg, title, fields)
while True:
if fieldvalue == None:
break
errmsg = ''
for item in range(len(fields)):
option = fields[item].strip()
if fieldvalue[item].strip() == "" and option[0] == "*":
errmsg += ('[%s]为必填项。\n\n' % fields[item])
if errmsg == '':
break
fieldvalue = g.multenterbox(errmsg, title, fields, fieldvalue)
if fieldvalue == None:
return 'cancel'
else:
per_name = fieldvalue[0]
per_request = fieldvalue[1]
values.append(per_name)
values.append(per_request)
return 'ok'
#执行脚本的窗口
def runscript():
msg = '把要执行的sql脚本写在下面'
title = '执行脚本!'
text = ''
script = g.codebox(msg, title, text)
while script == None or script == '\n' or script == '':
g.msgbox('没有任何脚本写入!请写入脚本!!!')
script = g.codebox(msg, title, text)
values.append(script)
#获取mac地址
def get_mac_address():
mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
mac_adr = ":".join([mac[e:e+2] for e in range(0,11,2)])
values.append(mac_adr)
#获取ip和计算机名称
def get_ipadrr():
#获取本机电脑名
computer_name = socket.getfqdn(socket.gethostname( ))
#获取本机ip
ip_addr = socket.gethostbyname(computer_name)
values.append(computer_name)
values.append(ip_addr)
#写入txt文件
def writeintext(writein):
# 将脚本存放起来
writeintxt = open('account.txt', 'a+',encoding="utf-8")
writeintxt.write(writein + '/' + nowTime + '\n')
writeintxt.close()
class GPCommand(object):
# 类的初始化
def __init__(self):
self.hostname = '10.1.2.xxx'
self.username = 'appxxx'
self.password = 'xxxx'
self.database = 'gsdw'
def connectGp(self):
try:
#链接数据库
#读取配置利用connect链接数据库
self.connect = psycopg2.connect( host=self.hostname, user=self.username, password=self.password, dbname=self.database )
#创建一个新的cursor
self.cursor = self.connect.cursor()
print("connect gp successful")
except:
print('connect gp error.')
def insertData(self,my_dict):
try:
id = my_dict['id']
per_name = my_dict['per_name']
per_request = my_dict['per_request']
script = ''
script_tmp = my_dict['script']
if "'" in script_tmp:
nops = []
new_loop = []
itemplist = list(script_tmp)
for i in range(len(itemplist)):
if itemplist[i] == "'":
nops.append(i)
for item in nops:
new_loop.append(item + nops.index(item))
for i in new_loop:
itemplist.insert(i, "'")
script = "".join(itemplist)
else:
script = script_tmp
mac_adr = my_dict['mac_adr']
computer_name = my_dict['computer_name']
ip_addr = my_dict['ip_addr']
insertsql = "INSERT INTO dw_edw.edw_pub_log_database_change (id,per_name,per_request,script,mac_adr,computer_name,ip_addr,load_dt) values('%s','%s','%s','%s','%s','%s','%s',now()) " % (id,per_name,per_request,script,mac_adr,computer_name,ip_addr)
self.cursor.execute(insertsql)
self.connect.commit()
return 'insert_success'
except psycopg2.Error:
error = 'Failed to setup Postgres environment.\n{0}'.format(sys.exc_info())
return 'insert_failed' + error
def execscript(self,my_dict):
id = my_dict['id']
execscript = my_dict['script']
try:
self.cursor.execute(execscript)
self.connect.commit()
#更新执行结果
updatesql = "update dw_edw.edw_pub_log_database_change set result = 'Y' where id = '%s' " %(id)
self.cursor.execute(updatesql)
self.connect.commit()
print('执行成功')
return 'exec_success'
except psycopg2.Error:
error = 'Failed to setup Postgres environment.\n{0}'.format(sys.exc_info())
print('执行失败')
return 'exec_failed' + error
#raise SystemExit(
#print(error)
#)
#关闭数据库
def closeMysql(self):
self.cursor.close()
self.connect.close()
print("数据库已关闭")
def main():
gpCommand = GPCommand()
gpCommand.connectGp()
per_result = per_message()
if per_result == 'cancel':
sys.exit(0)
else:
runscript()
get_mac_address()
get_ipadrr()
# # #写入txt文件
# # for item in values:
# # writeintext(item)
new_dict = {
"id" : uuid.uuid1(),
"per_name": values[0],
"per_request": values[1],
"script": values[2],
"mac_adr": values[3],
"computer_name": values[4],
"ip_addr": values[5],
}
insert_result = gpCommand.insertData(new_dict)
if insert_result == 'insert_success':
#g.msgbox(msg='记录已插入成功,正在执行脚本……',title='请确认')
exec_result = gpCommand.execscript(new_dict)
if exec_result == 'exec_success':
g.msgbox(msg='执行成功',title='请确认')
else:
g.msgbox(msg='执行失败,请在测试环境测试后再执行'+ '\n'+ exec_result ,title='请确认')
else:
g.msgbox(msg='插入失败' + '\n' + insert_result)
# 最后一定要要把数据关闭
gpCommand.closeMysql()
main()`这里写代码片`