成都创新互联网站制作重庆分公司

Python开发游戏开服脚本

#!/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,scriptList
        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:]
                   if int(nowNum) < towNum:
                       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)
            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_'))
                    try:
                        shutil.move(self.servicedir + str(i) + '/bin/bz-tw-and-s_',self.servicedir + str(i) + '/bin/bz-tw-and-s' + str(i))
                    except Exception as e:
                        print e
                        print('%s服修改bz-tw-and-s_命名失败' % 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)
                            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)
                            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]
                try:
                    dbUser.command("createUser", "bz", pwd=password, roles=["readWrite"])
                except Exception as e:
                    print('''         %s

                请测试账户密码验证是否正确
                    '''% e)
                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:]
        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+)(.*)']
        if newService != []:
            for i in newService:
                print ('''
       ############################################
       #             %s服配置文件检查             #
       ############################################
                            ''' % i)
                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:
                                    time.sleep(0.5)
                                    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:
                                        time.sleep(0.5)
                                        print('         %s\033[31m%s\033[0m%s        %s' % (m.group(1), m.group(2), m.group(3), result))
                                    except Exception as e:
                                        time.sleep(0.5)
                                        print('         %s\033[31m%s\033[0m   %s' % (m.group(1), m.group(2), result))

    def scriptCheck(self):
        deploy = deployService()
        hotup = '(.*:)(\d{5})(/.*)'
        startstop = '(.*)(s)(\d+)(")'
        if newService != []:
            for i in newService:
                print ('''
        ############### %s服脚本检查 ###############
                             ''' % i)
                for script_name in scriptList:
                    with open( deploy.servicedir + str(i) + '/bin/'+ script_name, 'r')as f:
                        for line in f.readlines():
                            if re.match(hotup,line):
                                m = re.match(hotup,line)
                                if int(m.group(2)) == (10000 + int(i)):
                                    time.sleep(0.5)
                                    result='端口正确'
                                    print('         %s\033[31m%s\033[0m%s [\033[32m%s\033[0m]' % (m.group(1),m.group(2),m.group(3),result))
                                else:
                                    time.sleep(0.5)
                                    result = '端口错误'
                                    print('          %s\033[31m%s\033[0m%s [\033[5;31m%s\033[0m]' % (m.group(1), m.group(2), m.group(3), result))
                            if re.match(startstop,line):
                                m = re.match(startstop, line)
                                if int(m.group(3)) == (int(i)):
                                    time.sleep(0.5)
                                    result = '开关脚本服数正确'
                                    print('         %s%s\033[31m%s\033[0m%s [\033[32m%s\033[0m]' % (m.group(1), m.group(2), m.group(3), m.group(4), result))
                                else:
                                    time.sleep(0.5)
                                    result = '开关脚本服数正确'
                                    print('         %s\033[31m%s\033[0m%s [\033[5;31m%s\033[0m]' % (m.group(1), m.group(2), m.group(3), m.group(4), result))
        for i in newService:
            for file_name in os.listdir(deploy.servicedir + str(i) + '/bin/'):
                if re.match('(.*s)(\d+)',file_name):
                    m = re.match('(.*s)(\d+)',file_name)
                    if m.group(2) == str(i):
                        result = '服数正确'
                        time.sleep(1)
                        print
                        print("        ########## %s服二进制文件命名检查 ##########" % i)
                        print("         %s\033[31m%s\033[0m [\033[32m%s\033[0m]" % (m.group(1),m.group(2),result))
                    else:
                        time.sleep(1)
                        result = '服数错误'
                        print("         %s\033[31m%s\033[0m [\033[5;31m%s\033[0m]" % (m.group(1), m.group(2), result))

        for i in newService:
            print ('''
        ############### %s软链接人工检查 ###############''' % i)
            if os.path.exists(deploy.servicedir + str(i) + '/bin/logs') and os.path.exists(deploy.logdir+str(i)):
                print('         \033[32m软链接已存在\033[0m')
                os.system('ls -l %s'% (deploy.servicedir + str(i) + '/bin/logs'))
            else:
                print('         \033[31m软链接目录不存在,请检查\033[0m')

if __name__ == '__main__':
    start = readyTostart()
    start.ParametersCheck()
    start.Countdown()
    deploy = deployService()
    deploy.startDeploy()
    db = MongoDabase()
    db.createUser()
    check = configCheck()
    check.luaConfigcheck()
    check.scriptCheck()

网站题目:Python开发游戏开服脚本
本文URL:http://cxhlcq.com/article/goiisj.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部