saltstack作业执行

作业执行过程


代码如下:

# test.ping心跳检测
def isline(hostname):
    from exec_jobs import select_salt_return
    # test.ping存活判断,可以直接用local.cmd,返回True判断
    line_id = local.cmd_async(hostname,'test.ping','','pcre')
    # 数据库返回执行结果
    islines = select_salt_return(line_id)
    # 返回空为失败
    if not islines:
        return False
    else:
        return True

## 执行脚本判断,shell与Python分开执行
def file_output(editor,job_name,script,hostName,params):
    # 判断服务器是否存活,不存活返回失败
    lines = isline(hostName)
    if lines is False:
        return False
    if script == 'shell':
        # job_name转utf-8
        job_name = job_name.decode('utf-8').encode('utf-8')
        # 生成文件目录
        output = open('/CMDB/exec_file/{0}.sh'.format(job_name),'w')
        # 存放文件内容
        param_output = ""
         # 逐行存放到文件中
        for param in params:
            param_output = "{0}={1}".format(param['param_name'],param['param_value'])
            output.write(param_output + '\n')
        # 写入文件
        output.write(editor)
        output.close()
        # 生成执行文件名
        job_names = job_name + '.sh'
        # salt远程传输文件
        local.cmd(hostName,'cp.get_file',['salt://exec_file/{0}'.format(job_names),'/tmp/exec_job/{0}'.format(job_names),'base',True],'','pcre')
        # 空格转义
        job_names = job_names.replace(" ","\ ")
        # 远程执行脚本
        job_id = local.cmd_async(hostName,'cmd.run',['bash  -xe /tmp/exec_job/{0}'.format(job_names)],'pcre')
        # 保存执行语句
        command_names = 'bash  -xe /tmp/exec_job/{0}'.format(job_names)
    else:
        # 生成文件目录
        output = open('/CMDB/exec_file/{0}.py'.format(job_name),'w')
        # 写入文件
        output.write(editor)
        output.close()
        # 生成执行文件名
        job_names = job_name + '.py'
        # salt远程传输文件
        local.cmd(hostName,'cp.get_file',['salt://exec_file/{0}'.format(job_names),'/tmp/exec_job/{0}'.format(job_names),'base',True],'','pcre')
        # 空格转义
        job_names = job_names.replace(" ","\ ")
        # 远程执行脚本
        job_id = local.cmd_async(hostName,'cmd.run',['python /tmp/exec_job/{0}'.format(job_names)],'pcre')
        # 保存执行语句
        command_names = 'bash  -xe /tmp/exec_job/{0}'.format(job_names)
    return job_id, command_names

你可能感兴趣的:(saltstack作业执行)