Esempio n. 1
0
def run_cmd(request):
    try:
        server_names = request.POST.get('server_names')
        belong_tos = request.POST.get('belong_tos')
        server_names = server_names.split(',')
        belong_tos = belong_tos.split(',')
        cmd = request.POST.get('cmd')
        time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        servers = {}
        cmd_results = ''
        for i in  zip(server_names,belong_tos):
            if not servers.has_key(i[1]):
                servers[i[1]] = []
            servers[i[1]].append(i[0])
        for k,v in servers.items():
            v = ','.join(v)
            cmd_result = client_send_data("{'salt':1,'act':'cmd.run','hosts':'%s','argv':%s}" % (v,cmd.split(',')),CENTER_SERVER[k][0],CENTER_SERVER[k][1])
            cmd_result = convert_str_to_html(cmd_result)
            if cmd_results:
                cmd_results = cmd_result
            else:
                cmd_results = cmd_results + '<br><br><br><br>' + cmd_result
        for i in server_names:
            log.objects.create(source_ip=i,username=request.user.username,command=cmd,time=time_now)
        return HttpResponse(simplejson.dumps({'code':0,'msg':u'完成执行完成','cmd_results':cmd_results}),content_type="application/json")
    except Exception,e:
        logger.error(e)
        return HttpResponse(simplejson.dumps({'code':1,'msg':u'完成执行失败'}),content_type="application/json")
Esempio n. 2
0
def run_cmd(request):
    try:
        server_names = request.POST.get('server_names')
        belong_tos = request.POST.get('belong_tos')
        server_names = server_names.split(',')
        belong_tos = belong_tos.split(',')
        cmd = request.POST.get('cmd')
        cmd_template = request.POST.get('cmd_template')

        for center_server in belong_tos:
            if not check_center_server_up(CENTER_SERVER[center_server][0],CENTER_SERVER[center_server][1]):
                return HttpResponse(json.dumps({'code':1,'msg':u'无法连接到%s' % center_server}),content_type="application/json")

        time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        servers = {}
        cmd_results = ''
        for i in  zip(server_names,belong_tos):
            if not servers.has_key(i[1]):
                servers[i[1]] = []
            servers[i[1]].append(i[0])
        for k,v in servers.items():
            v = ','.join(v)
            if cmd:
                cmd_result = client_send_data(json.dumps({'salt':1,'act':'cmd.run','hosts':v,'argv':cmd.split(',,')}),CENTER_SERVER[k][0],CENTER_SERVER[k][1])
                cmd_result = convert_str_to_html(cmd_result)
                if not cmd_results:
                    cmd_results = cmd_result
                else:
                    cmd_results = cmd_results + '<br><br><br><br>' + cmd_result
            if cmd_template:
                orm = command_template.objects.get(description=cmd_template)
                command = '''echo '%s' > /tmp/tempfile && if awk 'FNR==1' /tmp/tempfile|grep python > /dev/null 2>&1;then python /tmp/tempfile;else bash /tmp/tempfile;fi;rm -rf /tmp/tempfile''' % re.sub(r"'",'''\'"'"\'''',orm.cmd)
                cmd_result = client_send_data(json.dumps({'salt':1,'act':'cmd.run','hosts':v,'argv':command.split(',,')}),CENTER_SERVER[k][0],CENTER_SERVER[k][1])
                cmd_result = convert_str_to_html(cmd_result)
                if cmd_results:
                    cmd_results = cmd_result
                else:
                    cmd_results = cmd_results + '<br><br><br><br>' + cmd_result
                cmd = u'模板 < %s >' % cmd_template
        for i in server_names:
            log.objects.create(source_ip=i,username=request.user.username,command=cmd,time=time_now)
        return HttpResponse(json.dumps({'code':0,'msg':u'完成执行完成','cmd_results':cmd_results}),content_type="application/json")
    except Exception,e:
        logger.error(e)
        return HttpResponse(json.dumps({'code':1,'msg':u'完成执行失败'}),content_type="application/json")
