Exemple #1
0
def wssh(request, sid):
    try:
        server = Network_Assets.objects.get(assets_id=sid)
        if request.user.is_superuser:
            serverList = Network_Assets.objects.all()
            return render(request, 'webssh/webssh.html', {
                "user": request.user,
                "server": server,
                "serverList": serverList
            })
        else:
            user_server = Network_Assets.objects.get(user_id=request.user.id,
                                                     server_id=sid)
            userServer = Network_Assets.objects.filter(user_id=request.user.id)
            serverList = []
            for s in userServer:
                ser = Network_Assets.objects.get(id=s.server_id)
                serverList.append(ser)
            if user_server:
                return render(
                    request, 'webssh/webssh.html', {
                        "user": request.user,
                        "server": server,
                        "serverList": serverList
                    })
    except Exception as ex:
        logger.error(msg="请求webssh失败: {ex}".format(ex=str(ex)))
        return render(request, 'webssh/webssh.html', {
            "user": request.user,
            "errorInfo": "你没有权限访问这台服务器!"
        })
Exemple #2
0
 def disconnect(self,message,**kwargs):
     try:
         user = User.objects.get(username=self.message.user)
     except Exception as ex:
         logger.error(msg="webssh获取用户[{user}]信息失败: {ex}".format(user=self.message.user,ex=str(ex)))
         pass
     Group(user.username).discard(message.reply_channel)    
Exemple #3
0
def assets_delete(request):
	if request.method == "POST":
		fList = []
		sList = []
		for ast in request.POST.getlist('assetsIds[]'):
			try:
				assets = Assets.objects.get(id=int(ast))
			except Exception as ex:
				logger.error(msg="删除资产失败: {ex}".format(ex=ex))
				continue
			if assets.assets_type in ['vmser', 'server']:
				try:
					server_assets = Server_Assets.objects.get(assets=assets)
				except Exception as ex:
					fList.append(assets.management_ip)
					assets.delete()
					continue
				sList.append(server_assets.ip)
				server_assets.delete()
			else:
				try:
					net_assets = Network_Assets.objects.get(assets=assets)
				except Exception as ex:
					fList.append(assets.management_ip)
					assets.delete()
					continue
				sList.append(assets.management_ip)
				net_assets.delete()
			assets.delete()
		return JsonResponse({'msg': "数据删除成功", "code": 200, 'data': {"success": sList, "failed": fList}})
Exemple #4
0
def assets_modf(request, aid):
	if request.method == 'GET':
		try:
			assets = Assets.objects.get(id=aid)
			userList = User.objects.all()
		except:
			return render(request, 'assets/assets_modf.html', {"user": request.user},
						  )
		if assets.assets_type in ['server', 'vmser']:
			try:
				asset_body = assets.server_assets
			except Exception as ex:
				logger.error(msg="修改资产失败: {ex}".format(ex=str(ex)))
				return render(request, '404.html', {"user": request.user},
							  )
			return render(request, 'assets/assets_modf.html', {"user": request.user, "asset_type": assets.assets_type,
															   "asset_main": assets, "asset_body": asset_body,
															   "assets_data": getBaseAssets(), 'userList': userList},
						  )
		else:
			try:
				asset_body = assets.network_assets
			except:
				return render(request, 'assets/assets_modf.html', {"user": request.user},
							  )
			return render(request, 'assets/assets_modf.html', {"user": request.user, "asset_type": assets.assets_type,
															   "asset_main": assets, "asset_body": asset_body,
															   "assets_data": getBaseAssets(), 'userList': userList},
						  )
	elif request.method == 'POST':
		assets_type = json.loads(request.body)['assets_type']
		asset = json.loads(request.body)['data']['assets']
		dic = json.loads(request.body)['data']
		del dic['assets']
		del asset['name']
		del asset['id']
		del asset['assets_type']
		del asset['sn']
		try:
			Assets.objects.filter(id=aid).update(**asset)
		except Exception as ex:
			logger.debug(msg=ex)
			return JsonResponse({'msg': "修改失败~", "code": '502'})
		if assets_type == 'server':
			try:
				Server_Assets.objects.filter(assets_id=aid).update(**dic)
			except Exception as ex:
				logger.debug(msg=ex)
				return JsonResponse({'msg': "修改失败~", "code": '502'})
			return JsonResponse({'msg': "修改成功~", "code": '502'})
		elif assets_type == 'net':
			try:
				Network_Assets.objects.filter(assets_id=aid).update(**dic)
			except Exception as ex:
				logger.debug(msg=ex)
				return JsonResponse({'msg': "修改失败~", "code": '502'})
			return JsonResponse({'msg': "修改成功~", "code": '502'})
