代碼中的問題是,如果缺少某個欄位,則會引發錯誤,如果我排除錯誤,則不會顯示任何內容
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
我希望如果丟失了一個欄位,那么它存盤我在資料包中獲得的傳入欄位并顯示在表中,對于空欄位,它不顯示任何內容并將該欄位保留在表中。基本上我希望它存盤傳入欄位并在表中列印并且不會為丟失的欄位引發錯誤。我現在正在 fileCapture 上嘗試它以檢查作業,但我需要在 liveCapture 上執行此操作
uj5u.com熱心網友回復:
如果我正確理解你,你不想得到屬性錯誤而是在欄位丟失時輸入一個空值。
您可以通過使用getattr函式檢查值來做到這一點。
所以我不知道究竟是什么dhcp,如果它丟失或總是存在,只有后面的東西才能丟失。
但是可以說 dhcp 始終存在并且您指向的實際欄位可能會丟失:
- 創建一個名為:
get_value_or_none(obj, key, default='') -> str - 現在讓我們使用
getattr.
def get_value(obj, key, default='') -> str:
return getattr(obj, key, default=default)
現在通過用函式呼叫包裝呼叫來替換您在代碼中所做的所有相應的分配:即: get_value(packet.dhcp, 'option_domain_name')
就是這樣,它應該作業。
附注。如果dhcp并不總是存在,你也必須對它做同樣的事情。
uj5u.com熱心網友回復:
我是通過使用以下方法做到的:
dictionary.get()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/392966.html
上一篇:帶反斜杠的字串到字典
下一篇:python:如何減少到單行:
