Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/jsf/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python将对象列表与查询集进行比较,以获得两个匹配值?_Python_Django - Fatal编程技术网

Python将对象列表与查询集进行比较,以获得两个匹配值?

Python将对象列表与查询集进行比较,以获得两个匹配值?,python,django,Python,Django,我已经创建了保存我的实时VPN数据的对象列表。我也有VPN数据存储在数据库中 我希望能够将实时数据对象列表与数据库进行比较,如果数据匹配,则执行“某些操作” 如果一个对象是anyconnect,则用户名将与数据库匹配;如果一个对象是site-to-site,则对等对象将与BD匹配 我需要浏览对象列表并找到匹配项 基本上,我所做的是将实时数据与数据库数据进行比较,如果在数据库中找到了实时数据,我将更新数据库记录,说服务是“向上的”,如果找不到,服务将是“向下的” 有谁能为我指出实现这一目标的正确方

我已经创建了保存我的实时VPN数据的对象列表。我也有VPN数据存储在数据库中

我希望能够将实时数据对象列表与数据库进行比较,如果数据匹配,则执行“某些操作”

如果一个对象是anyconnect,则用户名将与数据库匹配;如果一个对象是site-to-site,则对等对象将与BD匹配

我需要浏览对象列表并找到匹配项

基本上,我所做的是将实时数据与数据库数据进行比较,如果在数据库中找到了实时数据,我将更新数据库记录,说服务是“向上的”,如果找不到,服务将是“向下的”

有谁能为我指出实现这一目标的正确方向吗

编辑:

实时数据列表

>>> for i in active_vpns:
...  print('username: {} peer_ip: {}'.format(i.username,i.peer_ip))
username: remote_vpn.user1: 1.2.3.4
username:  peer_ip: 1.1.1.1
username:  peer_ip: 2.2.2.2
username:  peer_ip: 3.3.3.3
数据库数据列表

>>> vpn_services = ThirdPartyService.objects.all()
>>>  for i in vpn_services:
...  print('username: {} peer_ip: {}'.format(i.username,i.peer_ip))
username: remote_vpn.user1: 1.2.3.4
username: remote_vpn.user2: 1.2.3.5
username:  peer_ip: 1.1.1.1
username:  peer_ip: 2.2.2.2
username:  peer_ip: 3.3.3.3
username:  peer_ip: 4.4.4.4
现在在这个例子中,我想将peer_ip 4.4.4.4设置为Down,将remote_vpn.user2设置为Down,并将其余服务设置为Up

完整代码:

#!/usr/bin/env python
from django_setup import setup
setup()
import re
import ipaddress
from netmiko import ConnectHandler
from monitoring.models import ThirdPartyService
from datetime import datetime

class VPNData(object):
    def __init__(self, service_name='', username='', vpn_peer_ip='', duration='', data_transmit='', data_receive='', timestamp=''):
        self.service_name = service_name
        self.username = username
        self.vpn_peer_ip = vpn_peer_ip
        self.duration = duration
        self.data_transmit = data_transmit
        self.data_receive = data_receive
        self.timestamp = timestamp
    def __repr__(self):
        return '{} {}'.format(self.__class__.__name__, self.username)   

def to_megabytes(bytes, bsize=1024):
    r = float(bytes)
    for i in range(2):
        r = r / bsize
    return round(r)

#creds for logging on to devices
username = 'monitoring'
password = '*******'
device_ip = '10.10.10.10'

# firewall conenction details
firewall = {
        'device_type': 'cisco_asa',
        'ip':   device_ip,
        'username': username,
        'password': password,
        'port' : 22,        # optional, defaults to 22
        'secret': '',       # optional, defaults to ''
        'verbose': False,   # optional, defaults to False
    }  
# connect to firewall
conn_fw = ConnectHandler(**firewall)
# get anyconnect sessions
anyconnect_connections = conn_fw.send_command('show vpn-sessiondb anyconnect')  
# get site to site vpn sessions
s2s_connections = conn_fw.send_command('show vpn-sessiondb l2l')  
# disconnect ssh session
conn_fw.disconnect()

