作業(yè)執(zhí)行過程
代碼如下:
# 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')
# 數(shù)據(jù)庫返回執(zhí)行結(jié)果
islines = select_salt_return(line_id)
# 返回空為失敗
if not islines:
return False
else:
return True
## 執(zhí)行腳本判斷,shell與Python分開執(zhí)行
def file_output(editor,job_name,script,hostName,params):
# 判斷服務(wù)器是否存活酌畜,不存活返回失敗
lines = isline(hostName)
if lines is False:
return False
if script == 'shell':
# job_name轉(zhuǎn)utf-8
job_name = job_name.decode('utf-8').encode('utf-8')
# 生成文件目錄
output = open('/CMDB/exec_file/{0}.sh'.format(job_name),'w')
# 存放文件內(nèi)容
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()
# 生成執(zhí)行文件名
job_names = job_name + '.sh'
# salt遠(yuǎn)程傳輸文件
local.cmd(hostName,'cp.get_file',['salt://exec_file/{0}'.format(job_names),'/tmp/exec_job/{0}'.format(job_names),'base',True],'','pcre')
# 空格轉(zhuǎn)義
job_names = job_names.replace(" ","\ ")
# 遠(yuǎn)程執(zhí)行腳本
job_id = local.cmd_async(hostName,'cmd.run',['bash -xe /tmp/exec_job/{0}'.format(job_names)],'pcre')
# 保存執(zhí)行語句
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()
# 生成執(zhí)行文件名
job_names = job_name + '.py'
# salt遠(yuǎn)程傳輸文件
local.cmd(hostName,'cp.get_file',['salt://exec_file/{0}'.format(job_names),'/tmp/exec_job/{0}'.format(job_names),'base',True],'','pcre')
# 空格轉(zhuǎn)義
job_names = job_names.replace(" ","\ ")
# 遠(yuǎn)程執(zhí)行腳本
job_id = local.cmd_async(hostName,'cmd.run',['python /tmp/exec_job/{0}'.format(job_names)],'pcre')
# 保存執(zhí)行語句
command_names = 'bash -xe /tmp/exec_job/{0}'.format(job_names)
return job_id, command_names