本文整理汇总了Python中pyshark.FileCapture方法的典型用法代码示例。如果您正苦于以下问题:Python pyshark.FileCapture方法的具体用法?Python pyshark.FileCapture怎么用?Python pyshark.FileCapture使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyshark
的用法示例。
在下文中一共展示了pyshark.FileCapture方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import pyshark [as 别名]
# 或者: from pyshark import FileCapture [as 别名]
def __init__(self, pcapfile, scapy_pkts=None, tshark_pkts=None):
"""Initialization method of the class.
Parameters
----------
pcapfile : str
Path to a previously captured pcap.
scapy_pkts : :obj:`PacketList`
List of packets generated by Scapy.
tshark_pkts : :obj:`FileCapture`
List of packets generated by Pyshark.
"""
if scapy_pkts:
self._scapy_pkts = scapy_pkts
else:
self._scapy_pkts = rdpcap(pcapfile)
if tshark_pkts:
self._tshark_pkts = tshark_pkts
else:
self._tshark_pkts = FileCapture(pcapfile)
self._i = -1
示例2: get_records
# 需要导入模块: import pyshark [as 别名]
# 或者: from pyshark import FileCapture [as 别名]
def get_records(self):
"""Parse the btsnoop file into a dictionary of records"""
if self.snoop_file is None and self.pcap_file is None:
raise ValueError("Must load a btsnoop or PCAP file to get records")
return
if self.snoop_file is not None:
try:
records = bts.parse(self.snoop_file)
except Exception as e:
print "Error: "
print e.message
return None
elif self.pcap_file is not None:
py_cap = pyshark.FileCapture(self.pcap_file)
records = []
for packet in py_cap:
records.append(packet)
self.records = records
return records
示例3: amag_parse
# 需要导入模块: import pyshark [as 别名]
# 或者: from pyshark import FileCapture [as 别名]
def amag_parse(infile):
print "[*] Loading pcap: "+infile+" ..."
pcap = pyshark.FileCapture(infile, display_filter='tcp.port == 3001 && (frame contains "8Mt")')
pcap.load_packets()
num = len(pcap)
print "[*] Parsing pcap for AMAG Symmetry badge numbers..."
for packet in range(0 , num):
pdata = str(pcap[packet].data.get_field_value('data'))
full = pdata[-28:-12]
raw_cn = re.findall('..',full[:10])
raw_fc = re.findall('..',full[-6:])
cn = int(str(int(str(int(str("0x"+raw_cn[0]), 16)-0x10).zfill(2))).zfill(2)+str(int(str(int(str("0x"+raw_cn[1]), 16)-0x10).zfill(2))).zfill(2)+str(int(str(int(str("0x"+raw_cn[2]), 16)-0x10).zfill(2))).zfill(2)+str(int(str(int(str("0x"+raw_cn[3]), 16)-0x10).zfill(2))).zfill(2)+str(int(str(int(str("0x"+raw_cn[4]), 16)-0x10).zfill(2))).zfill(2))
fc = int(str(int(str(int(str("0x"+raw_fc[0]), 16)-0x10).zfill(2))).zfill(2)+str(int(str(int(str("0x"+raw_fc[1]), 16)-0x10).zfill(2))).zfill(2)+str(int(str(int(str("0x"+raw_fc[2]), 16)-0x10).zfill(2))).zfill(2))
if cn > 0:
with open("amag-badges.csv","a+")as f:
f.write(str(cn)+","+str(fc)+","+infile+"\n")
print "[+] CN: "+str(cn)+" FC:"+str(fc)
示例4: run
# 需要导入模块: import pyshark [as 别名]
# 或者: from pyshark import FileCapture [as 别名]
def run(self):
cap = pyshark.FileCapture(self.filename,only_summaries=True)
i = j = 0
resultdump=[]
for p in cap:
ret = self.traffic_analyze(p)
i = i+1
if not ret:
# print("[Result] No security issues.")
#else:
j = j+1
#print("[Result] WARINING: Trojan has been discovered.")
#print(p.no, p.protocol, p.source, p.destination,'\n')
ttime = time.asctime(time.localtime(time.time()))
hash=hashlib.md5()
hash1=p.protocol+p.destination
hash.update(hash1.encode('utf-8'))
conn=sqlite3.connect("homeguard.db")
#print("Opened database successfully!")
resultdict=dict()
resultdict['dev']=self.device_name
resultdict['time']=ttime
resultdict['num']=p.no
resultdict['des']=p.destination
resultdict['protocol']=p.protocol
resultdict['hash']=hash.hexdigest()
resultdump.append(resultdict)
sql="insert into Result(dev,time,num,des,protocol,hash)values('%s','%s','%s','%s','%s','%s')"%(self.device_name,ttime,p.no,p.destination,p.protocol,hash.hexdigest())
conn.execute(sql)
conn.commit()
conn.close()
#print("Close database successfully!")
#print(j,"/",i,'\n')
#print(self.domain_ip,'\n')
#print(self.new_ip)
#print(self.device_ip)
print(resultdump)
示例5: count_packets
# 需要导入模块: import pyshark [as 别名]
# 或者: from pyshark import FileCapture [as 别名]
def count_packets():
cap = pyshark.FileCapture('http.cap', keep_packets=False)
cap.apply_on_packets(counter, timeout=10000)
return len(packets_array)
示例6: __init__
# 需要导入模块: import pyshark [as 别名]
# 或者: from pyshark import FileCapture [as 别名]
def __init__(self, pcap_file, device_name):
self.filename = 'pcaps/' + pcap_file + ".pcap"
self.devicename = 'device_fingerprint_database/' + device_name + ".yaml"
self.device_name = device_name
f = open(self.devicename)
self.rules = yaml.load(f)
#self.device_ip = '172.27.35.73'
self.DNS_server_ip = ['4.2.2.2','8.8.8.8']
self.domain_ip = []
self.domain_ip.append(self.rules['domain'])
#print('domain ip: ',self.domain_ip)
self.new_ip = {}
cap = pyshark.FileCapture(self.filename,only_summaries=True)
for p in cap:
if p.protocol == "DNS":
if "response" in p.info:
result = re.findall(r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b", p.info)
if result:
for r in result:
if r not in self.domain_ip:
self.domain_ip.append(r)
# if p.protocol == "ARP":
# if str(self.rules['packet'][0]['MAC']) in p.info: #xiaoaitongxue MAC address
# self.device_ip = p.info.split(" ")[0]
示例7: get_pyshark_packet_data
# 需要导入模块: import pyshark [as 别名]
# 或者: from pyshark import FileCapture [as 别名]
def get_pyshark_packet_data(self, pcap_file, dict_fp):
all_protocols = set()
pcap_file_short = ntpath.basename(pcap_file)
with gzip_writer(dict_fp) as f_out:
with pyshark.FileCapture(pcap_file,
use_json=True,
include_raw=True,
keep_packets=False,
custom_parameters=['-o', 'tcp.desegment_tcp_streams:false', '-n']) as cap:
for packet in cap:
packet_dict = {}
packet_dict['filename'] = pcap_file_short
frame_info = packet.frame_info._all_fields
for key in frame_info:
packet_dict[key] = frame_info[key]
# can overflow the field size for csv
#packet_dict['raw_packet'] = packet.get_raw_packet()
layers = str(packet.layers)
packet_dict['layers'] = layers
str_layers = layers[1:-1].split(', ')
for str_layer in str_layers:
# ignore raw layers
if 'RAW' not in str_layer:
all_protocols.add(str_layer)
# only include specified protocols due to unknown parsing for some layers
if str_layer in self.PROTOCOLS:
layer_info = getattr(packet, str_layer.split()[
0][1:].lower())._all_fields
# check for nested dicts, one level deep
for key in layer_info:
# DNS doesn't parse well
if isinstance(layer_info[key], dict) and str_layer != '<DNS Layer>':
for inner_key in layer_info[key]:
packet_dict[inner_key] = layer_info[key][inner_key]
else:
packet_dict[key] = layer_info[key]
# clean up records
packet_dict_copy = deepcopy(packet_dict)
keys = packet_dict_copy.keys()
for key in keys:
if not key[0].isalpha() or key == 'tcp.payload_raw' or key == 'tcp.payload':
del packet_dict[key]
f_out.write(json.dumps(packet_dict) + '\n')
for protocol in self.PROTOCOLS:
if protocol in all_protocols:
all_protocols.remove(protocol)
if all_protocols:
self.logger.warning(
f'Found the following other layers in {pcap_file_short} that were not added to the CSV: {all_protocols}')
示例8: _read_pcap
# 需要导入模块: import pyshark [as 别名]
# 或者: from pyshark import FileCapture [as 别名]
def _read_pcap(self, path):
logger.debug("Reading pcap file: %s", path)
packets = pyshark.FileCapture(path)
for pcap in packets:
has_transport = pcap.transport_layer is not None
packet_time = float(pcap.sniff_timestamp)
packet_dict = dict()
highest_layer = pcap.highest_layer.upper()
packet_dict["highest_layer"] = highest_layer
if has_transport:
packet_dict["transport_layer"] = pcap.transport_layer.upper()
else:
packet_dict["transport_layer"] = "NONE"
packet_dict["src_port"] = -1
packet_dict["dst_port"] = -1
packet_dict["transport_flag"] = -1
packet_dict["timestamp"] = int(packet_time * 1000)
packet_dict["time"] = str(pcap.sniff_time)
packet_dict["packet_length"] = int(pcap.length)
packet_dict["data"] = ""
for layer in pcap.layers:
layer_name = layer.layer_name.upper()
if "IP" == layer_name or "IPV6" == layer_name:
packet_dict["src_ip"] = str(layer.src)
packet_dict["dst_ip"] = str(layer.dst)
if hasattr(layer, "flags"):
packet_dict["ip_flag"] = int(layer.flags, 16)
else:
packet_dict["ip_flag"] = -1
if hasattr(layer, "geocountry"):
packet_dict["geo_country"] = str(layer.geocountry)
else:
packet_dict["geo_country"] = "Unknown"
elif has_transport and layer_name == pcap.transport_layer:
packet_dict["src_port"] = int(layer.srcport)
packet_dict["dst_port"] = int(layer.dstport)
if hasattr(layer, "flags"):
packet_dict["transport_flag"] = int(layer.flags, 16)
else:
packet_dict["transport_flag"] = -1
elif "FTP" == layer_name:
packet_dict["data"] = str(layer._all_fields)
if "src_ip" not in packet_dict:
continue
# Map packet attributes
packet_dict = MapperManager.map(packet_dict)
SinkManager.write(packet_dict)
示例9: __init__
# 需要导入模块: import pyshark [as 别名]
# 或者: from pyshark import FileCapture [as 别名]
def __init__(
self,
filters: str = None,
src_file: str = None,
dest_file: str = None,
interfaces: list = None,
limit_length: int = None,
pkt_count: int = None,
callback=None
):
"""
Packet capture method
:param filters: https://wiki.wireshark.org/DisplayFilters
:param src_file: Il file .pcap da cui leggere i pacchetti ascoltati (o None, per Live sniffing)
:param dest_file: Il file in cui scrivere il .pcap dei pacchetti ascoltati (o None)
:param interfaces: The list of interfaces to sniff (or None, to sniff all interfaces)
:param limit_length: The limit length of each packet field (they will be truncated), or None
:param pkt_count: Max packets to sniff, or None
:param callback: The callback method to call (or None) (@see PcapSniffer._user_callback_example)
"""
if not PcapSniffer.is_executable():
raise RuntimeError('Unable to execute pcap sniffer')
self.count = 0 # Sniffed packets
self.max_count = pkt_count
# Prevents the mac manufacturer lookup sniffing
self.filters = PcapSniffer._get_filters(filters)
self.src_file = src_file
self.dest_file = dest_file
self.limit_length = limit_length
self.user_callback = callback
self.interfaces = interfaces
Log.info('Analyzing filters: ' + str(self.filters))
if self.src_file is not None:
Log.info('Analyzing file: ' + self.src_file)
self._capture = pyshark.FileCapture(
input_file=self.src_file,
display_filter=self.filters,
output_file=self.dest_file,
# include_raw=True,
# use_json=True
# debug=APP_DEBUG
)
else:
Log.info('Analyzing live traffic')
self._capture = pyshark.LiveCapture(
interface=self.interfaces,
display_filter=self.filters,
output_file=self.dest_file,
# include_raw=True,
# use_json=True
# debug=APP_DEBUG
)