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
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()

执行结果展示

原文地址:http://blog.51cto.com/yht1990/2139005

时间: 2024-11-13 23:32:10

Python开发游戏开服脚本的相关文章

最新dedecms网页游戏开服表发号网站源码模板

模板介绍 最新dedecms网页游戏开服表发号网站源码模板,让你更精确的把握游戏开服时间和战略技巧. 这套网页游戏模板是织梦二次开发后的一套网页源码,后台也是经过二次开发后,适合游戏网站的一些参数说明及添加信息. 模板文件: 404.htm            大气的404页面 article_fahao.htm  发号模板详细页 article_time.htm   发号时间详细页 footer_time.htm    发号时间底部模板 head_time.htm      发号时间头部模板

python socket模拟游戏开服

python socket服务端 #!/usr/bin/python #-*- coding: utf-8 -*- import socket import os,sys host='127.0.0.1' #监听的IP port=60000       #监听的端口 buffer=1024      #接受的字节数 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)  #建立socket对象 sock.bind((host,port)) #

游戏开服 报一些 ip 设置 数据格式的异常,但断点明明都是数字 没问题的

游戏服开始起服,结果报乱七八招的错误,先  ccs 那 ip 有问题,我给直接注释掉了:然后又 报 KeyValueDictCache 中 ips 设置有问题,都是报格式错误,结果我断点明明都是数字结果 在判断数字 那反而还是报错,结果我想想估计 是tm的 编码问题,原来 我之前刚导入项目 到intellj,结果有几个jar包存在却类 报错找不到jar包,结果我把报错的类 编码改为gbk(intellj最下边直接改的编码),结果类就不报错了,但是起服 后就是出现上边的乱七八糟的问题,结果我把编码

python邮件发送开服记录

#-*-coding:utf-8 -*- #!/usr/bin/python import sys reload(sys) # reload 才能调用 setdefaultencoding 方法 sys.setdefaultencoding('utf-8') # 设置 'utf-8' import MySQLdb import houtai_dbname from email.mime.text import MIMEText from email.header import Header im

二十年前是怎样开发游戏的?

知乎上有人问:"贴吧都是十五六岁就用引擎写游戏的天才,大家怎么看?",感觉现在做游戏真实一件幸福的事情呀,不尽想起当年开发游戏的各种艰辛. 现在做游戏很简单,大把代码给你参考,大把框架给你使用,Windows帮你作完了大部分事情.我们那个年纪写游戏时,家里还没有Internet,什么资料都查不到,什么开源引擎都没有,95年左右你要写一个游戏,你起码面临: 同显卡打交道,显卡著名的 ModeX显示模式,估计现在没几个人听过了吧,直接写显卡端口,N多trick才能初始化成功. 直接访问显存

python编写开发更新数据后台脚本

#!/usr/bin/env python #coding:utf-8 import os import re import shutil as copy copy_web_service = '/data/web/s1' dest_web_service = '/data/web/s' all_web_service = '/data/web/' crontab_file = '/data/update/crontab.txt' openservice_num = '/data/update/

【游戏】终于开服了

网易魔兽终于在昨天开服了,晚上下班后,登录的服务器,一切安好.上线时间很短,第一件事就是重新点了一下天赋,有改动,由于没有去杀怪,没看到具体效果.总体来说,服务器不卡,我的延迟136.图标方面没有出现箱子河蟹,不过好像有一个物品的图标变化了.我相信图标方面,目前只是临时对应方案,网易应该还会放出一个资源更新包,不会真的变成“箱子世界”.游戏新的设定还不错,有几个原来靠插件实现的地方,现在原生支持了.大脚插件有一部分不是很好用,不过常用的还不错啦.游戏字体,特别是数字,看着别扭,迅速用工具把所有字

python开发_tkinter_小球完全弹性碰撞游戏

python开发_tkinter_小球完全弹性碰撞游戏 完成这个小球的完全弹性碰撞游戏灵感来自于: 下面是我花了一周下班时间所编写的一个小球完全弹性碰撞游戏: 游戏初始化状态: 最下面的游标和修改小球的移动速度 =================================================== 源码部分: =================================================== 1 #python tkinter 2 #python versio

Coco2d-x android win7 Python 搭建游戏开发环境

1:我用电脑配置 win7 3 核 内存8G 台式机,一直想研究Coco2d 游戏开发,所以经过一周的需找,终于把环境搭建好了 2:我用的版本是该版本,至于搭建android开发环境省略了, 3: 2.2>安装ndk,为了使用c++/c进行android开发 下载android-ndk-r8e,然后在eclipse或adt bundle中配置ndk路径. 4: 5:采用VS 编译环境 我之前用的VS2010 感觉用着不爽,所以改成现在的VS 2012 , 6:一般用python建立项目: 用py