Ejemplo n.º 1
0
def iptables_lint_contents(contents, webobj=None, machine=None):
    from karesansui.lib.file.configfile import ConfigFile

    if not os.path.exists(CONF_TMP_DIR):
        os.makedirs(CONF_TMP_DIR)
        r_chmod(CONF_TMP_DIR, 0770)
        r_chown(CONF_TMP_DIR, KARESANSUI_USER)
        r_chgrp(CONF_TMP_DIR, KARESANSUI_GROUP)

    seconds = 10 * 60
    for _old in glob.glob("%s/iptables-save.*" % (CONF_TMP_DIR, )):
        mtime = os.stat(_old).st_mtime
        if int(time.time()) > (mtime + seconds):
            os.unlink(_old)

    serial = time.strftime("%Y%m%d%H%M%S", time.localtime())
    filename = "%s/iptables-save.%s" % (
        CONF_TMP_DIR,
        serial,
    )

    ConfigFile(filename).write(contents)
    r_chmod(filename, 0660)
    r_chown(filename, KARESANSUI_USER)
    r_chgrp(filename, KARESANSUI_GROUP)

    return iptables_lint(filename, webobj, machine, delete=True)
Ejemplo n.º 2
0
def iptables_lint_contents(contents, webobj=None, machine=None):
    from karesansui.lib.file.configfile import ConfigFile
    
    if not os.path.exists(CONF_TMP_DIR):
        os.makedirs(CONF_TMP_DIR)
        r_chmod(CONF_TMP_DIR,0770)
        r_chown(CONF_TMP_DIR,KARESANSUI_USER)
        r_chgrp(CONF_TMP_DIR,KARESANSUI_GROUP)

    seconds = 10 * 60
    for _old in glob.glob("%s/iptables-save.*" % (CONF_TMP_DIR,)):
        mtime = os.stat(_old).st_mtime
        if int(time.time()) > (mtime + seconds):
            os.unlink(_old)

    serial = time.strftime("%Y%m%d%H%M%S",time.localtime())
    filename = "%s/iptables-save.%s" % (CONF_TMP_DIR,serial,)

    ConfigFile(filename).write(contents)
    r_chmod(filename,0660)
    r_chown(filename,KARESANSUI_USER)
    r_chgrp(filename,KARESANSUI_GROUP)

    return iptables_lint(filename, webobj, machine, delete=True)
Ejemplo n.º 3
0
def exec_script(script="",user="******",msg="",watch_name="",logfile="/dev/null"):
    retval = False

    func_name = sys._getframe(0).f_code.co_name
    append_line(logfile,"[%s] Entering function '%s'." % (func_name,func_name,))

    # スクリプトの一時保存ディレクトリを作成
    SCRIPT_TMP_DIR = "%s/tmp/.script" % (KARESANSUI_DATA_DIR,)
    if not os.path.exists(SCRIPT_TMP_DIR):
        os.makedirs(SCRIPT_TMP_DIR)
        r_chmod(SCRIPT_TMP_DIR,0770)
        r_chown(SCRIPT_TMP_DIR,KARESANSUI_USER)
        r_chgrp(SCRIPT_TMP_DIR,KARESANSUI_GROUP)
        append_line(logfile,"[%s] Create directory '%s'." % (func_name,SCRIPT_TMP_DIR,))

    try:
       user_id = int(user)
    except:
       user_id = pwd.getpwnam(user)[2]

    # スクリプトファイルの生成
    fname = None
    try:
        fd, fname  = tempfile.mkstemp(suffix="",prefix="script_",dir=SCRIPT_TMP_DIR)
        append_line(logfile,"[%s] Create script '%s'." % (func_name,fname,))
        fp = os.fdopen(fd,"w")
        fcntl.lockf(fp.fileno(), fcntl.LOCK_EX)
        script = re.sub("%{watch_name}",watch_name.encode('utf_8'),script)
        script = re.sub("%{msg}"       ,msg.encode('utf_8')       ,script)
        fp.write(script)
        fcntl.lockf(fp.fileno(), fcntl.LOCK_UN)
        fp.close()
        os.chmod(fname,0700)
        os.chown(fname,user_id,-1)

    except:
        append_line(logfile,"[%s] Error: failed to create script." % (func_name,))
        if fname is not None and os.path.exists(fname):
            os.unlink(fname)

    if fname is not None and os.path.exists(fname):

        # マジッククッキーを調べる
        magic_cookie = open(fname).readline().rstrip()
        if magic_cookie[-8:] == "bin/perl":
            interpreter = "perl"
        elif magic_cookie[-10:] == "bin/python" or \
             magic_cookie[-10:] == "env python":
            interpreter = "python"
        elif magic_cookie[-7:] == "bin/php":
            interpreter = "php"
        elif magic_cookie[-8:] == "bin/ruby":
            interpreter = "ruby"
        elif magic_cookie[-8:] == "bin/tcsh":
            interpreter = "tcsh"
        elif magic_cookie[-7:] == "bin/csh":
            interpreter = "csh"
        else:
            interpreter = "sh"

        # コマンド文字列の作成
        if os.getuid() != user_id:
            command_args = ["su","-s", "/bin/bash", user, fname]
        else:
            command_args = [interpreter,fname]

        # コマンドの実行
        append_line(logfile,"[%s] Execute command '%s'." % (func_name," ".join(command_args),))
        (rc,res) = execute_command(command_args)
        new_res = []
        for _aline in res:
            append_line(logfile,"[%s] output> %s" % (func_name,_aline,))
            _aline = re.sub("^%s:[ \t]+" % fname, "", _aline)
            new_res.append(_aline)
            pass
        append_line(logfile,"[%s] command return value = %d" % (func_name,rc,))

        os.unlink(fname)

        retval = [rc,new_res]
    else:
        append_line(logfile,"[%s] Error: cannot create script file." % (func_name,))

    append_line(logfile,"[%s] Leaving function '%s'." % (func_name,func_name,))
    return retval
