def _get_live_capture(self): return pyshark.LiveCapture(interface=self.interface, display_filter=self.display_filter)
def start(self, streamName): displayFilter = 'wlan.sa=='+self.targetBssid self.tshark = pyshark.LiveCapture(interface=self.wlanInterface, display_filter=displayFilter) for packet in self.tshark.sniff_continuously(): yield int(packet.wlan_radio.signal_dbm)
def checkIfNewDevice(packet): if packet is not None and packet.wlan is not None and hasattr( packet.wlan, 'da' ) and packet.wlan.da != "ff:ff:ff:ff:ff:ff" and packet.wlan.addr is not None and packet.wlan.addr not in wirelessList: captureTime = datetime.datetime.now() if packet.wlan.addr not in deviceList or ( datetime.datetime.now() - deviceList[packet.wlan.addr]) > datetime.timedelta(minutes=1): imageName = packet.wlan.addr + "_" + unicode(captureTime) + ".jpg" print " device MAC : %s " % (packet.wlan.addr) img = cam.get_image() pygame.image.save(img, imageName) deviceList.update({packet.wlan.addr: captureTime}) pygame.camera.init() cameraList = pygame.camera.list_cameras() if (len(cameraList) == 0): print "No video devices detected" else: cam = pygame.camera.Camera(cameraName, (640, 480)) cam.start() capture = pyshark.LiveCapture(interface=interfaceName) while True: for pkt in capture.sniff_continuously(packet_count=1000): if hasattr(pkt, 'wlan'): checkIfWireless(pkt) checkIfNewDevice(pkt)
def capture_frogs(): global interface cap = pyshark.LiveCapture(interface) print interface cap.sniff(timeout=2) dir(cap) for pkt in cap: all_layers = pkt.layers for layer in all_layers: layer_name = layer._layer_name if "radiotap" in layer_name: #print "radiotap" if layer.channel_flags_5ghz == '1': #print "on 5ghz" chan = '5' else: #print "on 2ghz" chan = '2' sendMessage("Frog/radiotap", chan) if "wlan_radio" in layer_name: if 'signal_dbm' in dir(layer): sig_strength = layer.signal_dbm sendMessage("Frog/wlan_radio", sig_strength) #print sig_strength if "wlan" in layer_name: #print "wlan" trans_addr = "" rec_addr = "" if 'ta' in dir(layer): trans_addr = layer.ta #sendMessage("Frog/wlan_addr/trans",trans_addr) if 'ra' in dir(layer): rec_addr = layer.ra #sendMessage("Frog/wlan_addr/rec",rec_addr) sendMessage("Frog/wlan_addr", trans_addr + "," + rec_addr) if "http" in layer_name: print layer #print dir(layer) if 'content_encoding' in dir(layer): content_encoding = layer.content_encoding sendMessage("Frog/ssl/encoding", content_encoding) if 'set_cookie' in dir(layer): set_cookie = layer.set_cookie sendMessage("Frog/ssl/cookie", set_cookie) if 'server' in dir(layer): server = layer.server sendMessage("Frog/http", server) if 'user_agent' in dir(layer): user_agent = layer.user_agent sendMessage("Frog/http/user_agent", user_agent) print user_agent #print "USER: "******"wlan_mgt" in layer_name: #print layer if 'ssid' in dir(layer): ssid = layer.ssid sendMessage("Frog/wlan_mgt/ssid", ssid) print ssid if "ip" in layer_name: #print "ip" if 'src' in dir(layer): source_addr = layer.src sendMessage("Frog/ip/src", source_addr) if 'dst' in dir(layer): dest_addr = layer.dst sendMessage("Frog/ip/dst", dest_addr) if 'ttl' in dir(layer): ttl = layer.ttl sendMessage("Frog/ip/ttl", ttl) if 'id' in dir(layer): ip_id = layer.id if "ssl" in layer.layer_name: if 'handshake' in dir(layer): handshake_protocol = layer.handshake #print "a rare SSL frog appears" capture_frogs()
addrs = psutil.net_if_addrs() lis = list(addrs.keys()) while (op != "EXIT"): menuInterface() op = input( "\nSeleccionar la tarjeta a analizar (Si desea salir escriba \"EXIT\"):" ) try: op = int(op) if ((op > 0) & (op <= len(lis))): interfaceNetwork = lis[op - 1] cleanTerminal() print("La interfaz elegida es: ", end="") print(interfaceNetwork) timeOutCapture = input( "Ingresar el tiempo en segundos, en el que desea capturar tramas: " ) try: timeOutCapture = int(timeOutCapture) while (timeOutCapture <= 0): timeOutCapture = input( "Ingresar el tiempo en segundos, en el que desea capturar tramas: " ) capture = pyshark.LiveCapture(interface=interfaceNetwork) capture.sniff(timeout=timeOutCapture) viewResults(capture) except: print("", end="") except: print("", end="")
def check(ip): with open("IP.csv", 'rt') as f: reader = csv.reader(f, delimiter=',') if ip in reader: return 1 else: return 0 nm = nmap3.Nmap() writer_file = open("IP.csv", "a") log = csv.writer(writer_file) cap = pyshark.LiveCapture(interface="eth0") cap.sniff(timeout=1) for packet in cap.sniff_continuously(): if 'IP' in packet: src = packet.ip.src option = check(src) if option == 1: continue else: print("New IP address [" + packet.ip.src + "] has just arrived.") data_from_nmap = nm.scan_top_ports(packet.ip.src) os_results = nm.nmap_os_detection(packet.ip.src) print(data_from_nmap) print(os_results) #usually over here we are going to have to add many many more VAPT tools #also have to write those objects to our csv file
def main(self): TOTAL_PKT_CNT = 10 interfaces = 0 # Start capture frames from sirit. dir, file = os.path.split(os.path.abspath(self.sniffer_file)) self.can_bus.configure_port(self.uut.can_bus.port) self.can_bus.power_up(self.uut.can_bus.port) """ Audi Can message for drive direction Motor_14 0x3BE 958 8 100 10 Application Cyclic MO_Gangposition 3 4 4 OnChange 14 g?ltiger Wert 0 Gang_N 1 Gang_1 2 Gang_2 3 Gang_3 4 Gang_4 5 Gang_5 6 Gang_6 7 Gang_7 8 Gang_8 9 Automat_P 10 Automat_Vorwaerts_S 11 Automat_Vorwaerts_D/E 12 Zwischenstellung 13 Gang_R 14 Istgang_nicht_definiert 15 Fehler """ msg_id = 0x3BE cam_msg_reverse = [0x0, 0x0, 0xD0, 00, 0x0, 0x0, 0x0, 0x0] cam_msg_forward = [0x0, 0x0, 0x10, 0x0, 0x0, 0x0, 0x0, 0x0] test_sequence = [cam_msg_reverse, cam_msg_forward, cam_msg_reverse] # Send CAN command of AUDI CAN Protocol to set on CAM drive direction try: for cam_msg in test_sequence: cam_frame_found = False self.transmit_can_data = True # can_bus.send_frame( self.uut.can_bus.port, 0x3BE, cam_msg) canThread = threading.Thread(target=self._send_can_messeges, args=( can_bus, self.uut.can_bus.port, 0x3BE, cam_msg, )) canThread.start() # Create filter for frames not from our dut and cam filter = '!(wlan.sa=={}) and cam'.format( self.uut.rf_interfaces[1].mac_addr) cam_frames = self.sniffer.start_live_capture( interfaces, total_packet_count=TOTAL_PKT_CNT, timeout_sec=60, display_filter=filter) g5_data = pyshark.LiveCapture( interface=self.sniffer.get_interface_name(0), display_filter=filter) for packet in g5_data.sniff_continuously( packet_count=TOTAL_PKT_CNT): print 'Woo, another packet:', packet if len(cam_frames._packets) == 0: pass # Search CAM frame in data for frame_idx, frame in enumerate(cam_frames._packets): if frame.layers[-1].layer_name == 'cam': cam_frame_found = True break self.transmit_can_data = False canThread.join() # Cam frames not found if not cam_frame_found: continue driveDirection = int(frame.cam.driveDirection) if ((cam_msg[2] == cam_msg_reverse[2]) and (driveDirection == 1)): self.stats.can_bus_data_ok += 1 elif ((cam_msg[2] == cam_msg_forward[2]) and (driveDirection == 0)): self.stats.can_bus_data_ok += 1 cam_frames.clear() except Exception as e: raise e finally: self.can_bus.power_down(self.uut.can_bus.port) self.can_bus.close_port(self.uut.can_bus.port)
import pyshark import os # any OS calls on ifconfig must be with sudo INTERFACE = "eth0" PROMISCOUS_ON = "ifconfig {interface} promisc".format(interface=INTERFACE) PROMISCOUS_OFF = "ifconfig {interface} -promisc".format(interface=INTERFACE) capture = pyshark.LiveCapture(interface=INTERFACE) capture.sniff(timeout=50) print len(capture) print capture[0] # remeber always at the end ret = os.system(PROMISCOUS_OFF) print ret
interface = config['interface'] interfaces = interface.split(",") bpf_filter = config['bpf_filter'] time_zone = config['time_zone'] tz = time_zone url = config['db_url'] name = config['username'] passw = config['password'] except yaml.YAMLError as e: logging.error(e) logging.info("Config is OK") # PyShark config try: cap = pyshark.LiveCapture(interface=interfaces, bpf_filter=bpf_filter) except Exception as e: logging.error(e) # Init clickhouse try: db = dbmodels.Database('politraf', db_url=url, username=name, password=passw, readonly=False, autocreate=True) except Exception as e: logging.error(e) def database_write(today, timestamp, protocol, src_addr, src_port, dst_addr, dst_port, qry_name): try: db.insert([ dbmodels.CONNStats(event_date=today, timestamp=timestamp, protocol=protocol, src_addr=src_addr, src_port=src_port, dst_addr=dst_addr, dst_port=dst_port, qry_name=qry_name)
CONFIG = configparser.ConfigParser() CONFIG.read(CONFIG_PATH) if args.interface is not None: INTERFACE = args.interface elif "capture" in CONFIG and "interface" in CONFIG['capture']: INTERFACE = CONFIG['capture']['interface'] else: print(parser.print_help()) sys.exit(-1) if args.interval is not None: COMMIT_INTERVAL = args.interval elif "capture" in CONFIG and "interval" in CONFIG['capture']: COMMIT_INTERVAL = float(CONFIG['capture']['interval']) else: print(parser.print_help()) sys.exit(-1) log("Setting capture interval ", COMMIT_INTERVAL) print(f"Setting up to capture from {INTERFACE}") capture = pyshark.LiveCapture(interface=INTERFACE, bpf_filter='udp or tcp') if DEBUG: capture.set_debug() log("Starting capture") capture.apply_on_packets(QueuedCommit) # timeout=30) capture.close()
def capture_and_plot(intf): print(f"begining live capture on {intf}") capture = pyshark.LiveCapture(interface=intf) packet_map = {} for packet in capture.sniff_continuously(packet_count=sample_size): # print(packet) if "ip" not in packet or "tcp" not in packet: continue ip = packet.ip tcp = packet.tcp port = tcp.dstport try: port = int(port) if port > 5600: continue except Exception: continue src = ip.src dst = ip.dst flags = tcp.flags time_delta = tcp.time_delta key = f'{src}/{dst}:{port}' if key in packet_map: data_points = packet_map[key] data_points.append(float(time_delta)) else: data_points = [ float(time_delta), ] packet_map[key] = data_points print( f' source: {src} dest: {dst} port: {port} time_lapse(RTT):{time_delta} flags:{flags}' ) map_len = len(packet_map) fig, axs = plt.subplots(map_len) fig.suptitle('RTTs (round trip time) of Packets') i = 0 for k, v in packet_map.items(): if map_len > 1: axs[i].plot(range(len(v)), v) axs[i].set_title(f'(src/dest:port) - {k}') axs[i].set_ylabel("Delta Time (Pub - Sub)") axs[i].set_xlabel("Number of Samples") else: axs.plot(range(len(v)), v) axs.set_title(f'(src/dest:port) - {k}') axs.set_ylabel("Delta Time (Pub - Sub)") axs.set_xlabel("Number of Samples") i = i + 1 plt.show()
import pyshark capsav = pyshark.LiveCapture(interface="Wi-Fi", bpf_filter="udp port 67 or udp port 68") print("Begin Capture") print("Waiting for DHCP packets.") for packet in capsav.sniff_continuously(packet_count=4): print("Just Arrived: ", packet.eth.addr) print("DHCP Server IP: ", packet.dhcp.get_field('option_dhcp_server_id')) print("DHCP Leased IP: ", packet.dhcp.get_field('ip_your')) print("DHCP Option: ", packet.dhcp.get_field('option_dhcp')) print("DHCP Option Type: ", packet.dhcp.get_field('option_type')) print("DHCP FQDN: ", packet.dhcp.get_field('fqdn_name')) print("IP in packet: ", 'IP' in packet)
import pyshark capture = pyshark.LiveCapture(interface = 'wlan0mon', bpf_filter = 'subtype probereq', output_file = 'tdump1.pcap') capture.sniff(timeout = 10)
SSDP = 0 server_ip = '10.0.0.5' threshold = 10 def identify_source_port(source_port): if source_port == 53: DNS += 1 elif source_port == 123: NTP += 1 elif source_port == 161: SNMP += 1 elif source_port == 1900: SSDP += 1 def check_threshold(): if DNS > threshold or NTP > threshold or SNMP > threshold or SSDP > threshold: print('Server has surpassed the threshold') return True return False while True: capture = pyshark.LiveCapture(interface='eth0', display_filter='udp') capture.sniff(timeout = 5) if len(capture) == 0: continue for packet in capture: #print(packet[1].get('dst_host')) #print(packet[2].get('srcport')) if packet[1].get('dst_host').get_default_value() == server_ip and int(packet[1].get('len').get_default_value()) > threshold: identify_source_port(packet[2].get('srcport'))
import pyshark capsav = pyshark.LiveCapture(interface="Wi-Fi",bpf_filter="icmp") capsav.sniff(packet_count=5) print (capsav[1].sniff_time) print ("Frame info Time: ", capsav[1].frame_info.time) print (capsav[1].sniff_timestamp) print (capsav[1].ip.dst) """ for packet in capsav.sniff_continuously(packet_count=5): print("Just Arrived: ", packet.eth.addr) print("IP in packet: ", 'IP' in packet) if ('ICMP' in packet) == True: print("->IP Source: ", packet.ip.addr) print("->IP Destination: ", packet.ip.dst) else: print("NO IP ADDRESS IN PACKET") """
#!/usr/bin/python ''' Show the number of retrys on a specific channel Listen to all traffic Count packets / wlan.fc.retry == 1 Show % of number of retry vs packets. ''' import pyshark # Get beacon frames with correct checksum for transmitter address... capture_filter = 'wlan.fcs.status == 1' capture = pyshark.LiveCapture('en0', display_filter=capture_filter, monitor_mode=True) a = 1 packets = 1 packets100 = 1 retrys = 1 retrys100 = 1 for packet in capture.sniff_continuously(): tmp = packet.__dict__ # fields = tmp['layers'][2].__dict__ retry = int(tmp['layers'][2].get_field_value('wlan.fc.retry')) channel = int(tmp['layers'][1].get_field_value('channel')) if a == 1: print 'Capturing on channel: %i' % channel
import pyshark import pandas as pd import matplotlib.pyplot as plt filename = input( "Please enter OUTPUT filename with Extension csv/pcap example- file.csv or file.pcap:: " ) try: capture = pyshark.LiveCapture(interface="wlan0", output_file=filename) capture.sniff() except KeyboardInterrupt: print(capture) if len(capture) > 10: capture1 = pyshark.FileCapture(filename) ip = [] for pkt in capture1: if ("IP" in pkt): if ("UDP" in pkt): print(pkt.ip.src, pkt.udp.dstport) ip.append([pkt.ip.src, pkt.udp.dstport]) elif ("TCP" in pkt): print(pkt.ip.src, pkt.tcp.dstport) ip.append([pkt.ip.src, pkt.tcp.dstport]) elif ("IPV6" in pkt): if ("UDP" in pkt): print(pkt.ipv6.src, pkt.udp.dstport) ip.append([pkt.ipv6.src, pkt.udp.dstport]) elif ("TCP" in pkt): print(pkt.ipv6.src, pkt.tcp.dstport) ip.append([pkt.ipv6.src, pkt.tcp.dstport])
import pyshark import time import argparse import get_malicious import hashlib from OTXv2 import OTXv2 from OTXv2 import IndicatorTypes from greynoise import GreyNoise otx = OTXv2("2e8bf67d611de674bd70308e0c48371a36b9ebf5847aa33f670efd0b2f2b9bf3") #greynoise API initialization #api_client = GreyNoise(api_key="UW3D9zMw61AxTsy9ydprpLz6WGwZLFIJNJR1ra0bPVaKE37zsl3kOoPiiXfqfQUG") cap = pyshark.LiveCapture(interface='eth0') cap.sniff(timeout=1) for packet in cap.sniff_continuously(): print('Just arrived:', packet.ip.src) #Geynoise query #data_of_ip_gn=api_client.quick(packet.ip.src) #print(data_of_ip_gn) alerts = get_malicious.ip(otx, args['packet.ip.src']) if len(alerts) > 0: print('Identified as potentially malicious from AlienVault OTX') print(str(alerts)) else: print('Unknown or not identified as malicious from AlienVault OTX') time.sleep(2)
sys.path.append('..') import rsp RED = '\x1B[31m' GREEN = '\x1B[32m' NORMAL = '\x1B[0m' if sys.argv[1:]: port = int(sys.argv[1]) filter_expression = 'port %d' % port ports = [port] else: filter_expression = '(port 31337) or (port 31338) or (port 31339) or (port 31340)' ports = [31337, 31338, 31339, 31340] cap = pyshark.LiveCapture(interface='lo', bpf_filter=filter_expression) for pkt in cap.sniff_continuously(): if not hasattr(pkt.tcp, 'payload'): continue srcport = int(str(pkt.tcp.srcport), 10) if srcport in ports: print(RED + '<- ', end='') else: print(GREEN + '-> ', end='') result = '' for hex2 in str(pkt.tcp.payload).split(':'): byte = int(hex2, 16) if byte >= 32 and byte <= 126:
import pyshark cap = pyshark.LiveCapture(interface=2) cap.sniff(timeout=10) print(cap) import pyshark cap = pyshark.FileCapture('wlan.pcap', only_summaries=True) dir(cap[0])
9] == "44" and data[8] == "48" def check_for_end_of_packet(data): return data[len(data) - 1] == "00" and data[len(data) - 2] == "0d" and data[len(data) - 3] == "03" def check_for_start(data): for i in range(2, len(data) - 1): if data[i] == "83" and data[i - 1] == "00" and data[i - 2] == "00": return i cap = pyshark.LiveCapture(None, bpf_filter='tcp port 7891') img_data = [] dst_data = [] image_set = False dst_incoming = False first_packet = False for packet in cap.sniff_continuously(): if packet[1].src == '192.168.1.100' and hasattr(packet.tcp, 'payload'): payload = packet.tcp.payload.split(':') if dst_incoming: if first_packet: payload = payload[12:] first_packet = False if check_for_end_of_packet(payload): payload = payload[:len(payload) - 3] for i in range(0, len(payload)):
#!/usr/bin/python3.8 #Pyshark will only work, if tshark is installed on the system import pyshark from os import sys interface = 'Loopback' CapFilter = 'tcp port 65432' #Setup capture on localhost cap = pyshark.LiveCapture(interface=interface, bpf_filter=CapFilter) #Run continous packet tracing for packet in cap.sniff_continuously(): #Print captured packets to shell print(packet)
import pyshark cap = pyshark.LiveCapture() print(cap)
import pyshark import datetime i = 0 while (1): packet = pyshark.LiveCapture(interface="wlp1s0") for cap in packet.sniff_continuously(packet_count=1): if (i == 0): pack_time = 0 time = float(cap.sniff_timestamp) i = 1 pack_time = float(cap.sniff_timestamp) - time time = float(cap.sniff_timestamp) size = cap.length packet = 1 prot = cap.transport_layer if hasattr(cap, 'tcp'): port = cap.tcp.dstport if hasattr(cap, 'udp'): port = cap.udp.dstport print(pack_time, "\t", size, "\t", packet, "\t", prot, "\t", port)
def capture_packet(threadName, nic): print("Start an new thread to capture network packets with {}".format(nic)) client = mqtt.Client(client_id=threadName, clean_session=MQTT_CLIENT_CLEAR_SESSION) client.max_queued_messages_set(MQTT_CLIENT_MAX_QUEUED_MESSAGES) client.max_inflight_messages_set(MQTT_CLIENT_MAX_INFLIGHT_MESSAGES) client.message_retry_set(MQTT_CLIENT_MESSAGE_RETRY) # Enable it when you have an encrypted MQTT Broker # client.tls_set(ca_certs=MQTT_CLIENT_CA_CERTS, # certfile=MQTT_CLIENT_CERTFILE, # keyfile=MQTT_CLIENT_KEYFILE, # cert_reqs=MQTT_CLIENT_CERT_REQS, # tls_version=MQTT_CLIENT_TLS_VERSION, # ciphers=MQTT_CLIENT_CIPHERS # ) # client.enable_logger(logger=MQTT_CLIENT_DEFAULT_LOGGER) client.on_connect = on_connect client.on_message = on_message client.on_disconnect = on_disconnect client.connected_flag = False capture = pyshark.LiveCapture(interface=nic) b_connecting_in_progress = False while True: # When MQTT client has started one connectin, it will wait for successful message back or timout or error # without issuing another connection request. if b_connecting_in_progress and (not client.connected_flag): continue try: if not client.connected_flag: print( f"Connect to MQTT broker {MQTT_BROKER_HOSTNAME}:{MQTT_BROKER_PORT} with keepalive {MQTT_BROKER_CONNECTION_TIMOUT} seconds." ) client.connect(host=MQTT_BROKER_HOSTNAME, port=MQTT_BROKER_PORT, keepalive=MQTT_BROKER_CONNECTION_TIMOUT) client.loop_start() b_connecting_in_progress = True else: i = 0 for packet in capture.sniff_continuously(): print(packet) result = client.publish(MQTT_BROKER_PACKET_TOPIC_NAME, payload=pickle.dumps(packet), qos=0, retain=False) status = result[0] if status == 0: i += 1 #print(f"Successfully sent one message {packet}") else: print( f"Failed {result} to send message to topic {MQTT_BROKER_PACKET_TOPIC_NAME}" ) if status == 4: client.reconnect() except ConnectionRefusedError: print("ConnectionRefusedError") b_connecting_in_progress = False time.sleep(MQTT_CLIENT_MESSAGE_RETRY) continue except KeyboardInterrupt: client.disconnect() capture.close() sys.exit(0)
parser.add_argument("-o", "--output", help="guardar pcap capturada a un archivo") args = parser.parse_args() if args.verbosity: print(">>> Verbosity Activado") if args.live: if args.output: print ">>> Se guardarán los datos en: ", args.output else: args.output = "./temp.pcap" print ">>> Generando Captura Live escuchando en ", args.live capture = pyshark.LiveCapture(interface=args.live, display_filter='http.authbasic', output_file=args.output) if not args.timeout: args.timeout = 50 print ">>> Timeout configurado a ", args.timeout, " segundos" # capture.sniff(timeout=50) elif not args.packet_limit: args.packet_limit = 10 #print capture if args.timeout == 0: print ">>> Iniciando Captura ininterrumpida (timeout 0), limitando por el contados de paquetes: ", args.packet_limit for i, packet in enumerate( capture.sniff_continuously( packet_count=int(args.packet_limit))): print 'Packet num: ', i if args.verbosity:
default=False) args = parser.parse_args() # live ring capture if args.ring: logger.info("Starting Live Ring Capture on " + args.interface) cap = pyshark.LiveRingCapture(interface=args.interface, only_summaries=True, ring_file_size=4096, num_ring_files=50, ring_file_name='./db/pcap/pci.pcapng') packet_analysis_live(cap) # live capture elif args.interface: logger.info("Starting Live Capture on " + args.interface) cap = pyshark.LiveCapture(interface=args.interface, only_summaries=True) packet_analysis_live(cap) # pcap elif args.filepath: logger.info("Starting pcap analysis on " + args.filepath) cap = pyshark.FileCapture(input_file=args.filepath, only_summaries=True) packet_analysis(cap) else: parser.print_help() sys.exit()
import sys import pyshark sys.path.append('.') sys.path.append('..') import rsp RED = '\x1B[31m' GREEN = '\x1B[32m' NORMAL = '\x1B[0m' port = 31337 if sys.argv[1:]: port = int(sys.argv[1]) cap = pyshark.LiveCapture(interface='lo', bpf_filter='port %d' % port) for pkt in cap.sniff_continuously(): if not hasattr(pkt.tcp, 'payload'): continue srcport = int(str(pkt.tcp.srcport), 10) if srcport == port: print(RED + '<- ', end='') else: print(GREEN + '-> ', end='') result = '' for hex2 in str(pkt.tcp.payload).split(':'): byte = int(hex2, 16) if byte >= 32 and byte <= 126:
import pyshark capture = pyshark.LiveCapture(interface='wlan0mon', bpf_filter='subtype probereq') for packet in capture.sniff_continuously(): if packet['WLAN_MGT'].ssid != 'SSID: ': print 'Device: ', packet['WLAN'].sa, ' SSID: ', packet['WLAN_MGT'].ssid
def startCaptureDNS(): capture = pyshark.LiveCapture( interface='en0', display_filter='dns' ) #creates a new pyshark object with a specific interface and desired parameters capture.apply_on_packets(examinePacketDNS)