hxp
2024-08-31 44bcd51874e364012946b5f34dd7bb166d86edfb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
#!/usr/bin/python
# -*- coding: GBK -*-
#
##@package
#
# @todo: 
#
# @author: Alee
# @date 2019-2-20 ÏÂÎç04:50:04
# @version 1.0
#
# @note: 
#
#---------------------------------------------------------------------
#---------------------------------------------------------------------
from bottle import Bottle, request
from lib import mylog
import os, time
import md5
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import datetime
import subprocess
import urllib
from lib import ReadConfig
import traceback
# get: request.query.username request.GET.get('username','')
# post: request.forms.get('username')  request.POST.get('username')
#===============================================================================
# @myapp.route('/cool/kk/:name3/:count#\\d+#')
# def maybe(name3, count):
# client_ip = request.environ.get('REMOTE_ADDR')
# client_ip = request.environ.get('HTTP_X_FORWARDED_FOR') or request.environ.get('REMOTE_ADDR')
#===============================================================================
 
cfg = ReadConfig.ReadConfig(os.getcwd() + "\\config.ini")
SSL = cfg.GetInt("Mail", "SSL")
SMTPServer = cfg.GetValue("Mail", "SMTPServer")
Receivers = eval(cfg.GetValue("Mail", "Receivers"))
 
g_AllMapCnt = 0
 
myapp = Bottle()
 
# ¿ÉÖ´Ðй̶¨µÄÔ¶³ÌÃüÁî
 
@myapp.route('/control/openandclose.php', method='POST')
def RemoteCmd():
    dataDict = request.POST
#    for key in dataDict:
#        print key
#        mylog.debug("---%s"%dataDict[key])
    result = dataDict.get("control", "")
    if not result:
        return
    
    sign = dataDict.get("sign", "")
    if not sign:
        return
    
    ofile = open(r".\key.txt")
    text = ofile.read().strip()
    ofile.close()
    if sign != md5.md5("%s1234666%s" % (result, text)).hexdigest():
        mylog.debug("sign failed")
        return
    
    if result == "kaifu":
        pResult = os.popen('tasklist /FI "IMAGENAME eq EventServer.exe"')
        pResult = pResult.read()
        if "PID" in pResult or "pid" in pResult:
            return " =======server is opening£¬ EventServer.exe  is running"
        #os.system(r"call c:\ProjectServer\LaunchServerManager\Õý³£¿ª·þ.bat")
        # system call»áµ¼ÖÂ×Ó½ø³ÌÕ¼Óø¸½ø³ÌµÄÎļþÃèÊö·ûµ¼Ö¶˿ÚÎÞ·¨ÊÍ·Å£¬ Ó°ÏìÖØÆôʹÓÃ
        # Èç¹ûÐèÒª±£³Ö×Ó½ø³Ì³ÖÐø³¤ÆÚÔËÐеÄÓ¦¸Ãµ÷Óàsubprocess.Popen(cmd, close_fds=True)
        cmd = r"C:\server\LaunchServerManager\start.bat"
        subprocess.Popen(cmd, close_fds=True)
        return "open success"
    elif result == "guanfu":
        # ¼ÇµÃ¹Ø·þºó»òÕßÖØÆô»úÆ÷Ðè×Ô¶¯Æô¶¯·þÎñÆ÷¿ØÖÆÌ¨
        os.system(r"call C:\server\LaunchServerManager\close.bat")
        return "close success"
    elif result == "xiazai":
        # ¼ÇµÃ¹Ø·þºó»òÕßÖØÆô»úÆ÷Ðè×Ô¶¯Æô¶¯·þÎñÆ÷¿ØÖÆÌ¨
        os.system(r"call c:\RemoteServer\download.py")
        return "download success"
    elif result == "gengxin":
        # ¼ÇµÃ¹Ø·þºó»òÕßÖØÆô»úÆ÷Ðè×Ô¶¯Æô¶¯·þÎñÆ÷¿ØÖÆÌ¨
        os.system(r"call c:\RemoteServer\update.py")
        return "update success"
    elif result == "chongqi":
        # ¼ÇµÃ¹Ø·þºó»òÕßÖØÆô»úÆ÷Ðè×Ô¶¯Æô¶¯·þÎñÆ÷¿ØÖÆÌ¨
        pResult = os.popen('tasklist /FI "IMAGENAME eq ChinGameServer.exe"')
        pResult = pResult.read()
        if "PID" in pResult :
            return "server is opening, restart failed"
        else:
            os.system(r"call c:\RemoteServer\reboot.py")
            return "reboot success"
    elif result == "quxiaochongqi":
        
        # ¼ÇµÃ¹Ø·þºó»òÕßÖØÆô»úÆ÷Ðè×Ô¶¯Æô¶¯·þÎñÆ÷¿ØÖÆÌ¨
        os.system(r"call c:\RemoteServer\calreboot.py")
        return "cancel reboot  success"
    elif result == "runscript":
        # Ö´Ðнű¾ Â·¾¶¹Ì¶¨µ±Ç°Ä¿Â¼script.py
        os.system(r"call c:\RemoteServer\script.py")
        return "run script success"
    elif result == "runtime":
        return CheckUpTime()
    elif result == "restarMain":
        os.system(r"call c:\RemoteServer\restartMain.py")
        return "RestartMain ok"
    return
 
