本文整理汇总了Python中scapy.all.sniff方法的典型用法代码示例。如果您正苦于以下问题:Python all.sniff方法的具体用法?Python all.sniff怎么用?Python all.sniff使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scapy.all
的用法示例。
在下文中一共展示了all.sniff方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start
# 需要导入模块: from scapy import all [as 别名]
# 或者: from scapy.all import sniff [as 别名]
def start(self):
self.logger.debug('Starting monitoring on %s', self.iface_manager.iface)
self.iface_manager.start()
while True:
try:
# macOS
if platform.system() == 'Darwin':
self.logger.warning('macOS support is pre-alpha - many improvements coming soon')
scapy.sniff(iface=self.iface_manager.iface, monitor=True, prn=self.process_packet, store=0)
break
# linux
else:
# For versions of scapy that don't provide the exceptions kwarg
scapy.sniff(iface=self.iface_manager.iface, prn=self.process_packet, store=0)
break
except TJException:
raise
except (OSError, IOError):
self.logger.error(traceback.format_exc())
self.logger.info('Sniffer error occurred. Restarting sniffer in 3 seconds...')
time.sleep(3)
示例2: _capture_packets
# 需要导入模块: from scapy import all [as 别名]
# 或者: from scapy.all import sniff [as 别名]
def _capture_packets(self):
while self._is_active():
if not self._host_state.is_inspecting():
time.sleep(2)
continue
result = utils.safe_run(sc.sniff, kwargs={
'prn': self._host_state.packet_processor.process_packet,
'stop_filter':
lambda _:
not self._is_active() or
not self._host_state.is_inspecting(),
'timeout': 30
})
if isinstance(result, utils._SafeRunError):
time.sleep(1)
示例3: filter_string
# 需要导入模块: from scapy import all [as 别名]
# 或者: from scapy.all import sniff [as 别名]
def filter_string(self):
"""Create filter string for scapy sniff() function."""
if self.test_params.ip_version == 4:
return (
"udp and (dst host "
+ DNS_SD_MULTICAST_IPV4
+ " or dst host "
+ str(self.test_params.src_endpoint.ip_addr)
+ ") and (src host "
+ str(self.test_params.dst_endpoint.ip_addr)
+ ") and (dst port 5353 or src port 5353)"
)
elif self.test_params.ip_version == 6:
return (
"udp and (dst host "
+ DNS_SD_MULTICAST_IPV6
+ " or dst host "
+ str(self.test_params.src_endpoint.ipv6_addr)
+ ") and (src host "
+ str(self.test_params.dst_endpoint.ip_addr)
+ ") and (dst port 5353 or src port 5353)"
)
return None
示例4: ping
# 需要导入模块: from scapy import all [as 别名]
# 或者: from scapy.all import sniff [as 别名]
def ping(test_params, show_result=False):
"""Check mDNS service availability by sending ping packet and waiting for response."""
if not test_params:
return None
query = DNS_SD_QUERY
mdns_sniffer = MulticastDNSSniffer(test_params, query)
thread = threading.Thread(target=mdns_send_query, args=(test_params, query))
thread.start()
print_verbose(test_params, "filter: {}".format(mdns_sniffer.filter_string()))
sniff(
filter=mdns_sniffer.filter_string(),
prn=mdns_sniffer.filter_action,
count=10000,
timeout=test_params.timeout_sec + 2,
)
print_verbose(
test_params, "received mDNS response: {}".format(mdns_sniffer.server_alive)
)
return mdns_sniffer.server_alive
示例5: run
# 需要导入模块: from scapy import all [as 别名]
# 或者: from scapy.all import sniff [as 别名]
def run(iface, local_ip, sniff_filter, spoof_domains):
print("#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#")
print("-#-#-#-#-#-RUNNING DNS SPOOFER-#-#-#-#-#-")
print("#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#")
print("Interface:\t\t\t%s" % iface)
print("Resolving to IP:\t\t%s" % local_ip)
print("Spoof domains:\t\t%s" % ', '.join(spoof_domains))
print("BPF sniff filter:\t\t%s" % sniff_filter)
print("")
print("Waiting for DNS requests...")
print("(Make sure the device you are targeting is set to use"\
"your local IP (%s) as its DNS server)" % local_ip)
scapy.sniff(iface=iface,
filter=sniff_filter,
prn=handle_packet_fn(iface, local_ip, spoof_domains))
示例6: run
# 需要导入模块: from scapy import all [as 别名]
# 或者: from scapy.all import sniff [as 别名]
def run(self):
# TODO this loop could be reconciled with the ofp Connection to become a
# single select loop.
self.sock = s = conf.L2listen(
type=ETH_P_ALL,
iface=self.iface,
filter='inbound'
)
while not self.finished:
try:
sniffed = sniff(1, iface=self.iface, timeout=1, opened_socket=s)
print 'Sniffer received %d packet(s)' % len(sniffed)
for pkt in sniffed:
self.forward_packet(pkt)
except Exception, e:
logging.error("scapy.sniff error: %s" % e)
示例7: arp_monitor
# 需要导入模块: from scapy import all [as 别名]
# 或者: from scapy.all import sniff [as 别名]
def arp_monitor(self):
"""
Simplistic ARP Monitor
This program uses the sniff() callback (parameter prn). The store
parameter is set to 0 so that the sniff() function will not store
anything (as it would do otherwise) and thus can run forever.
The filter parameter is used for better performances on high load:
The filter is applied inside the kernel and Scapy will only see ARP traffic.
-- https://scapy.readthedocs.io/en/latest/usage.html#simplistic-arp-monitor
"""
log.info('Waiting for any devices having MAC address prefixes of {} '
'to appear on your local network'.format(self.mac_prefixes))
#sniff(prn=self.arp_monitor_callback, filter="arp", store=0)
sniff(prn=self.check_esp32, filter="arp", store=0)
示例8: start_poisen
# 需要导入模块: from scapy import all [as 别名]
# 或者: from scapy.all import sniff [as 别名]
def start_poisen(target, interface, scapy_filter):
vpoison = threading.Thread(target=poison)
vpoison.setDaemon(True)
vthread.append(vpoison)
vpoison.start()
gwpoison = threading.Thread(target=gw_poison)
gwpoison.setDaemon(True)
gwthread.append(gwpoison)
gwpoison.start()
if dns_sniff or dns_sniff_gource:
pkt = scapy.sniff(iface=interface,filter=scapy_filter,prn=dnshandle)
else:
pkt = scapy.sniff(iface=interface,filter=scapy_filter,prn=rawhandle)
示例9: sniff
# 需要导入模块: from scapy import all [as 别名]
# 或者: from scapy.all import sniff [as 别名]
def sniff(self, target=None, iface=None):
def _process(pkt):
match_ip = pkt.haslayer(IP) and (pkt[IP].src == target[0] or pkt[IP].dst == target[0]) if target else True
match_port = pkt.haslayer(TCP) and (
pkt[TCP].sport == target[1] or pkt[TCP].dport == target[1]) if len(target) == 2 else True
if match_ip and match_port:
self.capabilities.insert(pkt, client=False)
events = self.capabilities.get_events() # misuse get_events :/
if events:
strconn = {'src': None,
'dst': None,
'sport': None,
'dport': None}
if pkt.haslayer(IP):
strconn['src'] = pkt[IP].src
strconn['dst'] = pkt[IP].dst
if pkt.haslayer(TCP):
strconn['sport'] = pkt[TCP].sport
strconn['dport'] = pkt[TCP].dport
print ("Connection: %(src)s:%(sport)d <==> %(dst)s:%(dport)d" % strconn)
print ("* EVENT - " + "\n* EVENT - ".join(e[0] for e in events))
return
if iface:
conf.iface = iface
while True:
bpf = None
if len(target):
bpf = "host %s" % target[0]
if len(target) == 2:
bpf += " and tcp port %d" % target[1]
sniff(filter=bpf,
prn=_process,
store=0,
timeout=3)
示例10: waitForPacket
# 需要导入模块: from scapy import all [as 别名]
# 或者: from scapy.all import sniff [as 别名]
def waitForPacket(self, state=None, filterfct=None, timeout=None,
buffermode=False, **kargs):
"""Wait for one packet matching a filter function
state: initial state, may be empty but should be a valid state
instance.
filterfct: boolean function applied on a packet received to select it
or not. Ex: lambda pkt: pkt.haslayer("TCP")
other args: extra args for sniff function of scapy"""
if state is None:
if self.state is None:
raise Exception("A state object must be given as parameter when \
waiting for a packet if no initstate entered in the Tester.")
state = self.state
else:
self.state.update(state)
if timeout:
tOut = " (timeout after " + str(timeout) + " secs)"
else: tOut = ""
self.debug("Sniffing using custom function..." + tOut, level=2)
# if buffermode:
# # in buffermode, the packets are stored in buf and they are transmitted
# # to user only when a UDP signal is encountered
# buf = sniff(count=0, lfilter=lambda pkt: filterfct(pkt) or \
# pkt.haslayer(UDP), filter="udp or tcp",
# stop_filter=lambda pkt: pkt.haslayer(UDP),
# timeout=timeout, **kargs)
# self.sendAck(buf[-1].getlayer("IP").src)
# return buf[:-1]
pkts = sniff(count=1, lfilter=filterfct, filter="tcp",
timeout=timeout, **kargs)
if pkts is None or len(pkts) == 0:
raise PktWaitTimeOutException(timeout)
return pkts[0].getlayer("IP")
示例11: main
# 需要导入模块: from scapy import all [as 别名]
# 或者: from scapy.all import sniff [as 别名]
def main():
# All code is in main function because no higher level wrapper functions are needed for scapy
# Argparse setup
parser = argparse.ArgumentParser(description="Packet sniffer")
parser.add_argument("--iface", type=str, help="interface to sniff")
parser.add_argument("--filter", type=str, help="bpf filter string")
parser.add_argument("--outfile", type=str, help="Pcap file to output")
args = parser.parse_args()
if not args.iface:
# Needs an interface
print("--iface required")
exit()
# Default Values for opts
outfile = "out.pcap"
filt = None
try:
pkts = scapy.sniff(filter=filt, iface=args.iface)
scapy.wrpcap(outfile, pkts)
except PermissionError:
# Raw sockets require root privs
print("Must run as root")
exit()
示例12: __init__
# 需要导入模块: from scapy import all [as 别名]
# 或者: from scapy.all import sniff [as 别名]
def __init__(self, config):
super(CredentialSniffer, self).__init__(config, "credentialsniffer")
self.running_interface = self.config["sniffing_interface"]
self.running_bssid = self.config["bssid"]
self.running_ssid = self.config["ssid"]
self.log_dir = self.config["log_dir"]
self.wifi_clients = {}
self.wpa_handshakes = {}
self.broadcasted_bssids = {} # bssid: beacon_packet
self.sniffer_thread = None
self.should_stop = False
self.log_lock = Lock()
try:
self.fixed_channel = int(self.config["fixed_sniffing_channel"])
except:
self.fixed_channel = 7
try:
self.timeout = int(self.config["timeout"])
except:
self.timeout = 30
# When sniffing for credentials on interface running in Master mode
# scapy will only be able to sniff for layer 3 packets (Networking)
# so it never receives a Beacon packet (layer2) to verify the access point ssid
# best to pass it as parameter since we are running the access point we know the ssid
self.is_ap = False
# This will be called by the AirSniffer
示例13: start_credential_sniffing
# 需要导入模块: from scapy import all [as 别名]
# 或者: from scapy.all import sniff [as 别名]
def start_credential_sniffing(self):
# TODO map packets to interface with threads
try:
sniff( store = 0,
prn = self.extract_credential_info,
stop_filter = self._stop)
except Exception as e:
print "Error Occurred while sniffing."
print str(e)
示例14: sniff_packet
# 需要导入模块: from scapy import all [as 别名]
# 或者: from scapy.all import sniff [as 别名]
def sniff_packet(interface):
scapy.sniff(iface=interface, store=False, prn=process_packets)
示例15: run
# 需要导入模块: from scapy import all [as 别名]
# 或者: from scapy.all import sniff [as 别名]
def run(self):
"""Starts sniffing for incoming ARP packets with scapy.
Actions after receiving a packet ar defines via _packet_handler.
"""
# the filter argument in scapy's sniff function seems to be applied too late
# therefore some unwanted packets are processed (e.g. tcp packets of ssh session)
# but it still decreases the number of packets that need to be processed by the lfilter function
sniff(prn=self._packet_handler, filter=self._SNIFF_FILTER(), lfilter=self._LFILTER, store=0, iface=self.interface)