Ejemplo n.º 4
0
def write_conf(dop, webobj=None, machine=None, modules=[], extra_args={}):
    """<comment-ja>
    @param dop: 辞書配列操作オブジェクト
    @param webobj: 
    @param machine: 
    @type dop: object dict_op
    @rtype: boolean
    @return: True or False
    </comment-ja>
    <comment-en>
    TODO: English Comment
    </comment-en>
    """
    from karesansui.lib.file.configfile import ConfigFile

    if isinstance(dop,karesansui.lib.dict_op.DictOp) is False:
        return False

    if not os.path.exists(CONF_TMP_DIR):
        os.makedirs(CONF_TMP_DIR)
        r_chmod(CONF_TMP_DIR,0770)
        r_chown(CONF_TMP_DIR,KARESANSUI_USER)
        r_chgrp(CONF_TMP_DIR,KARESANSUI_GROUP)

    serial = time.strftime("%Y%m%d%H%M%S",time.localtime())

    if len(modules) == 0:
        modules = dop.ModuleNames

    w_modules = []
    w_files   = []
    for _module in modules:
        if _module in dop.ModuleNames:
            filename = "%s/%s.%s" % (CONF_TMP_DIR,_module,serial,)
            data = preprint_r(dop.getconf(_module),return_var=True)
            ConfigFile(filename).write(data+"\n")
            r_chmod(filename,0660)
            r_chown(filename,KARESANSUI_USER)
            r_chgrp(filename,KARESANSUI_GROUP)
            w_modules.append(_module)
            w_files.append(filename)

    if len(w_modules) == 0:
        return False

    options = {
         "module"     : ":".join(w_modules),
         "input-file" : ":".join(w_files),
    }
    options["delete"] = None

    try:
        extra_args['pre-command']
        options['pre-command'] = "b64:" + base64_encode(extra_args['pre-command'])
    except:
        pass
    try:
        extra_args['post-command']
        options['post-command'] = "b64:" + base64_encode(extra_args['post-command'])
    except:
        pass

    try:
        options['include'] = extra_args['include']
    except:
        pass

    #cmd_name = u"Write Settings - %s" % ":".join(w_modules)
    cmd_name = u"Write Settings"

    if type(webobj) == types.InstanceType:
        from karesansui.db.model._2pysilhouette import Job, JobGroup, \
                                                       JOBGROUP_TYPE
        from karesansui.db.access._2pysilhouette import jg_findby1, jg_save,corp
        from karesansui.db.access._2pysilhouette import save_job_collaboration
        from karesansui.db.access.machine2jobgroup import new as m2j_new
        from pysilhouette.command import dict2command

        _cmd = dict2command(
            "%s/%s" % (karesansui.config['application.bin.dir'],
                       CONFIGURE_COMMAND_WRITE), options)

        _jobgroup = JobGroup(cmd_name, karesansui.sheconf['env.uniqkey'])
        _jobgroup.jobs.append(Job('%s command' % cmd_name, 0, _cmd))

        _machine2jobgroup = m2j_new(machine=machine,
                                jobgroup_id=-1,
                                uniq_key=karesansui.sheconf['env.uniqkey'],
                                created_user=webobj.me,
                                modified_user=webobj.me,
                                )

        save_job_collaboration(webobj.orm,
                               webobj.pysilhouette.orm,
                               _machine2jobgroup,
                               _jobgroup,
                               )

        """
        _jobgroup.type = JOBGROUP_TYPE['PARALLEL']
        if corp(webobj.orm, webobj.pysilhouette.orm,_machine2jobgroup, _jobgroup) is False:
            webobj.logger.debug("%s command failed. Return to timeout" % (cmd_name))
            for filename in w_files:
                if os.path.exists(filename):
                    os.unlink(filename)
            return False

        cmd_res = jobgroup.jobs[0].action_stdout
        """

    else:
        from karesansui.lib.utils import execute_command

        opts_str = ""
        for x in options.keys():
            if options[x] is None:
                opts_str += "--%s " % x 
            else:
                opts_str += "--%s=%s " % (x, options[x])

        _cmd = "%s/bin/%s %s" % (KARESANSUI_PREFIX, CONFIGURE_COMMAND_WRITE, opts_str.strip(),)

        command_args = _cmd.strip().split(" ")
        (rc,res) = execute_command(command_args)
        if rc != 0:
            for filename in w_files:
                if os.path.exists(filename):
                    os.unlink(filename)
            return False

        cmd_res = "\n".join(res)

    """
    for filename in w_files:
        if os.path.exists(filename):
            os.unlink(filename)
    """

    return True
