Python开发游戏开服脚本

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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(‘                   33[1;31;40m脚本即将开始执行...33[0m‘)
        time.sleep(2)
        print
        for i in range(3,0,-1):
            time.sleep(1)
            print(‘              脚本还有33[5;31;40m%s33[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(‘0d‘, openMonth): openMonth = openMonth[1:]
            if re.match(‘0d‘, 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(‘                    33[1;31;40m部署情况如下33[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+‘
‘)
                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(‘                 33[31m%s33[0m 服已经部署完成...‘ % i)
                print
        print(‘             33[1;31;40m数据库密码文件存放位置如下33[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 = ‘                 [33[32mID正确33[0m]‘
                                        else:
                                            result = ‘[33[32m端口正确33[0m]‘
                                    else:
                                        result = ‘ [33[5;31m配置错误33[0m]‘
                                        if int(m.group(2)) == int(openYear) and int(m.group(4)) == int(Month) and int(m.group(6)) == int(Day):
                                            yresult = ‘[33[32m年月日正确33[0m]‘
                                        else:
                                            yresult = ‘ [33[5;31m年或月或日错误33[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 = ‘      [33[32m密码正确33[0m]‘
                                        else:
                                            result = ‘[33[32m名字正确33[0m]‘
                                    else:
                                        result = ‘      [33[5;31m配置错误33[0m]‘
                                try:
                                    print(‘         %s33[31m%s33[0m%s33[31m%s33[0m%s33[31m%s33[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(‘         %s33[31m%s33[0m%s        %s‘ % (m.group(1), m.group(2), m.group(3), result))
                                    except Exception as e:
                                        print(‘         %s33[31m%s33[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开发游戏开服脚本的主要内容,如果未能解决你的问题,请参考以下文章

游戏运维平台

手游开服一天被黑客攻击,官方直接停服,将游戏改为单机版!

开服应该如何选择服务器

常用python日期日志获取内容循环的代码片段

搭建传奇游戏,都需要准备什么东西。

有啥游戏引擎用python脚本写的?