Python pyshark.FileCapture() Examples

The following are 9 code examples of pyshark.FileCapture(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyshark , or try the search function .
Example #1
Source File: tgenerator.py    From polymorph with GNU General Public License v2.0 9 votes vote down vote up
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 
Example #2
Source File: hci_parser.py    From BLESuite with MIT License 8 votes vote down vote up
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 
Example #3
Source File: traffic_analysis_engine.py    From IoT-Home-Guard with MIT License 7 votes vote down vote up
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) 
Example #4
Source File: symmetry-pcap2cards.py    From Concierge with MIT License 7 votes vote down vote up
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) 
Example #5
Source File: pcap_sniffer.py    From black-widow with GNU General Public License v3.0 6 votes vote down vote up
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
            ) 
Example #6
Source File: count_packets.py    From Learning-Python-Networking-Second-Edition with MIT License 6 votes vote down vote up
def count_packets():
	cap = pyshark.FileCapture('http.cap', keep_packets=False)
	cap.apply_on_packets(counter, timeout=10000)
	return len(packets_array) 
Example #7
Source File: traffic_analysis_engine.py    From IoT-Home-Guard with MIT License 6 votes vote down vote up
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] 
Example #8
Source File: pcap_to_csv.py    From NetworkML with Apache License 2.0 6 votes vote down vote up
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}') 
Example #9
Source File: reader.py    From pcap-processor with GNU General Public License v3.0 6 votes vote down vote up
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)