Exemple #5
0
def getFileType(filePath):
    try:
        files = magic.Magic(uncompress=True,mime=True)
        file_type = files.from_file(filePath)
    except Exception as ex:
        file_type = '未知'
        logger.error("获取文件类型失败: {ex}".format(ex=ex))
    return file_type
    
Exemple #6
0
 def new_ssh_connect(self):
     self.client = paramiko.SSHClient()
     self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
     try:
         self.client.connect(self.ip,
                             self.port,
                             self.user,
                             self.password,
                             timeout=5)
         self.ssh_connect = self.client.invoke_shell()
     except Exception as e:
         logger.error("设备%s登陆失败,失败原因:%s", self.hostname, e)
         exit()
Exemple #7
0
    def connect(self,message,**kwargs):
        try:
            username = message['path'].strip('/').split('/')[-1]
        except Exception as ex:
            message.reply_channel.send({"accept":False}) 
            logger.error(msg="webssh连接失败: {ex}".format(ex=str(ex)))     
        try:
            user = User.objects.get(username=self.message.user)  
        except Exception as ex:
            message.reply_channel.send({"accept":False}) 

        if str(self.message.user) == str(username):
            message.reply_channel.send({'accept': True})
            Group(user.username).add(message.reply_channel)
Exemple #8
0
    def conf_bak(self):

        self.new_ssh_connect()
        time.sleep(1)
        out = self.ssh_connect.recv(1024).decode()
        #fencoding = chardet.detect(out)
        date = datetime.datetime.now().strftime("%Y%m%d")
        filename = self.hostname + "-" + date + ".cfg"
        cmd = "backup startup-configuration to 10.16.17.100 " + filename
        self.ssh_connect.send("\n")
        time.sleep(1)
        self.ssh_connect.send(cmd + "\n")
        time.sleep(5)
        out = self.ssh_connect.recv(65535).decode()
        if 'Finished.' or 'finished!' in out:
            logger.info("%s 备份成功", self.hostname)
        else:
            logger.error("%s 备份失败", self.hostname)
        self.del_ssh_connect()
