1. 程式人生 > >Python開發遊戲開服腳本

Python開發遊戲開服腳本

second min already 文件 r+ alt tor ole watermark

#!/usr/bin/env python #coding:utf-8 from pymongo import MongoClient import datetime import random import shutil import time import sys import re import os class readyTostart(object): def Countdown(self): print(‘‘‘ ###################################### # 拜見包大人一健開服腳本 # ###################################### ‘‘‘) print(‘ \033[1;31;40m腳本即將開始執行...\033[0m‘) time.sleep(2) print for i in range(3,0,-1): time.sleep(1) print(‘ 腳本還有\033[5;31;40m%s\033[0m秒開始執行,請稍等...‘ % i) print def ParametersCheck(self): global openNum,openYear,openMonth,openDay try: openNum = sys.argv[1] if not re.match(‘^[0-9]+$‘, openNum): if not re.match(‘(^[0-9]+)-([0-9]+$)‘, openNum): print(‘Please output in the specified format. Example num1-num2,Does not support decimals‘) sys.exit(1) else: parmet1 = re.match(‘(^[0-9]+)-([0-9]+$)‘, openNum) if int(parmet1.group(1)) > int(parmet1.group(2)): print(‘The first opening number %s cannot be greater than the second opening number %s‘ % (parmet1.group(1),parmet1.group(2))) sys.exit(1) if re.match(‘^[0]‘, openNum): print(‘You cannot enter numbers starting with 0‘) sys.exit(1) except Exception as e: print e values = sys.argv[0] print(‘Please enter at least one parameter‘) Exaples = ‘Exaples: python {key} 10 | python {key} 1-10‘ print(Exaples.format(key=values)) sys.exit(1) nowDate = datetime.datetime.now() + datetime.timedelta(days=1) openYear = nowDate.strftime("%Y") try: cusDate = sys.argv[2] except Exception as e: cusDate = nowDate openMonth = cusDate.strftime("%m") openDay = cusDate.strftime("%d") if re.match(‘0\d‘, openMonth): openMonth = openMonth[1:] if re.match(‘0\d‘, openDay): openDay = openDay[1:] else: if not re.match(‘^[0-9]+\.[0-9]+‘,cusDate): print ‘The second parameter format is => month.day‘ sys.exit(1) openMonth = cusDate.split(‘.‘)[0] openDay = cusDate.split(‘.‘)[1] if int(openMonth) < 1 or int(openMonth) > 12: print ‘The month you entered cannot be greater than twelve and less than one‘ sys.exit(1) if int(openDay) < 1 or int(openDay) > 31: print("You can‘t enter more than 31 or less than 1") sys.exit(1) openMonth = ‘=‘ + openMonth openDay = ‘=‘ + openDay class deployService(object): def __init__(self): self.toolsdirctory = ‘/data/tools/new_server/‘ self.servicedir = ‘/data/bz-tw-and/s‘ self.codedir = ‘/data/bz-tw-and‘ self.logdir = ‘/data/logs/s‘ self.userInputSpecified = [] self.userInputall = [] self.alreadyExist = [] def startDeploy(self): global inputNum,newService if not os.path.exists(self.codedir): print(‘%s not exists,script exit‘ % self.codedir) sys.exit(0) if not os.path.exists(self.toolsdirctory + ‘Config.lua‘) or not os.path.exists(self.toolsdirctory + ‘bin‘): print(‘(%s and %s)file or dirctory not exists,script exit‘ % (self.toolsdirctory + ‘Config.lua‘, self.toolsdirctory + ‘bin‘)) sys.exit(1) inputNum = re.match(‘(\d+)-(\d+)‘, openNum) inputOnenum = re.match(‘(^[1-9][0-9]*$)‘, openNum) if inputOnenum: num = 1 for i in os.listdir(self.codedir): nowService = re.match(‘(s)(\d+)‘,i) if nowService: num += 1 nowNum = i[1:] if openNum == nowNum: print(‘ %s Service already existsService already exists‘ % openNum) sys.exit() newNum = str(num) + ‘-‘ + openNum inputNum = re.match(‘(\d+)-(\d+)‘, newNum) if inputNum: oneNum = int(inputNum.group(1)) towNum = int(inputNum.group(2)) for fuNum in range(1,towNum+1): self.userInputall.append(fuNum) for fuNum in range(oneNum,towNum+1): self.userInputSpecified.append(fuNum) for i in os.listdir(self.codedir): nowService = re.match(‘(s)(\d+)‘,i) if nowService: nowNum = i[1:] self.alreadyExist.append(int(nowNum)) differenceSet=(set(self.userInputall)^set(self.alreadyExist)) intersection=(set(self.userInputSpecified)&set(self.alreadyExist)) newService=list(differenceSet) oldService=list(intersection) if newService != []: for i in newService: gameService = self.servicedir + str(i) os.mkdir(gameService) shutil.copytree(self.toolsdirctory + ‘bin‘, gameService + ‘/bin‘) shutil.copytree(self.servicedir + str(1) + ‘/scripts‘, self.servicedir + str(i) + ‘/scripts‘) shutil.copyfile(self.toolsdirctory + ‘Config.lua‘,gameService +‘/Config.lua‘) if not os.path.exists(self.logdir +str(i)): os.mkdir(self.logdir +str(i)) os.symlink(self.logdir+str(i),self.servicedir + str(i) + ‘/bin/logs‘) if not os.path.exists(self.toolsdirctory + ‘/bin/bz-tw-and-s_‘): print(‘%s not exists,Please Check‘ % (self.toolsdirctory + ‘/bin/bz-tw-and-s_‘)) shutil.move(self.servicedir + str(i) + ‘/bin/bz-tw-and-s_‘,self.servicedir + str(i) + ‘/bin/bz-tw-and-s‘ + str(i)) scriptList = [‘hotup.sh‘,‘hotup_client.sh‘,‘start.sh‘,‘stop.sh‘] for scriptName in scriptList: if not os.path.exists(self.servicedir+str(i) + ‘/bin/‘ + scriptName): print(‘%s not exists,Please Check‘ % scriptName) hotupLine = ‘‘ hotupPort = 10000 + int(i) for scriptName in [‘hotup.sh‘,‘hotup_client.sh‘]: with open(self.servicedir + str(i) + ‘/bin/‘ + scriptName, ‘r‘)as f: for line in f.readlines(): if line.find(‘10000‘): line = re.sub(‘10000‘, str(hotupPort), line) hotupLine += line else: hotupLine += line with open(self.servicedir + str(i) + ‘/bin/‘ + scriptName, ‘w‘)as f: f.write(hotupLine) start_stop_Line = ‘‘ for scriptName in [‘start.sh‘,‘stop.sh‘]: with open(self.servicedir + str(i) + ‘/bin/‘ + scriptName, ‘r‘)as f: for line in f.readlines(): if line.find(‘1‘): line = re.sub(‘1‘, str(i), line) start_stop_Line += line else: start_stop_Line += line with open(self.servicedir + str(i) + ‘/bin/‘ + scriptName, ‘w‘)as f: f.write(start_stop_Line) if oldService != []: for i in oldService:print(‘ already kai fu %s‘ % i) else: print(‘Exaples: python %s 10 | python %s 1-10‘ % (sys.argv[0],sys.argv[0])) class MongoDabase(object): def __init__(self,serverIp=‘192.168.6.184‘,databasePort=27017,user=‘root‘,password=‘123456‘,adminDatabase=‘admin‘): self.client = MongoClient(serverIp,databasePort) self.db = self.client[adminDatabase] self.db.authenticate(user,password) def createPassword(self): password = ‘‘ for i in range(8): current = random.randrange(0,8) if current > i: temp = random.randint(0,9) elif current < i: temp = chr(random.randint(65,90)) else: temp = chr(random.randint(97,122)) password += str(temp) return password def createUser(self): global passwordList passwordList = {} deploy = deployService() configfileLine = ‘‘ passwordPath = ‘/data/script/‘ if not os.path.exists(passwordPath): os.mkdir(passwordPath) print(‘ \033[1;31;40m部署情況如下\033[0m‘) print if newService != []: for i in newService: clientPort = 20000 + int(i) httpPort = 10000 + int(i) dbName = ‘s‘ + str(i) SvrId = str(i) gameServiceName = ‘bz-tw-and-s‘ + str(i) password = self.createPassword() passwordList.update({i:password}) dbUser = self.client[gameServiceName] dbUser.command("createUser", "bz", pwd=password, roles=["readWrite"]) old = [‘20003‘,‘10003‘,‘s3‘,‘zxjRYZGI‘,‘sid‘,‘2018‘,‘=5‘,‘=19‘] new = [clientPort,httpPort,dbName,password,SvrId,openYear,openMonth,openDay] for old,new in zip(old,new): with open(deploy.servicedir + str(i) + ‘/Config.lua‘,‘r‘)as f: for line in f.readlines(): if line.find(str(old)): line = re.sub(str(old),str(new),line) configfileLine += line else: configfileLine += line with open(deploy.servicedir + str(i) + ‘/Config.lua‘, ‘w‘)as f: f.write(configfileLine) configfileLine = ‘‘ with open(passwordPath+‘mongo_pass.txt‘,‘a+‘)as f: mongoDbname = ‘bz-tw-and-‘ + str(i) f.write(mongoDbname+‘=‘+password+‘\n‘) os.remove(deploy.servicedir + str(i)+‘/scripts/Config.lua‘) shutil.copyfile(deploy.servicedir + str(i) + ‘/Config.lua‘,deploy.servicedir + str(i)+‘/scripts/Config.lua‘) print(‘ \033[31m%s\033[0m 服已經部署完成...‘ % i) print print(‘ \033[1;31;40m數據庫密碼文件存放位置如下\033[0m‘) print print(‘ /data/script/mongo_pass.txt‘) class configCheck(object): def luaConfigcheck(self): deploy = deployService() Month = openMonth[1:] Day = openDay[1:] if newService != []: for i in newService: print (‘‘‘ ############################################ # %s服配置文件檢查 # ############################################ ‘‘‘ % i) data = [‘(GAME_IO_LISTEN_PORT = )(\d+)‘, ‘(GAME_HTTP_LISTEN_PORT=)(\d+)‘, ‘(DBNAME="bz-tw-and-)(.*)(")‘, ‘(DBPWD=")(.*)(")‘, ‘(SvrId = )(.*)‘, ‘(activityStartDate={year=)(\d{4})(,month=)(\d+)(,day=)(\d+)(.*)‘] with open(deploy.servicedir + str(i) + ‘/scripts/Config.lua‘, ‘r‘)as f: for line in f.readlines(): for d in data: if re.match(d, line): m = re.match(d, line) try: if int(m.group(2)) == 10000 + int(i) or int(m.group(2)) == 20000 + int(i) or int(m.group(2)) == int(i): if int(m.group(2)) == int(i): result = ‘ [\033[32mID正確\033[0m]‘ else: result = ‘[\033[32m端口正確\033[0m]‘ else: result = ‘ [\033[5;31m配置錯誤\033[0m]‘ if int(m.group(2)) == int(openYear) and int(m.group(4)) == int(Month) and int(m.group(6)) == int(Day): yresult = ‘[\033[32m年月日正確\033[0m]‘ else: yresult = ‘ [\033[5;31m年或月或日錯誤\033[0m]‘ except Exception as e: if str(m.group(2)) == str(‘s‘+str(i)) or str(m.group(2)) == str(passwordList[i]): if str(m.group(2)) == str(passwordList[i]): result = ‘ [\033[32m密碼正確\033[0m]‘ else: result = ‘[\033[32m名字正確\033[0m]‘ else: result = ‘ [\033[5;31m配置錯誤\033[0m]‘ try: print(‘ %s\033[31m%s\033[0m%s\033[31m%s\033[0m%s\033[31m%s\033[0m%s%s‘ % (m.group(1), m.group(2), m.group(3), m.group(4), m.group(5), m.group(6),m.group(7), yresult)) except Exception as e: try: print(‘ %s\033[31m%s\033[0m%s %s‘ % (m.group(1), m.group(2), m.group(3), result)) except Exception as e: print(‘ %s\033[31m%s\033[0m %s‘ % (m.group(1), m.group(2), result)) if __name__ == ‘__main__‘: start = readyTostart() start.ParametersCheck() start.Countdown() deploy = deployService() deploy.startDeploy() db = MongoDabase() db.createUser() check = configCheck() check.luaConfigcheck()

執行結果展示
技術分享圖片

Python開發遊戲開服腳本