Ejemplo n.º 5
0
def exec_script(script="",
                user="******",
                msg="",
                watch_name="",
                logfile="/dev/null"):
    retval = False

    func_name = sys._getframe(0).f_code.co_name
    append_line(logfile, "[%s] Entering function '%s'." % (
        func_name,
        func_name,
    ))

    # スクリプトの一時保存ディレクトリを作成
    SCRIPT_TMP_DIR = "%s/tmp/.script" % (KARESANSUI_DATA_DIR, )
    if not os.path.exists(SCRIPT_TMP_DIR):
        os.makedirs(SCRIPT_TMP_DIR)
        r_chmod(SCRIPT_TMP_DIR, 0770)
        r_chown(SCRIPT_TMP_DIR, KARESANSUI_USER)
        r_chgrp(SCRIPT_TMP_DIR, KARESANSUI_GROUP)
        append_line(
            logfile, "[%s] Create directory '%s'." % (
                func_name,
                SCRIPT_TMP_DIR,
            ))

    try:
        user_id = int(user)
    except:
        user_id = pwd.getpwnam(user)[2]

    # スクリプトファイルの生成
    fname = None
    try:
        fd, fname = tempfile.mkstemp(suffix="",
                                     prefix="script_",
                                     dir=SCRIPT_TMP_DIR)
        append_line(logfile, "[%s] Create script '%s'." % (
            func_name,
            fname,
        ))
        fp = os.fdopen(fd, "w")
        fcntl.lockf(fp.fileno(), fcntl.LOCK_EX)
        script = re.sub("%{watch_name}", watch_name.encode('utf_8'), script)
        script = re.sub("%{msg}", msg.encode('utf_8'), script)
        fp.write(script)
        fcntl.lockf(fp.fileno(), fcntl.LOCK_UN)
        fp.close()
        os.chmod(fname, 0700)
        os.chown(fname, user_id, -1)

    except:
        append_line(logfile,
                    "[%s] Error: failed to create script." % (func_name, ))
        if fname is not None and os.path.exists(fname):
            os.unlink(fname)

    if fname is not None and os.path.exists(fname):

        # マジッククッキーを調べる
        magic_cookie = open(fname).readline().rstrip()
        if magic_cookie[-8:] == "bin/perl":
            interpreter = "perl"
        elif magic_cookie[-10:] == "bin/python" or \
             magic_cookie[-10:] == "env python":
            interpreter = "python"
        elif magic_cookie[-7:] == "bin/php":
            interpreter = "php"
        elif magic_cookie[-8:] == "bin/ruby":
            interpreter = "ruby"
        elif magic_cookie[-8:] == "bin/tcsh":
            interpreter = "tcsh"
        elif magic_cookie[-7:] == "bin/csh":
            interpreter = "csh"
        else:
            interpreter = "sh"

        # コマンド文字列の作成
        if os.getuid() != user_id:
            command_args = ["su", "-s", "/bin/bash", user, fname]
        else:
            command_args = [interpreter, fname]

        # コマンドの実行
        append_line(
            logfile, "[%s] Execute command '%s'." % (
                func_name,
                " ".join(command_args),
            ))
        (rc, res) = execute_command(command_args)
        new_res = []
        for _aline in res:
            append_line(logfile, "[%s] output> %s" % (
                func_name,
                _aline,
            ))
            _aline = re.sub("^%s:[ \t]+" % fname, "", _aline)
            new_res.append(_aline)
            pass
        append_line(logfile, "[%s] command return value = %d" % (
            func_name,
            rc,
        ))

        os.unlink(fname)

        retval = [rc, new_res]
    else:
        append_line(logfile,
                    "[%s] Error: cannot create script file." % (func_name, ))

    append_line(logfile, "[%s] Leaving function '%s'." % (
        func_name,
        func_name,
    ))
    return retval