All pastes #2075442 Raw Edit

Mine

public python v1 · immutable
#2075442 ·published 2011-06-06 08:23 UTC
rendered paste body
import string,cgi,time,os,socketfrom BaseHTTPServer import BaseHTTPRequestHandler, HTTPServerfrom permissionsparser import parse, writeYml#Set up some global variablesPERMISSIONS_FILE   = ''ESSENTIALS_FILE    = ''MCSTATS_JSON_FILE  = ''MINECRAFT_LCK_FILE = ''TELNET_HOST = ''TELNET_PORT = TELNET_USER = ''TELNET_PASS = ''PASSWORD    = '' #this is for http form authentication#and also very important... (these are for THIS WEBSERVER SCRIPT)!!!MINECRAFT_SERVER_NAME = 'survival.minecraft.co.nz'MINECRAFT_SERVER_PORT = 8101class MyHandler(BaseHTTPRequestHandler):    def do_GET(self):        try:            if self.path.endswith("users"):                f = open(PERMISSIONS_FILE, 'r')                self.send_response(200)                self.send_header('Content-type',	'text/html')                self.end_headers()                can_start = False                st_mtime  = os.stat(PERMISSIONS_FILE).st_mtime                send_data = '{"epochTime":"%s","users":{' % st_mtime                for i in f.readlines():                    if can_start == True and not ' - ' in i and not 'permissions:' in i:                        if 'group:' in i:                            send_data += '"%s",' % i[15:].strip()                        else:                            send_data += '"%s":' % i.strip()[:-1]                    if 'users:' in i:                        can_start = True                f.close()                send_data = send_data[:-1] + '}}'                self.wfile.write(send_data)                return            if self.path.endswith("motd"):                self.send_response(200)                self.send_header('Content-type',	'text/html')                self.end_headers()                f = open(ESSENTIALS_FILE, 'r')                w = f.readlines()                f.close()                ready = False                motd = []                for i in w:                    if ready == True:                        if i[:4] == '  - ':                            motd += [i[5:-2]]                        else:                            ready = False                    if i == 'motd:\n':                        ready = True                self.wfile.write("<HTML><BODY><h3>Message of the Day editor</h3>\                    <p>This message appears when players join or type '/motd'.</p>\                    <p>Colour codes: <image src='http://i.imgur.com/h3CIU.png' /></p>\                    <form method='POST' enctype='multipart/form-data' action='http://%s:%s/motd'>\                    <textarea name='motd' cols=80 rows=10>" % (MINECRAFT_SERVER_NAME, MINECRAFT_SERVER_PORT))                self.wfile.write('\n'.join(motd))                self.wfile.write("</textarea><br>Password: <input type='password' name='pwd' /><br>\                    <input type=submit value=Submit> <i>(takes about 8 seconds)</i></form></BODY></HTML>")                return                                                # BEGIN   +=============================================================================                                            if self.path.endswith("permissions"):                self.send_response(200)                self.send_header('Content-type',	'text/html')                self.end_headers()                ymldata, users = parse(PERMISSIONS_FILE)                                u = []                for i in users:                    u += [[i, users[i]['group']]]                u = sorted(u)                self.wfile.write("<HTML><BODY><h3>Permissions Editor (alpha)</h3>\                    <form method='POST' enctype='multipart/form-data' action='http://%s:%s/permissions-confirm'>\                    Select a user <select name='userselect'>\n" % (MINECRAFT_SERVER_NAME, MINECRAFT_SERVER_PORT))                for i in u:                    self.wfile.write("<option value='%s'>%s (%s)</option>\n" % (i[0], i[0], i[1]))                self.wfile.write("</select> or add a new one <input type='text' name='usertext' />\                    <br><br>New group <select name='newgroup'>\n\                    <option value='Visitor'>Visitor</option>\n\                    <option value='Griefer'>Griefer</option>\n\                    <option value='Builder'>Builder</option>\n\                    <option value='Architect'>Architect</option>\n\                    <option value='VIP'>VIP</option>\n\                    <option value='UberVIP'>UberVIP</option>\n\                    <option value='Mod'>Mod</option>\n\                    <option value='UberMod'>UberMod</option>\n\                    <option value='MiniAdmin'>MiniAdmin</option>\n</select>\                    <br><br><br><br>Password: <input type='password' name='pwd' />\                    <br><input type=submit value=Submit></form></BODY></HTML>")                return                                                # END     +=============================================================================                                            else:                f = open(MCSTATS_JSON_FILE)                self.send_response(200)                self.send_header('Content-type', 'text/html')                self.end_headers()                can_start = False                status = os.path.isfile(MINECRAFT_LCK_FILE)                send_data = '{"serverStatus":"%s",' % status                usersonline = []                for i in f.read().split('playersOnline')[1].split('playerName":'):                    if i[1] != ':':                        usersonline += [i.split('"')[1]]                playercount = len(usersonline)                if status == False: playercount = 0                if usersonline == ['No One']: playercount = 0                send_data += '"playerCount":%s,"playersOnline":"' % playercount                if status == False:                    send_data += ','                else:                    for i in usersonline:                        send_data += '%s,' % i                send_data = send_data[:-1] + '"}'                self.wfile.write(send_data)                f.close()                return            return                        except IOError:            self.send_error(404,'File Not Found: %s' % self.path)    def do_POST(self):        global rootnode        try:            if self.path.endswith("motd"):                ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))                if ctype == 'multipart/form-data':                    query=cgi.parse_multipart(self.rfile, pdict)                self.send_response(301)                                self.end_headers()                response = query.get('motd')[0].split('\r\n')                pwd = query.get('pwd')[0]                    if pwd == PASSWORD:                    self.wfile.write('<HTML><BODY><h3>Success!</h3>')                    f = open(ESSENTIALS_FILE, 'r')                    w = f.readlines()                    f.close()                                    ready = False                    config = []                    for i in w:                        if ready == True:                            if i[:4] != '  - ':                                for j in response:                                    config += ["  - '%s'\n" % j]                                config += i                                ready = False                        else:                            config += i                        if i == 'motd:\n':                            ready = True                                        f = open(ESSENTIALS_FILE, 'w')                    f.write(''.join(config))                    f.close()                    self.telnetCommand('reload')                                else:                    self.wfile.write('<HTML><BODY><h3>Error!</h3>Invalid password.')                    self.wfile.write("<br><a href='http://%s:%s/motd'>Go back</a>\                    </BODY></HTML>" % (MINECRAFT_SERVER_NAME, MINECRAFT_SERVER_PORT))                                if self.path.endswith("permissions-confirm"):                ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))                if ctype == 'multipart/form-data':                    query=cgi.parse_multipart(self.rfile, pdict)                self.send_response(301)                self.end_headers()                                userselect = query.get('userselect')[0]                usertext   = query.get('usertext')[0]                pwd        = query.get('pwd')[0]                group      = query.get('newgroup')[0]                                user = userselect                if usertext: user = usertext                                if pwd == PASSWORD:                    self.wfile.write('<HTML><BODY><h3>Please confirm:</h3>You want to change <b>%s</b> to group <b>%s</b>\                        <br><br>Is this correct?' % (user, group))                    self.wfile.write("<br><br><br><form method='POST' enctype='multipart/form-data' action='http://%s:%s/permissions-proceed'>\n\                        <input type=submit value='Yes, do it!'> <i>(takes about 8 seconds)</i>\n\                        <input type=hidden name='user' value='%s'>\n\                        <input type=hidden name='group' value='%s'>\n\                        </form>" % (MINECRAFT_SERVER_NAME, MINECRAFT_SERVER_PORT, user, group))                else:                    self.wfile.write('<HTML><BODY><h3>Error!</h3>Invalid password.')                            if self.path.endswith("permissions-proceed"):                ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))                if ctype == 'multipart/form-data':                    query=cgi.parse_multipart(self.rfile, pdict)                self.send_response(301)                self.end_headers()                                #get our info                user  = query.get('user')[0]                group = query.get('group')[0]                ymldata, users = parse(PERMISSIONS_FILE)                                if user not in users:                    users[user] = {}                users[user]['group'] = group                                #apply changes                writeYml(ymldata, users, PERMISSIONS_FILE)                self.telnetCommand('say User %s has been moved to %s' % (user, group))                result = self.telnetCommand('permissions -reload all')                                self.wfile.write('<HTML><BODY><h3>Success!</h3>Console output:<br><code>%s</code><br><br>' % '<br>'.join(result))                            self.wfile.write("<a href='http://%s:%s/permissions'>Go back</a></BODY></HTML>" % (MINECRAFT_SERVER_NAME, MINECRAFT_SERVER_PORT))                    except :            print '--- An internal error occurred while processing the POST data'            def telnetCommand(self, cmd):        try:            s = socket.socket()            s.connect((TELNET_HOST, TELNET_PORT))            s.send('%s\n' % TELNET_USER)            time.sleep(2)            s.send('%s\n' % TELNET_PASS)            time.sleep(2)            s.send('%s\n' % cmd)            time.sleep(2)            r = s.recv(1024)            s.close()            j = []            for i in r.split('\r\n'):                if len(i) > 1 and i[0] == ':':                    j += [i[1:]]            return j        except:            passdef main():    try:        server = HTTPServer(('', MINECRAFT_SERVER_PORT), MyHandler)        print 'started httpserver...'        server.serve_forever()    except KeyboardInterrupt:        print '^C received, shutting down server'        server.socket.close()if __name__ == '__main__':    main()