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 password = obj.system_user.password assets = [ { "hostname": 'host', "ip": ip, "port": port, "username": username, "password": password, }, ] task_tuple = (('setup', ''), ) runner = AdHocRunner(assets) result = runner.run(task_tuple=task_tuple, pattern='all', task_name='Ansible Ad-hoc') data = result['contacted']['host'][0]['ansible_facts'] hostname = data['ansible_nodename'] system = data['ansible_distribution'] + " " + data[ 'ansible_distribution_version'] disk = 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") memory = '{} MB'.format(data['ansible_memtotal_mb']) sn = data['ansible_product_serial'] model = data['ansible_product_name'] cpu = data['ansible_processor'][1] + " {}核".format( data['ansible_processor_count']) ass = asset.objects.filter(id=id).update(hostname=hostname, system=system, memory=memory, disk=disk, sn=sn, model=model, cpu=cpu) except Exception as e: ret['status'] = False ret['error'] = '硬件更新错误{}'.format(e) return HttpResponse(json.dumps(ret))
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, }, ] task_tuple = (('setup', ''), ) runner = AdHocRunner(assets) result = runner.run(task_tuple=task_tuple, pattern='all', task_name='Ansible Ad-hoc') data = result['contacted']['host'][0]['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))
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( 'delete_asset', assets, ) == True: ids1.append(i) 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、yml、python' return HttpResponse(json.dumps(ret)) data1 = [] for h in host: try: data2 = {} assets = [ { "hostname": h.hostname, "ip": h.network_ip, "port": h.port, "username": h.system_user.username, "password": h.system_user.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: task_tuple = (('script', a), ) hoc = AdHocRunner(hosts=assets) hoc.results_callback = CommandResultCallback() r = hoc.run(task_tuple) data2['ip'] = h.network_ip data2['data'] = r['contacted'][ h.hostname]['stdout'] data1.append(data2) elif s.tool_run_type == 1: task_tuple = (('script', p), ) hoc = AdHocRunner(hosts=assets) hoc.results_callback = CommandResultCallback() r = hoc.run(task_tuple) data2['ip'] = h.network_ip data2['data'] = r['contacted'][ h.hostname]['stdout'] data1.append(data2) elif s.tool_run_type == 2: play = PlayBookRunner(assets, playbook_path=y) b = play.run() data2['ip'] = h.network_ip data2['data'] = b['plays'][0]['tasks'][1]['hosts'][h.hostname]['stdout'] + \ b['plays'][0]['tasks'][1]['hosts'][h.hostname]['stderr'] data1.append(data2) else: data2['ip'] = "脚本类型错误" data2['data'] = "脚本类型错误" 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 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 password = obj.system_user.password assets = [ { "hostname": 'host', "ip": ip, "port": port, "username": username, "password": password, }, ] try: a2 = "fdisk -l | grep \"Disk /dev/[a-z]d\" | awk -F\"[ ]\" \'{print $3}\'" s = ssh(ip=ip, port=port, username=username, password=password, cmd=a2) disk1 = s['data'] disk2 = disk1.rstrip().split("\n") except Exception as e: disk2 = None task_tuple = (('setup', ''), ) runner = AdHocRunner(assets) result = runner.run(task_tuple=task_tuple, pattern='all', task_name='Ansible Ad-hoc') data = result['contacted']['host'][0]['ansible_facts'] hostname = data['ansible_nodename'] system = data['ansible_distribution'] + " " + data[ 'ansible_distribution_version'] # disk = "+".join(map(str, disk2)) + " 共计{}".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")) disk = "+".join(map(str, disk2)) + " 共计:{} GB".format( round(sum(map(float, disk2)))) try: a1 = "dmidecode | grep -P -A5 \"Memory\s+Device\" | grep Size | grep -v \"No Module Installed\" | 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))) except Exception as e: memory0 = None memory = "+".join(map(str, memory0)) + ' 共计:{} GB'.format( (sum(map(int, memory0)))) 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 = "请安装ipmitool" try: if data['ansible_eth0']: eth0 = data['ansible_eth0']['macaddress'] except Exception as e: eth0 = None try: if data['ansible_eth1']: eth1 = data['ansible_eth1']['macaddress'] except Exception as e: eth1 = None try: if data['ansible_eth2']: eth2 = data['ansible_eth2']['macaddress'] except Exception as e: eth2 = None try: if data['ansible_eth3']: eth3 = data['ansible_eth3']['macaddress'] except Exception as e: eth3 = None ass = asset.objects.filter(id=id).update(hostname=hostname, manage_ip=manage, system=system, memory=memory, disk=disk, sn=sn, model=model, cpu=cpu, eth0=eth0, eth1=eth1, eth2=eth2, eth3=eth3) except Exception as e: ret['status'] = False ret['error'] = '硬件更新错误{}'.format(e) return HttpResponse(json.dumps(ret))
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 password = obj.system_user.password assets = [ { "hostname": 'host', "ip": ip, "port": port, "username": username, "password": password, }, ] task_tuple = (('setup', ''),) runner = AdHocRunner(assets) result = runner.run(task_tuple=task_tuple, pattern='all', task_name='Ansible Ad-hoc') data = result['contacted']['host'][0]['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'] eth1 = data['ansible_{}'.format(net[1])]['macaddress'] eth2 = data['ansible_{}'.format(net[2])]['macaddress'] eth3 = data['ansible_{}'.format(net[3])]['macaddress'] except Exception as e: eth0,eth1,eth2,eth3 = None,None,None,None ass = asset.objects.filter(id=id).update(hostname=hostname, manage_ip=manage, system=system, memory=memory,disk=disk, sn=sn, model=model, cpu=cpu, eth0=eth0,eth1=eth1,eth2=eth2,eth3=eth3) except Exception as e: ret['status'] = False ret['error'] = '登陆账号权限不够,请在被添加的主机安装parted ipmitool dmidecode 或更新错误{}'.format(e) return HttpResponse(json.dumps(ret))