active_vpns =[]
# create list of anyconnect sessions
anyconnect_sessions = re.findall(r'(?s)(?<=Username     :)(.*?)(?=Security Grp)', anyconnect_connections, flags=re.S)
# process anyconnect sessions
for ac_sess in anyconnect_sessions:
    # create object for data    
    vpn = VPNData()
    # get username
    username = re.findall(r'(?s).*?(?=Index)', ac_sess, flags=re.S)
    vpn.username = username[0].strip()
    # get peer ip
    peer_ip = re.findall(r'(?s)(?<=Public IP    : )(.*?)(?=Protocol)', ac_sess, flags=re.S)
    vpn.peer_ip = peer_ip[0].strip()
    # get duration
    duration = re.findall(r'(?s)(?<=Duration     : )(.*?)(?=Inactivity)', ac_sess, flags=re.S)
    vpn.duration = duration[0].strip()
    # transmit bytes
    data_transmit = re.findall(r'(?s)(?<=Bytes Tx     : )(.*?)(?=Bytes Rx)', ac_sess, flags=re.S)
    vpn.data_transmit = data_transmit[0].strip()
    # receive bytes
    data_receive = re.findall(r'(?s)(?<=Bytes Rx     : )(.*?)(?=Group Policy)', ac_sess, flags=re.S)
    vpn.data_receive = data_receive[0].strip()
    # Add VPN to List
    active_vpns.append(vpn)

# Add extra string to get the last connection
s2s_connections += 'Connection'
# create list of sie to site vpn sessions
s2s_sessions = re.findall(r'(?s)(?<=Connection   :)(.*?)(?=Connection)', s2s_connections, flags=re.S)
# process site to site sessions
for s2s_sess in s2s_sessions:
    # create object for data
    vpn = VPNData()
    # get peer ip
    peer_ip = re.findall(r'(?s).*?(?=Index)', s2s_sess, flags=re.S)
    vpn.peer_ip = peer_ip[0].strip()
    # get duration
    duration = re.findall(r'(?s)(?<=Duration     : ).*', s2s_sess, flags=re.S)
    vpn.duration = duration[0].strip()
    # transmit bytes
    data_transmit = re.findall(r'(?s)(?<=Bytes Tx     : )(.*?)(?=Bytes Rx)', s2s_sess, flags=re.S)
    vpn.data_transmit = data_transmit[0].strip()
    # receive bytes
    data_receive = re.findall(r'(?s)(?<=Bytes Rx     : )(.*?)(?=Login Time)', s2s_sess, flags=re.S)
    vpn.data_receive = data_receive[0].strip()
    active_vpns.append(vpn)

# get list of VPNs from DB
vpn_services = ThirdPartyService.objects.all()
for service in vpn_services:


    vpn_data = ThirdPartyService.objects.update_or_create(
            defaults={
                'service_name' : 'anyconnect',
                'username' : username,
                'vpn_peer_ip' : peer_ip,
                'duration' : duration,
                'data_transmit' : to_megabytes(data_transmit),
                'data_receive' : to_megabytes(data_receive),
                'timestamp' : datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                },
            service_name = 'anyconnect',
            username = username
        )




print('{0} Script Completed'.format(datetime.now().strftime('%d-%m-%Y %H:%M:%S')))
#/usr/bin/env python
从django_安装程序导入安装程序
设置()
进口稀土
导入IP地址
从netmiko导入ConnectHandler
从monitoring.models导入第三方服务
从日期时间导入日期时间
VPNData类(对象):
def uuuu init uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
self.service\u name=服务\u name
self.username=用户名
self.vpn\u peer\u ip=vpn\u peer\u ip
self.duration=持续时间
self.data_transmit=数据_transmit
self.data\u receive=数据\u receive
self.timestamp=时间戳
定义报告(自我):
返回{}{}.格式(self.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
def至_兆字节(字节,bsize=1024):
r=浮点(字节)
对于范围(2)中的i:
r=r/b尺寸
返回轮(r)
#登录到设备的凭据
用户名='monitoring'
密码='********'
设备ip='10.10.10.10'
#防火墙配置详细信息
防火墙={
“设备类型”:“思科asa”,
“ip”:设备\u ip,
“用户名”:用户名,
“密码”:密码,
“端口”:22,可选,默认为22
“秘密”:“”,可选,默认为“”
“verbose”:False,#可选,默认为False
}  
#连接到防火墙
conn_fw=ConnectHandler(**防火墙)
#获取任意连接会话
anyconnect\u connections=conn\u fw.send\u命令('show vpn sessiondb anyconnect')
#获取站点到站点vpn会话
s2s_connections=conn_fw.send_命令('show vpn sessiondb l2l')
#断开ssh会话
断开连接()
活动的虚拟专用网络=[]
#创建任意连接会话的列表

anyconnect_sessions=re.findall(r’(?s)(?我会从数据库条目构建一个
dict
set
,然后使用它来测试活动连接

比如:

db_peer_ips = set(ThirdPartyService.objects.values_list('peer_ip', flat=True))
for i in active_vpns:
     status = 'Up' if i.peer_ip in db_peer_ips else 'Down'
     print('username: {} peer_ip: {} status: {}'.format(i.username, i.peer_ip, status))

“你能提取出代码的相关部分吗?”唐试图把它弄清楚,希望这更有意义