def ansbile_asset_hardware(ids, assets): current_process()._config = {'semprefix': '/mp'} inventory = BaseInventory(host_list=assets) runner = AdHocRunner(inventory) tasks = [ {"action": {"module": "setup", "args": ""}, "name": "script"}, ] retsult = runner.run(tasks, "all") hostname = assets[0]['hostname'] try: data = retsult.results_raw['ok'][hostname]['script']['ansible_facts'] nodename = data['ansible_nodename'] disk = "{}".format(str(sum([int(data["ansible_devices"][i]["sectors"]) * int(data["ansible_devices"][i]["sectorsize"]) / 1024 / 1024 / 1024 for i in data["ansible_devices"] if i[0:2] in ("vd", "ss", "sd")])) + str(" GB")) mem = round(data['ansible_memtotal_mb'] / 1024) cpu = int("{}".format(data['ansible_processor_count'] * data["ansible_processor_cores"])) system = data['ansible_product_name'] + "" + data['ansible_lsb']["description"] AssetInfo.objects.filter(id=ids).update(hostname=nodename, disk=disk, memory=mem, cpu=cpu, system=system) except Exception as e: logger.error(e) return e
def ansible_test(host_data, tasks): current_process()._config = {'semprefix': '/mp'} inventory = BaseInventory(host_data) runner = AdHocRunner(inventory) ret = runner.run(tasks, "all") print(ret.results_summary) print(ret.results_raw) return 'a'
def cmdjob(assets, tasks): """ :param assets: 资产帐号密码 :param tasks: 执行的命令 和 模块 :return: 执行结果 """ inventory = BaseInventory(host_list=assets) hostname = [] for i in inventory.hosts: hostname.append(i) runner = AdHocRunner(inventory) retsult = runner.run(tasks, "all") ret = None try: ok = retsult.results_raw['ok'] failed = retsult.results_raw['failed'] unreachable = retsult.results_raw['unreachable'] if not ok and not failed: ret = unreachable elif not ok: ret = failed else: ret = ok except Exception as e: logger.error("{}".format(e)) retsult_data = [] for i, element in enumerate(hostname): std, ret_host = [], {} for t in range(len(tasks)): try: out = ret[element]['task{}'.format(t)]['stdout'] err = ret[element]['task{}'.format(t)]['stderr'] std.append("{0}{1}".format(out, err)) except Exception as e: logger.error(e) try: std.append("{0} \n".format( ret[hostname[i]]['task{}'.format(t)]['msg'], t + 1)) except Exception as e: logger.error("第{0}个执行失败,此任务后面的任务未执行 {1}".format(t + 1, e)) std.append("第{0}个执行失败,此任务后面的任务未执行".format(t + 1)) ret_host['hostname'] = element ret_host['data'] = '\n'.join(std) retsult_data.append(ret_host) return retsult_data
def ThreadCmdJob(assets, tasks): """ 执行命令的线程 :param assets: 资产帐号密码 :param tasks: 执行的命令 和 模块 :return: 执行结果 """ inventory = BaseInventory(assets) runner = AdHocRunner(inventory) retsult = runner.run(tasks, "all") hostname = assets[0]['hostname'] try: """执行成功""" data = retsult.results_raw['ok'][hostname] except Exception as e: logger.error(e) try: """执行失败""" data = retsult.results_raw['failed'][hostname] except Exception as e: logger.error("连接不上 {0}".format(e)) data_fatal_msg = retsult.results_raw['unreachable'][hostname] task = [] for i in range(len(tasks)): try: """任务的返回结果 成功信息 """ task.append(data['task{}'.format(i)]['stdout']) except Exception as e: logger.error("执行失败{0}".format(e)) try: """失败信息""" task.append(retsult.results_raw['failed'][hostname][ 'task{}'.format(i)]['stderr']) except Exception as e: logger.error("执行失败{0}".format(e)) try: """连接失败""" task.append("连接失败 {0}".format( data_fatal_msg['task{}'.format(i)]['msg'])) except Exception as e: logger.error('未执行任务{0},请检查修改上面任务!!! \n {1}'.format( e, tasks)) task.append('未执行任务{0},请检查修改上面任务!!! \n \n {1}'.format( e, tasks)) ret = {'hostname': hostname, 'data': '\n'.join(task)} return ret
def TestAdHocRunner(): """ 以yml的形式 执行多个命令 :return: """ host_data = [ { "hostname": "server1", "ip": "192.168.188.200", "port": 22, "username": "******", "password": "", "private_key": '/root/.ssh/id_rsa', "become": { "method": "sudo", "user": "******", "pass": None, } }, ] inventory = BaseInventory(host_data) runner = AdHocRunner(inventory) tasks = [ { "action": { "module": "shell", "args": "echo 1 >> /tmp/1" }, "name": "run_whoami" }, ] ret = runner.run(tasks, "all") print(ret.results_summary) print(ret.results_raw)
def ansbile_tools(assets, tasks): current_process()._config = {'semprefix': '/mp'} inventory = BaseInventory(host_list=assets) hostname, retsult_data = [], [] ret = None for i in assets: hostname.append(i['hostname']) for t in tasks: if t['action']['module'] == "script": runner = AdHocRunner(inventory) t1 = [t] retsult = runner.run(t1, "all") try: ok = retsult.results_raw['ok'] failed = retsult.results_raw['failed'] unreachable = retsult.results_raw['unreachable'] if not ok and not failed: ret = unreachable elif not ok: ret = failed else: ret = ok except Exception as e: logger.error("{}".format(e)) for i in range(len(hostname)): std, ret_host = [], {} try: out = ret[hostname[i]][t['name']]['stdout'] if not out: out = ret[hostname[i]][t['name']]['stderr'] std.append("{0}".format(out)) except Exception as e: logger.error(e) try: std.append("{0}".format( ret[hostname[i]][t['name']]['msg'])) except Exception as e: logger.error("{0}执行失败{1}".format(t['name'], e)) ret_host['hostname'] = hostname[i] ret_host['data'] = ''.join(std) retsult_data.append(ret_host) elif t['action']['module'] == 'yml': runers = PlayBookRunner(playbook_path=t['action']['args'], inventory=inventory) retsult = runers.run() try: ret = retsult['results_callback'] except Exception as e: logger.error("{}".format(e)) for i in range(len(hostname)): std, ret_host = [], {} try: out = ret[hostname[i]]['stdout'] if not out: out = ret[hostname[i]]['stderr'] std.append("{0}".format(out)) except Exception as e: logger.error(e) try: std.append("{0}".format(ret[hostname[i]]['msg'])) except Exception as e: logger.error("{0}执行失败".format(e)) ret_host['hostname'] = hostname[i] ret_host['data'] = ''.join(std) retsult_data.append(ret_host) return retsult_data
def ansbile_tools_crontab(tools_name, *args): current_process()._config = {'semprefix': '/mp'} a_list, assets_list = [], [] for i in args: AssetInfo.objects.get(hostname=i) a_list.append(AssetInfo.objects.get(hostname=i)) t_obj = Tools.objects.get(name=tools_name) for i in a_list: var_all = { 'hostname': i.hostname, 'inner_ip': i.inner_ip, "network_ip": i.network_ip, "project": i.project.projects } try: var_all.update( Variable.objects.get(assets__hostname=i.hostname).vars) except Exception as e: pass assets_list.append( { "hostname": i.hostname, "ip": i.network_ip, "port": i.port, "username": i.user.username, "password": decrypt_p(i.user.password), "private_key": i.user.private_key.name, "vars": var_all, }, ) file = "data/script/{0}".format(random.randint(0, 999999)) file2 = "data/script/{0}".format(random.randint(1000000, 9999999)) tools, modules = None, None if t_obj.tool_run_type == 'shell' or t_obj.tool_run_type == 'python': with open("{}.sh".format(file), 'w+') as f: f.write(t_obj.tool_script) os.system("sed 's/\r//' {0}.sh > {1}.sh".format(file, file2)) tools = '{}.sh'.format(file2) modules = "script" elif t_obj.tool_run_type == 'yml': with open("{}.yml".format(file), 'w+') as f: f.write(t_obj.tool_script) os.system("sed 's/\r//' {0}.yml > {1}.yml".format(file, file2)) tools = '{}.yml'.format(file2) modules = "yml" inventory = BaseInventory(host_list=assets_list) hostname, retsult_data = [], [] for i in inventory.hosts: hostname.append(i) ret = None if modules == "script": runner = AdHocRunner(inventory) tasks = [ { "action": { "module": "{}".format(modules), "args": "{}".format(tools) }, "name": "script" }, ] retsult = runner.run(tasks, "all") try: ok = retsult.results_raw['ok'] failed = retsult.results_raw['failed'] unreachable = retsult.results_raw['unreachable'] if not ok and not failed: ret = unreachable elif not ok: ret = failed else: ret = ok except Exception as e: logger.error("{}".format(e)) for i, element in enumerate(hostname): std, ret_host = [], {} try: out = ret[element]['script']['stdout'] if not out: out = ret[element]['script']['stderr'] std.append("{0}".format(out)) except Exception as e: logger.error(e) try: std.append("{0}".format(ret[element]['script']['msg'])) except Exception as e: logger.error("执行失败{0}".format(e)) ret_host['hostname'] = element ret_host['data'] = ''.join(std) retsult_data.append(ret_host) elif modules == 'yml': runers = PlayBookRunner(playbook_path=tools, inventory=inventory) retsult = runers.run() try: ret = retsult['results_callback'] except Exception as e: logger.error("{}".format(e)) for i, element in enumerate(hostname): std, ret_host = [], {} try: out = ret[element]['stdout'] if not out: out = ret[element]['stderr'] std.append("{0}".format(out)) except Exception as e: logger.error(e) try: std.append("{0}".format(ret[element]['msg'])) except Exception as e: logger.error("执行失败{0}".format(e)) ret_host['hostname'] = element ret_host['data'] = ''.join(std) retsult_data.append(ret_host) return retsult_data
def post(self, request): ##命令行 ids = request.POST.getlist('id') code_id = request.POST.get('code_id', None) dest = request.POST.get('dest', None) user = User.objects.get(username=request.user) checker = ObjectPermissionChecker(user) ids1 = [] for i in ids: assets = asset.objects.get(id=i) if checker.has_perm( 'task_asset', assets, ) == True: ids1.append(i) else: error_3 = "主机没有权限" ret = {"error": error_3, "status": False} return HttpResponse(json.dumps(ret)) idstring = ','.join(ids1) if not ids: error_1 = "请选择主机" ret = {"error": error_1, "status": False} return HttpResponse(json.dumps(ret)) obj = asset.objects.extra(where=['id IN (' + idstring + ')']) ret = {'data': []} tasks = [] file = codebase.objects.get(id=code_id) for i in obj: try: assets = [ { "hostname": 'host', "ip": i.network_ip, "port": i.port, "username": i.system_user.username, "password": decrypt_p(i.system_user.password), }, ] tasks = [ { "action": { "module": "copy", "args": "src=./upload/{0} {1}".format( file.file.name, dest) }, "name": "copy_code" }, ] inventory = BaseInventory(assets) runner = AdHocRunner(inventory) retsult = runner.run(tasks, "all") ret1 = [] try: ret1.append( "分发成功 {} 备注:如果前面返回值为 false,表示已经分发完成了,请不要重复分发。". format(retsult.results_raw['ok']['host']['copy_code'] ['changed'])) except Exception as e: if retsult.results_summary['dark'] == {}: ret1.append("执行成功") else: ret1.append("命令有问题,{}".format( retsult.results_summary['dark'])) history.objects.create(ip=i.network_ip, root=i.system_user, port=i.port, cmd="上传 {} 到 {}".format( file.name, dest), user=user) ret2 = {'ip': i.network_ip, 'data': '\n'.join(ret1)} ret['data'].append(ret2) except Exception as e: ret['data'].append({ "ip": i.network_ip, "data": "账号密码不对,{}".format(e) }) return HttpResponse(json.dumps(ret))
def cmd(request): ##命令行 if request.method == "GET": obj = get_objects_for_user(request.user, 'asset.change_asset') return render(request, 'tasks/cmd.html', { 'asset_list': obj, "tasks_active": "active", "cmd_active": "active" }) if request.method == 'POST': ids = request.POST.getlist('id') args = request.POST.getlist('args', None) module = request.POST.getlist('module', None) user = User.objects.get(username=request.user) checker = ObjectPermissionChecker(user) ids1 = [] for i in ids: assets = asset.objects.get(id=i) if checker.has_perm( 'task_asset', assets, ) == True: ids1.append(i) else: error_3 = "主机没有权限" ret = {"error": error_3, "status": False} return HttpResponse(json.dumps(ret)) idstring = ','.join(ids1) if not ids: error_1 = "请选择主机" ret = {"error": error_1, "status": False} return HttpResponse(json.dumps(ret)) elif args == ['']: error_2 = "请输入命令" ret = {"error": error_2, "status": False} return HttpResponse(json.dumps(ret)) obj = asset.objects.extra(where=['id IN (' + idstring + ')']) ret = {'data': []} tasks = [] for x in range(len(module)): tasks.append( { "action": { "module": module[x], "args": args[x] }, "name": 'task{}'.format(x) }, ) for i in obj: try: assets = [ { "hostname": 'host', "ip": i.network_ip, "port": i.port, "username": i.system_user.username, "password": decrypt_p(i.system_user.password), }, ] inventory = BaseInventory(assets) runner = AdHocRunner(inventory) retsult = runner.run(tasks, "all") ret1 = [] for c in range(len(module)): try: ret1.append(retsult.results_raw['ok']['host'][ 'task{}'.format(c)]['stdout']) except Exception as e: if retsult.results_summary['dark'] == ['']: ret1.append("执行成功") else: ret1.append("命令有问题,{}".format( retsult.results_summary['dark'])) history.objects.create(ip=i.network_ip, root=i.system_user, port=i.port, cmd=args, user=user) ret2 = {'ip': i.network_ip, 'data': '\n'.join(ret1)} ret['data'].append(ret2) except Exception as e: ret['data'].append({ "ip": i.network_ip, "data": "账号密码不对,{}".format(e) }) return HttpResponse(json.dumps(ret))
def tools_script_post(request): ret = {'data': None} if request.method == 'POST': try: host_ids = request.POST.getlist('id', None) sh_id = request.POST.get('shid', None) user = request.user if not host_ids: error1 = "请选择主机" ret = {"error": error1, "status": False} return HttpResponse(json.dumps(ret)) user = User.objects.get(username=request.user) checker = ObjectPermissionChecker(user) ids1 = [] for i in host_ids: assets = asset.objects.get(id=i) if checker.has_perm( 'task_asset', assets, ) == True: ids1.append(i) else: error2 = "主机没有权限" ret = {"error": error2, "status": False} return HttpResponse(json.dumps(ret)) idstring = ','.join(ids1) host = asset.objects.extra(where=['id IN (' + idstring + ')']) sh = toolsscript.objects.filter(id=sh_id) for s in sh: if s.tool_run_type == 0: with open('tasks/script/test.sh', 'w+') as f: f.write(s.tool_script) a = 'tasks/script/{}.sh'.format(s.id) os.system( "sed 's/\r//' tasks/script/test.sh > {}".format(a)) elif s.tool_run_type == 1: with open('tasks/script/test.py', 'w+') as f: f.write(s.tool_script) p = 'tasks/script/{}.py'.format(s.id) os.system( "sed 's/\r//' tasks/script/test.py > {}".format( p)) # elif s.tool_run_type == 2: # with open('tasks/script/test.yml', 'w+') as f: # f.write(s.tool_script) # y = 'tasks/script/{}.yml'.format(s.id) # os.system("sed 's/\r//' tasks/script/test.yml > {}".format(y)) else: ret['status'] = False ret['error'] = '脚本类型错误,只能是shell、python' return HttpResponse(json.dumps(ret)) data1 = [] for h in host: try: password = decrypt_p(h.system_user.password) assets = [ { "hostname": 'host', "ip": h.network_ip, "port": h.port, "username": h.system_user.username, "password": password, }, ] history.objects.create(ip=h.network_ip, root=h.system_user.username, port=h.port, cmd=s.name, user=user) if s.tool_run_type == 0: tasks1 = [ { "action": { "module": "script", "args": "{}".format(a) }, "name": "1" }, ] elif s.tool_run_type == 1: tasks1 = [ { "action": { "module": "script", "args": "{}".format(p) }, "name": "1" }, ] inventory = BaseInventory(assets) runner = AdHocRunner(inventory) retsu = runner.run(tasks1, "all") try: data2 = { 'ip': h.network_ip, 'data': retsu.results_raw['ok']['host']['1']['stdout'] } except Exception as e: if retsu.results_summary['dark'] == ['']: data2 = {'ip': h.network_ip, 'data': "执行成功"} else: data2 = { 'ip': h.network_ip, 'data': "命令有问题,{}".format( retsu.results_summary['dark']) } data1.append(data2) except Exception as e: data2['ip'] = h.network_ip data2['data'] = "账号密码不对,或没有权限,请修改 {}, ".format(e) data1.append(data2) ret['data'] = data1 return HttpResponse(json.dumps(ret)) except Exception as e: ret['error'] = '未知错误 {}'.format(e) return HttpResponse(json.dumps(ret))
def ansbile_tools(assets, tools, modules): current_process()._config = {'semprefix': '/mp'} inventory = BaseInventory(host_list=assets) hostname, retsult_data = [], [] ret = None for i in inventory.hosts: hostname.append(i) if modules == "script": runner = AdHocRunner(inventory) tasks = [{"action": {"module": "{}".format( modules), "args": "{}".format(tools)}, "name": "script"}, ] retsult = runner.run(tasks, "all") try: ok = retsult.results_raw['ok'] failed = retsult.results_raw['failed'] unreachable = retsult.results_raw['unreachable'] if not ok and not failed: ret = unreachable elif not ok: ret = failed else: ret = ok except Exception as e: logger.error("{}".format(e)) for i, element in enumerate(hostname): std, ret_host = [], {} try: out = ret[element]['script']['stdout'] if not out: out = ret[element]['script']['stderr'] std.append("{0}".format(out)) except Exception as e: logger.error(e) try: std.append("{0}".format(ret[element]['script']['msg'])) except Exception as e: logger.error("执行失败{0}".format(e)) ret_host['hostname'] = element ret_host['data'] = ''.join(std) retsult_data.append(ret_host) elif modules == 'yml': runers = PlayBookRunner(playbook_path=tools, inventory=inventory) retsult = runers.run() try: ret = retsult['results_callback'] except Exception as e: logger.error("{}".format(e)) for i, element in enumerate(hostname): std, ret_host = [], {} try: out = ret[element]['stdout'] if not out: out = ret[element]['stderr'] std.append("{0}".format(out)) except Exception as e: logger.error(e) try: std.append("{0}".format(ret[element]['msg'])) except Exception as e: logger.error("执行失败{0}".format(e)) ret_host['hostname'] = element ret_host['data'] = ''.join(std) retsult_data.append(ret_host) return retsult_data
def asset_hardware_update(request): ret = {'status': True, 'error': None, 'data': None} if request.method == 'POST': try: id = request.POST.get('nid', None) obj = asset.objects.get(id=id) ip = obj.network_ip port = obj.port username = obj.system_user.username password1 = obj.system_user.password password = decrypt_p(password1) assets = [ { "hostname": 'host', "ip": ip, "port": port, "username": username, "password": password, }, ] inventory = BaseInventory(assets) runner = AdHocRunner(inventory) tasks = [ { "action": { "module": "setup", "args": "" }, "name": "setup" }, ] result = runner.run(tasks, "all") data = result.results_raw['ok']['host']['setup']['ansible_facts'] hostname = data['ansible_nodename'] system = data['ansible_distribution'] + " " + data[ 'ansible_distribution_version'] try: a2 = "parted -l | grep \"Disk \/dev\/[a-z]d\" | awk -F\"[ ]\" '{print $3}' | awk -F\"GB\" '{print $1}'" s = ssh(ip=ip, port=port, username=username, password=password, cmd=a2) disk1 = s['data'] disk2 = disk1.rstrip().split("\n") disk = "+".join(map(str, disk2)) + " 共计:{} GB".format( round(sum(map(float, disk2)))) except Exception as e: disk = " 共计{}".format(str(sum([int(data["ansible_devices"][i]["sectors"]) * \ int(data["ansible_devices"][i]["sectorsize"]) / 1024 / 1024 / 1024 \ for i in data["ansible_devices"] if i[0:2] in ("vd", "ss", "sd")])) + str(" GB")) try: a1 = "dmidecode | grep -P -A5 \"Memory\ Device\" | grep Size | grep -v \"No Module Installed\" | grep -v \"0\" | awk -F\":\" \'{print $2}\' | awk -F\" \" \'{print $1}\'" s = ssh(ip=ip, port=port, username=username, password=password, cmd=a1) memory1 = s['data'] if memory1 == "": memory0 = [] memory0.append( int(round((data['ansible_memtotal_mb']) / 1000))) else: memory2 = memory1.rstrip().split("\n") memory0 = [] for i in range(len(memory2)): memory0.append((int(int(memory2[i]) / 1024))) memory = "+".join(map(str, memory0)) + ' 共计:{} GB'.format( (sum(map(int, memory0)))) except Exception as e: memory = ' 共计:{} GB'.format( round((data['ansible_memtotal_mb'] / 1000))) sn = data['ansible_product_serial'] model = data["ansible_system_vendor"] + " " + data[ 'ansible_product_name'] cpu = data['ansible_processor'][1] + " {}核心".format( data['ansible_processor_count'] * data["ansible_processor_cores"]) try: a = "ipmitool lan print | grep -w \"IP Address \" | awk -F\":\" \ '{print $2}\'" s = ssh(ip=ip, port=port, username=username, password=password, cmd=a) manage = s['data'] except Exception as e: manage = None net = data["ansible_interfaces"][1:] net.sort() try: eth0 = data['ansible_{}'.format(net[0])]['macaddress'] except Exception as e: eth0 = None try: eth1 = data['ansible_{}'.format(net[1])]['macaddress'] except Exception as e: eth1 = None try: eth2 = data['ansible_{}'.format(net[2])]['macaddress'] except Exception as e: eth2 = None try: eth3 = data['ansible_{}'.format(net[3])]['macaddress'] except Exception as e: eth3 = None ass = asset.objects.filter(id=id).first() ass.hostname = hostname ass.manage_ip = manage ass.system = system ass.memory = memory ass.disk = disk ass.sn = sn ass.model = model ass.cpu = cpu ass.eth0 = eth0 ass.eth1 = eth1 ass.eth2 = eth2 ass.eth3 = eth3 ass.save() except Exception as e: ret['status'] = False ret['error'] = '登陆账号权限不够| 请在被添加的主机安装 parted ipmitool dmidecode | 或者 删除 主服务器/root/.ssh/known_hosts 文件'.format( e) return HttpResponse(json.dumps(ret))