#»ñÈ¡·þÎñÆ÷ÔËÐÐʱ¼ä
def CheckUpTime():
    cmd = 'systeminfo |findstr "System Boot Time"'
    r = os.popen(cmd)
    text = r.read().replace(',', '')
    text = text.split()
 
    startTime = text[3] + ' ' + text[4]
    print startTime
    timeArray = time.strptime(startTime, "%Y-%m-%d %H:%M:%S")
    startTimeStamp = int(time.mktime(timeArray))
    nowTimeStamp = time.time()
    print 
    upTime = nowTimeStamp - startTimeStamp
    days = int(upTime // (3600 * 24))
    hours = int(upTime % (3600 * 24) // 3600)
    updatetime = "OpenTime:%d Day %d Hours" % (days, hours)
    return updatetime
 
# OnLogError OnPyError
# ·þÎñÆ÷¿ªÆôµÄ״̬»ã±¨
@myapp.route('/control/state.php')
def ServerState():
    global g_AllMapCnt
    try:
        dataDict = request.GET
        stateType = dataDict.get("Type", "")
        
        if not stateType:
            return
        
        if stateType == "MapInit":
            # ·þÎñÆ÷¹Ø±ÕµÄʱºò»áÖØÆô£¬´Ë״ֻ̬ÓÃÓÚ¿ª·þµÄʱºòÊÇ·ñ³õʼ»¯OK
            g_AllMapCnt = dataDict.get("MapCount", 0)
            if g_AllMapCnt:
                ifile = open(".\MapCount.txt", "w")
                ifile.write(str(datetime.datetime.today()) + "\t·þÎñÆ÷¿ªÆôÍê±Ï£¬µØÍ¼Êý=%s" % g_AllMapCnt)
                ifile.close()
            #return "·þÎñÆ÷¿ªÆôÍê±Ï£¬µØÍ¼Êý=%s"%dataDict.get("MapCount", 0)
            return
        
        elif stateType == "ClearOpenServerOK":
            mailText = "ÇåµµÍê±Ï:%s ·þÎñÆ÷×é:%s, dbname:%s" % (stateType, dataDict.get("groupID", 0), dataDict.get("userDBName", 0))
            SendEmail(mailText, dataDict.get("userDBName", 0), "ÇåµµÍê±Ï")
            return
        
        elif stateType in ["MapError", "GameServerError", "PyMongoError"]:
            #groupID=%s&userDBName=%s&Type=PyMongoError
            mailText = "´íÎóÀàÐÍ:%s ·þÎñÆ÷×é:%s, dbname:%s Òì³£ÐÅÏ¢:%s" % (stateType,
                                                       dataDict.get("groupID", 0),
                                                       dataDict.get("userDBName", 0),
                                                       urllib.unquote_plus(dataDict.get("MsgInfo", "")))
            SendEmail(mailText, dataDict.get("userDBName", 0))
            return
        elif stateType == "MapDisconnect":
            # µØÍ¼5·ÖÖÓδÏìÓ¦£¬¿ÉÒÔ¿¨ÁË»òÕßÉÁÍË ¹Ø±Õ
            #groupID=%s&userDBName=%s&Type=PyMongoError
            mailText = "´íÎóÀàÐÍ:µØÍ¼±»¹Ø±Õ%s ·þÎñÆ÷×é:%s, dbname:%s" % (stateType,
                                                       dataDict.get("groupID", 0),
                                                       dataDict.get("userDBName", 0))
            SendEmail(mailText, dataDict.get("userDBName", 0))
            return
        elif stateType in ["MapServerRaiseException", "GameServerRaiseException", "RaiseException"]:
            mailText = "%s Å׳öTryÒì³£±¨´í:·þÎñÆ÷×é:%s, dbname:%s, MapID:%s Òì³£ÐÅÏ¢:%s" % (
                                                       stateType,
                                                       dataDict.get("groupID", 0),
                                                       dataDict.get("userDBName", 0),
                                                       dataDict.get("mapID", 0),
                                                       urllib.unquote_plus(dataDict.get("MsgInfo", "")))
            SendEmail(mailText, dataDict.get("userDBName", 0))
            return
        elif stateType == "GameWarning":
            # ÓÎϷͨÓþ¯¸æÓʼþʹÓÃ
            mailText = "ÓÎÏ·¾¯±¨:·þÎñÆ÷×é:%s, dbname:%s, ¾¯¸æÐÅÏ¢:%s" % (
                                                       dataDict.get("groupID", 0),
                                                       dataDict.get("userDBName", 0),
                                                       urllib.unquote_plus(dataDict.get("MsgInfo", "")))
            SendEmail(mailText, dataDict.get("userDBName", 0))
 
        elif stateType == "QueryMapOK":
            if g_AllMapCnt == 0:
                if not os.path.exists(".\MapCount.txt"):
                    return "===ÔÝÎÞ·´À¡£¬ÉԵȺó²éѯ==="
                ifile = open(".\MapCount.txt")
                text = ifile.read()
                ifile.close()
                return "=========ÉÏÒ»´Î¼Ç¼µÄ¿ªÆôÇé¿ö, Çë¹ý»áÔÙ²éѯ========", text
            return "·þÎñÆ÷¿ªÆôÍê±Ï£¬µØÍ¼Êý:%s" % g_AllMapCnt
        
        else:
            mailText = "´íÎóÀàÐÍ:%s ·þÎñÆ÷×é:%s, dbname:%s Òì³£ÐÅÏ¢:%s" % (stateType,
                                                       dataDict.get("groupID", 0),
                                                       dataDict.get("userDBName", 0),
                                                       urllib.unquote_plus(dataDict.get("MsgInfo", "")))
            SendEmail(mailText, dataDict.get("userDBName", 0))
            return
        
    except BaseException:
        errInfo = str(traceback.format_exc())
        print errInfo
        mailText = "Óʼþ¿ØÖÆÌ¨±¨´í! %s" % errInfo
        try:
            SendEmail(mailText, dataDict.get("userDBName", 0), "Óʼþ¿ØÖÆÌ¨±¨´í")
        except:
            print "ÎÞ·¨·¢ËÍÓʼþ"
            
# Óʼþ»ã±¨
def SendEmail(mailText, dbname, subject="ÓÎÏ··þÎñÆ÷Òì³£"):
    
    section = "Mail_%s" % SMTPServer
    if not cfg.HasSection(section):
        print "ûÓÐÅäÖøÃÓÊÏä·þÎñÆ÷:%s" % section
        return
    
    # µÚÈý·½ SMTP ·þÎñ
    mail_host = cfg.GetValue(section, "Host") #ÉèÖ÷þÎñÆ÷
    mail_user = cfg.GetValue(section, "User") #Óû§Ãû
    mail_pass = cfg.GetValue(section, "Pass") #¿ªÍ¨ÓÊÏäµÄSMTP£¬¶ÌÐÅÑéÖ¤ºó»ñÈ¡µÄ£¬·ÇÃÜÂë
    
    sender = mail_user
    
    serverInfo = dbname.split('GameUser_')[1]
    
    if SMTPServer == "qq":
        message = MIMEText('%s' % mailText, 'plain', 'gbk')
        message['From'] = mail_user
        message['To'] = Header("ÔËά", 'gbk')    # ²»·¢Ë͵ϰ»á±»¼Ç¼ΪÀ¬»øÓʼþ
        message['Subject'] = Header("%s%s" % (serverInfo, subject), 'gbk')
    else:
        message = MIMEText('%s' % mailText, 'plain', 'gbk')
        message['From'] = Header("%s %s" % (serverInfo, subject), 'gbk')
        message['To'] = Header("ÔËά", 'gbk')    # ²»·¢Ë͵ϰ»á±»¼Ç¼ΪÀ¬»øÓʼþ
        message['Subject'] = Header(subject, 'gbk')
    
    if SSL == 1:
        smtpObj = smtplib.SMTP_SSL(mail_host)
        smtpObj.connect(mail_host, 465)
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, Receivers, message.as_string())
    else:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host, 25)
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, Receivers, message.as_string())
        
    print "Óʼþ·¢Ëͳɹ¦"