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

时间:2017-09-07 12:12:40

标签: python django

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

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

如果一个对象是anyconnect,那么用户名将与DB匹配,如果一个对象是站点到站点,那么它将与BD匹配

我需要查看对象列表并找到匹配项

基本上我正在做的是将实时数据与数据库数据进行比较,如果在数据库中找到实时数据,我会更新数据库记录,如果找不到服务就是'Up',服务将是'向下'

有人能指出我正确的方向来实现这个目标吗?

编辑:

实时数据列表

>>> 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')))

1 个答案:

答案 0 :(得分:1)

我从数据库条目构建dictset,然后使用它来测试活动连接。

类似的东西:

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))