def job(id): ##计划任务 i = asset.objects.filter(id=id).first() print(i.network_ip, i.port, i.system_user.username, i.system_user.password) cpu1 = ssh(ip=i.network_ip, port=i.port, username=i.system_user.username, password=i.system_user.password, cmd=" top -bn 1 -i -c | grep Cpu ") cpu2 = cpu1['data'].split() cpu3 = cpu2[1].split('%') cpu = cpu3[0] total = ssh(ip=i.network_ip, port=i.port, username=i.system_user.username, password=i.system_user.password, cmd=" free | grep Mem: ") list = total['data'].split(" ") while '' in list: list.remove('') mem = float('%.2f' % (float('%.3f' % (int(list[2]) / int(list[1]))) * 100)) in1 = ssh(ip=i.network_ip, port=i.port, username=i.system_user.username, password=i.system_user.password, cmd="cat /proc/net/dev | grep eth0 ") in2 = in1['data'].split() time.sleep(1) in3 = ssh(ip=i.network_ip, port=i.port, username=i.system_user.username, password=i.system_user.password,cmd="cat /proc/net/dev | grep eth0 ") in4 = in3['data'].split() in_network = int((int(in4[1]) - int(in2[1]))/1024/10*8) out_network = int((int(in4[9]) - int(in2[9]))/1024/10*8) performance.objects.create(server_id=i.id, cpu_use=cpu, mem_use=mem,in_use=in_network,out_use=out_network)
def asset_performance(request, nid): try: i = asset.objects.get(id=nid) cpu_1 = ssh(ip=i.network_ip, port=i.port, username=i.system_user.username, password=i.system_user.password, cmd=" top -bn 1 -i -c | grep Cpu ") cpu_2 = cpu_1['data'].split() cpu = cpu_2[1].split('%')[0] total = ssh(ip=i.network_ip, port=i.port, username=i.system_user.username, password=i.system_user.password, cmd=" free | grep Mem: ") list = total['data'].split(" ") while '' in list: list.remove('') mem = float('%.2f' % (float('%.3f' % (int(list[2]) / int(list[1]))) * 100)) all = performance.objects.all() date, cpu_use, mem_use, in_use, out_use = [], [], [], [], [] for i in all: if i.server_id == int(nid): date.append(i.cdate.strftime("%m-%d %H:%M")) cpu_use.append(i.cpu_use) mem_use.append(i.mem_use) in_use.append(i.in_use) out_use.append(i.out_use) return render( request, 'asset/asset-performance.html', { 'cpu': cpu, 'mem': mem, "asset_id": id, 'date': date, 'cpu_use': cpu_use, 'mem_use': mem_use, 'in_use': in_use, 'out_use': out_use, "asset_active": "active", "asset_list_active": "active" }) except Exception as e: obj = asset.objects.all() error = "错误,{}".format(e) return render( request, 'asset/asset.html', { 'asset_list': obj, "asset_active": "active", "asset_list_active": "active", "error_performance": error })
def cmd_job(host,cmd): i = asset.objects.get(network_ip=host) password = decrypt_p(i.system_user.password) cmd=cmd ret = ssh(ip=i.ip, port=i.port, username=i.username, password=password, cmd=cmd) return ret['data']
def cmd_job(host, cmd): i = asset.objects.get(network_ip=host) cmd = cmd ret = ssh(ip=i.ip, port=i.port, username=i.username, password=i.password, cmd=cmd) return ret['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, }, ] 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 cmd_job(host,cmd): i = asset.objects.get(network_ip=host) cmd=cmd ret = ssh(ip=i.ip, port=i.port, username=i.username, password=i.password, cmd=cmd) return ret['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 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))