首页 > 编程语言 > 详细

pythonxml-rpc记录(游戏自动发布)

时间:2014-07-21 15:26:17      阅读:428      评论:0      收藏:0      [点我收藏+]

#!/usr/bin/python

# -*- encoding=utf-8 -*-


####################################

from SimpleXMLRPCServer import SimpleXMLRPCServer

from SocketServer import ThreadingMixIn

import subprocess, os.path, os, stat

import re, getopt, sys


ERR_INSECURE = ‘[INSECURE_NAME]‘

ERR_NO_SCRIPT = ‘[NO_SCRIPT]‘

ERR_DUP_SCRIPT = ‘[DUP_SCRIPT]‘

ERR_OK = ‘[OK]‘


PT = re.compile(r‘^[0-9a-zA-Z\._]*$‘)


SCRIPT_DIR = ‘script‘ #will be init to absolute path


class ThreadXMLRPCServer(ThreadingMixIn, SimpleXMLRPCServer):pass


#############################################

def hello():

    print "hello,world!"


def is_name_secure(script_name):

    global PT

    if PT.match(script_name):

        return True



def init_script_path():

    ‘‘‘Init script_dir to absolute dir‘‘‘

    global SCRIPT_DIR

    SCRIPT_DIR = os.path.join(os.path.dirname(__file__), SCRIPT_DIR)

    

def get_file_data(script_name):

    global SCRIPT_DIR

    full_name = os.path.join(SCRIPT_DIR, script_name)

    with open(full_name, ‘rb‘) as f:

        return f.read()


def single_process():

    import platform


    pf = platform.system()

    if pf == ‘Linux‘: 

        import fcntl


        pid_file =‘/var/run/rpc.pid‘

        fp = open(pid_file,‘w‘)


        try:

            fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)

        except IOError:

            # another instance is running

            sys.exit(0)

    

def install(prefix):

    main_path = os.path.join(prefix, "rpc")

    if not os.path.isdir(main_path):

        os.makedirs(main_path)


    log_path = os.path.join(main_path, "log")

    if not os.path.isdir(log_path):

        os.makedirs(log_path, 0777)


    script_path = os.path.join(main_path, "script")

    if not os.path.isdir(script_path):

        os.makedirs(script_path)


    target_file = os.path.join(main_path, "rpc.py")

    if not os.path.isfile(target_file):

        #os.renames(__file__, target_file)

        os.system ("cp %s %s" % (__file__, target_file))

        os.chmod(target_file, stat.S_IRWXU|stat.S_IRWXG|stat.S_IROTH)


    with open(‘/etc/crontab‘, ‘a+‘) as f:

        has_croned = False

        for line in f.readlines():

            if line.find(‘rpc.py‘) >= 0 and line.lstrip()[0] != ‘#‘:

                break

        else:# not found

            #f.seek(0, os.SEEK_END)

            f.write(‘*/1 * * * * root %s >> %s 2>&1 &\n‘%(target_file, os.path.join(log_path, ‘rpc.log‘)))


    print ‘install ok.‘

#############################################

def run_script(script_name, *args):

    global SCRIPT_DIR

    if not is_name_secure(script_name):

        return ERR_INSECURE

    full_name = os.path.join(SCRIPT_DIR, script_name)

    if not os.path.isfile(full_name):

        return ERR_NO_SCRIPT

    print "run:" + full_name, args

    return check_output([full_name] + list(args))


def set_script(script_name, data):

    global SCRIPT_DIR

    if not is_name_secure(script_name):

        return ERR_INSECURE

    full_name = os.path.join(SCRIPT_DIR, script_name)

    if os.path.isfile(full_name):

        return ERR_DUP_SCRIPT

    print "set:" + full_name, len(data), ‘bytes‘

    with open(full_name, ‘wb‘) as f:

        f.write(data)

    os.chmod(full_name, stat.S_IRWXU|stat.S_IRWXG|stat.S_IROTH)

    return ERR_OK


def list_all():

    pass

#############################################


def check_output(*popenargs, **kwargs):

    r"""Run command with arguments and return its output as a byte string.


    If the exit code was non-zero it raises a CalledProcessError.  The

    CalledProcessError object will have the return code in the returncode

    attribute and output in the output attribute.


    The arguments are the same as for the Popen constructor.  Example:


    >>> check_output(["ls", "-l", "/dev/null"])

    ‘crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n‘


    The stdout argument is not allowed as it is used internally.

    To capture standard error in the result, use stderr=STDOUT.


    >>> check_output(["/bin/sh", "-c",

    ...               "ls -l non_existent_file ; exit 0"],

    ...              stderr=STDOUT)

    ‘ls: non_existent_file: No such file or directory\n‘

    """

    if ‘stdout‘ in kwargs:

        raise ValueError(‘stdout argument not allowed, it will be overridden.‘)

    process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)

    output, unused_err = process.communicate()

    retcode = process.poll()

    if retcode:

        cmd = kwargs.get("args")

        if cmd is None:

            cmd = popenargs[0]

        raise subprocess.CalledProcessError(retcode, cmd, output=output)

    return output

#############################################

def serve_forever():

    svr=ThreadXMLRPCServer(("", 8282), allow_none=True)

    svr.register_function(hello)

    svr.register_function(run_script)

    svr.register_function(set_script)

    svr.register_function(list_all)

    print ‘running at :8282‘

    svr.serve_forever()


if __name__ == ‘__main__‘:

    args = sys.argv[1:]

    if len(args) == 0: #server

        init_script_path()

        single_process()

        serve_forever()

    else: #client

        init_script_path()

        opts, args = getopt.getopt(sys.argv[1:], "i:h:s:a:")

        host = None

        script_name = None

        arg_str = ‘‘

        prefix = ‘‘

        for o, a in opts:

            if o == "-h":

                host = a

            elif o == "-s":

                script_name = a

            elif o == "-a":

                arg_str = a

            elif o == "-i":

                prefix = a

                install(prefix)

                exit()

        if host and script_name:

            from xmlrpclib import ServerProxy

            svr=ServerProxy("http://%s:8282"%host)

            ret = svr.run_script(script_name, *arg_str.split())

            print ret

            if ret == ERR_NO_SCRIPT:

                ret = svr.set_script(script_name, get_file_data(script_name))

                print ret

                if ret == ERR_OK:

                    ret = svr.run_script(script_name, *arg_str.split())

                    print ret

                    

                


本文出自 “muzinan的技术博客” 博客,转载请与作者联系!

pythonxml-rpc记录(游戏自动发布)

原文:http://muzinan110.blog.51cto.com/684213/1440890

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!