Home > other >  How to valid the captured incoming empty field in a table
How to valid the captured incoming empty field in a table

Time:12-22

The problem in code is that if a field is missed then it raises error and if I except the error then it will not show anything

import pyshark
from tabulate import tabulate

capture = pyshark.FileCapture('/home/sipl/Downloads/DHCP.cap', display_filter='udp.port eq 67')
# capture2 = pyshark.LiveCapture(interface='wlo2', display_filter='arp')

d = dict()

for packet in capture:
    try:
        d['mac'] = packet.dhcp.hw_mac_addr
        d['hname'] = packet.dhcp.option_hostname

        d['vend'] = packet.dhcp.option_vendor_class_id
    except AttributeError:
        pass
    try:
        d['srvrid'] = packet.dhcp.option_dhcp_server_id
        d['smask'] = packet.dhcp.option_subnet_mask
        d['DNS'] = packet.dhcp.option_domain_name_server
        d['Domain'] = packet.dhcp.option_domain_name

    except AttributeError:
        pass
    try:
        d['ip'] = packet.dhcp.option_requested_ip_address

    except AttributeError:
        pass

    try:
        table = {'Mac': [d['mac']], 'IP': [d['ip']], 'host': [d['hname']],'vendor': [d['vend']], 'Server id': [d['srvrid']],
                 'Sub mask': [d['smask']], 'DNS': [d['dns']], 'Domain': [d['Domain']]}
        print(tabulate(table, headers='keys'))
    except KeyError:
        continue

I want that if a field is missed then it store the incoming fields i got in a packet and show in the table, for empty field it doesn't show anything and leave the field empty in table. Basically I want that it stores the incoming field and prints in table and didn't raise error for the missed field. I'm trying it now on fileCapture to check working but i need to do this on liveCapture

CodePudding user response:

If Im understand you correctly, you don't want to get the Attribute Error but put an empty value when field is missing.

You can do it by check for value using getattr function.

so I have no Idea exactly what dhcp and if its missing or always existing and only what comes after can be missing.

But lets says that dhcp always exists and the actual fields you are pointing at can be missed:

  1. Create a function called: get_value_or_none(obj, key, default='') -> str
  2. Now lets implement it using the getattr.
def get_value(obj, key, default='') -> str:
    return getattr(obj, key, default=default)

Now replace all the coresponding assignments you made in your code by wrapping the calls with the function calls: i.e: get_value(packet.dhcp, 'option_domain_name')

That's it, it should work.

PS. If the dhcp is not always present, you will have to do the same with it too.

CodePudding user response:

I did it by using the method:

dictionary.get()
  • Related