Esempio n. 3
0
def salt_top_run(request):
    center_server = request.POST.get("center_server")
    run_target = request.POST.get("run_target")
    state = request.POST.get("state")

    for server in center_server.split("|"):
        if not check_center_server_up(CENTER_SERVER[server][0], CENTER_SERVER[server][1]):
            return HttpResponse(
                json.dumps({"code": 1, "msg": u"无法连接到%s" % server, "cmd_results": ""}), content_type="application/json"
            )

    run_target_dict = {}
    target = []
    cmd_results = ""
    time_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    for i in zip(center_server.split("|"), run_target.split("|"), state.split("|")):
        if not run_target_dict.has_key(i[0]):
            run_target_dict[i[0]] = []
        run_target_dict[i[0]].append((i[1], i[2]))

    for i in run_target_dict.keys():
        master_dir = commands.getoutput(
            '''ssh %s "grep -A2 '^file_roots' /etc/salt/master |grep 'base:' -A1|grep '-'|cut -d'-' -f2"'''
            % CENTER_SERVER[i][0]
        )
        content = "base:\n"
        for j in run_target_dict[i]:
            for n in j[0].split(","):
                if not n in target:
                    target.append(n)
                    cmd = u"state模块 < %s >" % j[1]
                    log.objects.create(source_ip=n, username=request.user.username, command=cmd, time=time_now)
                else:
                    return HttpResponse(
                        json.dumps({"code": 1, "msg": u"目标主机不能重复", "cmd_results": cmd_results}),
                        content_type="application/json",
                    )
                content += "  '%s':\n" % n
                for m in j[1].split(","):
                    content += "    - %s\n" % m
        content += "EOF"
        os.system('''ssh %s "cat > %s/top.sls << EOF\n%s"''' % (CENTER_SERVER[i][0], master_dir, content))

    try:
        # def gevent_run_all(CENTER_SERVER,client_send_data,p,q):
        #     for i in run_target_dict.keys():
        #         for j in run_target_dict[i]:
        #             p.spawn(gevent_run,CENTER_SERVER,client_send_data,i,j[0],q)
        # def gevent_run(CENTER_SERVER,client_send_data,i,j,q):
        #     cmd_result = client_send_data(json.dumps({'salt':1,'act':'state.highstate','hosts':j,'argv':''}),CENTER_SERVER[i][0],CENTER_SERVER[i][1])
        #     cmd_result = convert_str_to_html(cmd_result)
        #     q.put(cmd_result)
        # p = Pool()
        # q = Queue()
        # p.spawn(gevent_run_all,CENTER_SERVER,client_send_data,p,q)
        # p.join()
        # for i in range(q.qsize()):
        #     cmd_result = q.get()
        #     if not cmd_results:
        #         cmd_results = cmd_result
        #     else:
        #         cmd_results = cmd_results + '<br><br><br><br>' + cmd_result

        hosts_list = []
        for i in run_target_dict.keys():
            for j in run_target_dict[i]:
                hosts_list.append(j[0])
            cmd_result = client_send_data(
                json.dumps({"salt": 1, "act": "state.highstate", "hosts": ",".join(hosts_list), "argv": ""}),
                CENTER_SERVER[i][0],
                CENTER_SERVER[i][1],
            )
            cmd_results = convert_str_to_html(cmd_result)
        return HttpResponse(
            json.dumps({"code": 0, "msg": u"模块执行完成", "cmd_results": cmd_results}), content_type="application/json"
        )
    except Exception:
        return HttpResponse(json.dumps({"code": 1, "msg": u"模块执行失败"}), content_type="application/json")
Esempio n. 4
0
 def gevent_run(CENTER_SERVER,client_send_data,i,j,q):
     cmd_result = client_send_data(json.dumps({'salt':1,'act':'state.highstate','hosts':j,'argv':''}),CENTER_SERVER[i][0],CENTER_SERVER[i][1])
     cmd_result = convert_str_to_html(cmd_result)
     q.put(cmd_result)