Exemple #9
0
def assets_facts(request, args=None):
	if request.method == "POST" and request.user.has_perm('OpsManage.change_server_assets'):
		server_id = request.POST.get('server_id')
		genre = request.POST.get('type')
		if genre == 'setup':
			try:
				server_assets = Server_Assets.objects.get(id=request.POST.get('server_id'))
				if server_assets.keyfile == 1:
					resource = [
						{"ip": server_assets.ip, "port": int(server_assets.port), "username": server_assets.username,
						 "sudo_passwd": server_assets.sudo_passwd}]
				else:
					resource = [{"ip": server_assets.ip, "port": server_assets.port, "username": server_assets.username,
								 "password": server_assets.passwd, "sudo_passwd": server_assets.sudo_passwd}]
			except Exception as ex:
				logger.error(msg="更新资产失败: {ex}".format(ex=str(ex)))
				return JsonResponse({'msg': "数据更新失败-查询不到该主机资料~", "code": 502})
			ANS = ANSRunner(resource)
			ANS.run_model(host_list=[server_assets.ip], module_name='setup', module_args="")
			data = ANS.handle_cmdb_data(ANS.get_model_result())
			if data:
				for ds in data:
					status = ds.get('status')
					if status == 0:
						try:
							assets = Assets.objects.get(id=server_assets.assets_id)
							Assets.objects.filter(id=server_assets.assets_id).update(sn=ds.get('serial'),
																					 model=ds.get('model'),
																					 manufacturer=ds.get(
																						 'manufacturer'))
						except Exception as ex:
							logger.error(msg="获取服务器信息失败: {ex}".format(ex=str(ex)))
							return JsonResponse({'msg': "数据更新失败-查询不到该主机的资产信息", "code": 403})
						try:
							Server_Assets.objects.filter(id=server_id).update(cpu_number=ds.get('cpu_number'),
																			  kernel=ds.get('kernel'),
																			  selinux=ds.get('selinux'),
																			  hostname=ds.get('hostname'),
																			  system=ds.get('system'),
																			  cpu=ds.get('cpu'),
																			  disk_total=ds.get('disk_total'),
																			  cpu_core=ds.get('cpu_core'),
																			  swap=ds.get('swap'),
																			  ram_total=ds.get('ram_total'),
																			  vcpu_number=ds.get('vcpu_number')
																			  )
							recordAssets.delay(user=str(request.user),
											   content="修改服务器资产:{ip}".format(ip=server_assets.ip), type="server",
											   id=server_assets.id)
						except Exception as ex:
							logger.error(msg="更新服务器信息失败: {ex}".format(ex=str(ex)))
							return JsonResponse({'msg': "数据更新失败-写入数据失败", "code": 400})
						for nk in ds.get('nks'):
							macaddress = nk.get('macaddress')
							count = NetworkCard_Assets.objects.filter(assets=assets, macaddress=macaddress).count()
							if count > 0:
								try:
									NetworkCard_Assets.objects.filter(assets=assets, macaddress=macaddress).update(
										assets=assets, device=nk.get('device'),
										ip=nk.get('address'), module=nk.get('module'),
										mtu=nk.get('mtu'), active=nk.get('active'))
								except Exception as ex:
									logger.warn(msg="更新服务器网卡信息失败: {ex}".format(ex=str(ex)))
							else:
								try:
									NetworkCard_Assets.objects.create(assets=assets, device=nk.get('device'),
																	  macaddress=nk.get('macaddress'),
																	  ip=nk.get('address'), module=nk.get('module'),
																	  mtu=nk.get('mtu'), active=nk.get('active'))
								except Exception as ex:
									logger.warn(msg="写入服务器网卡信息失败: {ex}".format(ex=str(ex)))

					else:
						return JsonResponse({'msg': "数据更新失败-无法链接主机~", "code": 502})
				return JsonResponse({'msg': "数据更新成功", "code": 200})
			else:
				return JsonResponse({'msg': "数据更新失败-请检查Ansible配置", "code": 400})

		elif genre == 'crawHw':
			try:
				server_assets = Server_Assets.objects.get(id=server_id)
				assets = Assets.objects.get(id=server_assets.assets_id)
				if server_assets.keyfile == 1:
					resource = [
						{"ip": server_assets.ip, "port": int(server_assets.port), "username": server_assets.username,
						 "sudo_passwd": server_assets.sudo_passwd}]
				else:
					resource = [{"ip": server_assets.ip, "port": server_assets.port, "username": server_assets.username,
								 "password": server_assets.passwd, "sudo_passwd": server_assets.sudo_passwd}]
			except Exception as e:
				logger.error(msg="更新硬件信息失败: {ex}".format(ex=ex))
				return JsonResponse({'msg': "数据更新失败-查询不到该主机资料~", "code": 502})
			ANS = ANSRunner(resource)
			ANS.run_model(host_list=[server_assets.ip], module_name='crawHw', module_args="")
			data = ANS.handle_cmdb_crawHw_data(ANS.get_model_result())
			if data:
				for ds in data:
					if ds.get('mem_info'):
						for mem in ds.get('mem_info'):
							if Ram_Assets.objects.filter(assets=assets, device_slot=mem.get('slot')).count() > 0:
								try:
									Ram_Assets.objects.filter(assets=assets, device_slot=mem.get('slot')).update(
										device_slot=mem.get('slot'), device_model=mem.get('serial'),
										device_brand=mem.get('manufacturer'), device_volume=mem.get('size'),
										device_status="Online"
									)

								except Exception as ex:
									return JsonResponse({'msg': "数据更新失败-写入数据失败", "code": 400})
							else:
								try:
									Ram_Assets.objects.create(device_slot=mem.get('slot'),
															  device_model=mem.get('serial'),
															  device_brand=mem.get('manufacturer'),
															  device_volume=mem.get('size'),
															  device_status="Online", assets=assets
															  )
									recordAssets.delay(user=str(request.user),
													   content="修改服务器资产:{ip}".format(ip=server_assets.ip),
													   type="server", id=server_assets.id)
								except Exception as e:
									return JsonResponse({'msg': "数据更新失败-写入数据失败", "code": 400})
					if ds.get('disk_info'):
						for disk in ds.get('disk_info'):
							if Disk_Assets.objects.filter(assets=assets, device_slot=disk.get('slot')).count() > 0:
								try:
									Disk_Assets.objects.filter(assets=assets, device_slot=disk.get('slot')).update(
										device_serial=disk.get('serial'), device_model=disk.get('model'),
										device_brand=disk.get('manufacturer'), device_volume=disk.get('size'),
										device_status="Online"
									)

								except Exception as e:
									return JsonResponse({'msg': "数据更新失败-写入数据失败", "code": 400})
							else:
								try:
									Disk_Assets.objects.create(device_serial=disk.get('serial'),
															   device_model=disk.get('model'),
															   device_brand=disk.get('manufacturer'),
															   device_volume=disk.get('size'),
															   device_status="Online", assets=assets,
															   device_slot=disk.get('slot')
															   )
									recordAssets.delay(user=str(request.user),
													   content="修改服务器资产:{ip}".format(ip=server_assets.ip),
													   type="server", id=server_assets.id)
								except Exception as e:
									return JsonResponse({'msg': "数据更新失败-写入数据失败", "code": 400})

				return JsonResponse({'msg': "数据更新成功", "code": 200})
			else:
				return JsonResponse({'msg': "数据更新失败,系统可能不支持,未能获取数据", "code": 400})

	else:
		return JsonResponse({'msg': "您没有该项操作的权限~", "code": 400})