Skip to content
8 changes: 4 additions & 4 deletions killerbee_extras_tools/openear/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
# Given a database and a key into the database's networks table,
# initiate a pcap and online database capture.
def startCapture(dev, capChan):
timeLabel = datetime.now().strftime('%Y%m%d-%H%M')
print 'Cap%s: Launching a capture on channel %s.' % (dev, capChan)
timeLabel = datetime.utcnow().strftime('%Y%m%d-%H%M')
print('Cap%s: Launching a capture on channel %s.' % (dev, capChan))
fname = 'zb_c%s_%s.pcap' % (capChan, timeLabel) #fname is -w equiv
signal.signal(signal.SIGINT, interrupt)
trigger = threading.Event()
Expand Down Expand Up @@ -39,7 +39,7 @@ def run(self):
self.kb = KillerBee(device=self.devstring, datasource="Wardrive Live")
self.kb.set_channel(self.channel)
self.kb.sniffer_on()
print "Capturing on \'%s\' at channel %d." % (self.kb.get_dev_info()[0], self.channel)
print("Capturing on \'%s\' at channel %d." % (self.kb.get_dev_info()[0], self.channel))
# loop capturing packets to dblog and file
while not self.trigger.is_set():
packet = self.kb.pnext()
Expand All @@ -52,5 +52,5 @@ def run(self):
self.kb.sniffer_off()
self.kb.close()
self.pd.close()
print "%d packets captured" % self.packetcount
print("%d packets captured" % self.packetcount)

27 changes: 15 additions & 12 deletions killerbee_extras_tools/openear/gps.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import gps, os, time
import os
import time

import gps

session = gps.gps()
session.poll()
Expand All @@ -10,18 +13,18 @@
# a = altitude, d = date/time, m=mode,
# o=postion/fix, s=status, y=satellites

print
print ' GPS reading'
print '----------------------------------------'
print 'fix ' , ("NO_FIX","FIX","DGPS_FIX")[session.fix.mode - 1]
print 'latitude ' , session.fix.latitude
print 'longitude ' , session.fix.longitude
print 'time utc ' , session.utc, session.fix.time
print 'altitude ' , session.fix.altitude
print('')
print(' GPS reading')
print('----------------------------------------')
print('fix ' , ("NO_FIX","FIX","DGPS_FIX")[session.fix.mode - 1])
print('latitude ' , session.fix.latitude)
print('longitude ' , session.fix.longitude)
print('time utc ' , session.utc, session.fix.time)
print('altitude ' , session.fix.altitude)

print
print ' Satellites (total of', len(session.satellites) , ' in view)'
print('')
print(' Satellites (total of', len(session.satellites) , ' in view)')
for i in session.satellites:
print '\t', i
print('\t', i)

time.sleep(3)
20 changes: 8 additions & 12 deletions killerbee_extras_tools/openear/gps/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,24 +31,20 @@ def connect(self, host, port):
host, port = host[:i], host[i+1:]
try: port = int(port)
except ValueError:
raise socket.error, "nonnumeric port"
#if self.verbose > 0:
# print 'connect:', (host, port)
raise socket.error("nonnumeric port")
msg = "getaddrinfo returns an empty list"
self.sock = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
#if self.debuglevel > 0: print 'connect:', (host, port)
self.sock.connect(sa)
except socket.error, msg:
#if self.debuglevel > 0: print 'connect fail:', (host, port)
except socket.error as msg:
self.close()
continue
break
if not self.sock:
raise socket.error, msg
raise socket.error(msg)

def close(self):
if self.sock:
Expand Down Expand Up @@ -128,22 +124,22 @@ def json_unpack(self, buf):
def asciify(d):
"De-Unicodify everything so we can copy dicts into Python objects."
t = {}
for (k, v) in d.items():
for (k, v) in list(d.items()):
ka = k.encode("ascii")
if type(v) == type(u"x"):
if type(v) == type("x"):
va = v.encode("ascii")
elif type(v) == type({}):
va = asciify(v)
elif type(v) == type([]):
va = map(asciify, v)
va = list(map(asciify, v))
else:
va = v
t[ka] = va
return t
self.data = dictwrapper(**asciify(json.loads(buf.strip(), encoding="ascii")))
# Should be done for any other array-valued subobjects, too.
if self.data["class"] == "SKY" and hasattr(self.data, "satellites"):
self.data.satellites = map(lambda x: dictwrapper(**x), self.data.satellites)
self.data.satellites = [dictwrapper(**x) for x in self.data.satellites]

def stream(self, flags=0, outfile=None):
"Control streaming reports from the daemon,"
Expand Down Expand Up @@ -182,7 +178,7 @@ def __init__(self, **ddict):
def get(self, k, d=None):
return self.__dict__.get(k, d)
def keys(self):
return self.__dict__.keys()
return list(self.__dict__.keys())
def __getitem__(self, key):
"Emulate dictionary, for new-style interface."
return self.__dict__[key]
Expand Down
14 changes: 7 additions & 7 deletions killerbee_extras_tools/openear/gps/gps.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
# now live in a different module.
#
import time
from client import *
from .client import *

NaN = float('nan')
def isnan(x): return str(x) == 'nan'
Expand Down Expand Up @@ -235,14 +235,14 @@ def default(i, vbit=0, cnv=float):
d1 = int(prefix.pop())
newsats = []
for i in range(d1):
newsats.append(gps.satellite(*map(int, satellites[i].split())))
newsats.append(gps.satellite(*list(map(int, satellites[i].split()))))
self.satellites = newsats
self.valid |= SATELLITE_SET

def __oldstyle_shim(self):
# The rest is backwards compatibility for the old interface
def default(k, dflt, vbit=0):
if k not in self.data.keys():
if k not in list(self.data.keys()):
return dflt
else:
self.valid |= vbit
Expand Down Expand Up @@ -283,7 +283,7 @@ def default(k, dflt, vbit=0):
elif self.data.get("class") == "SKY":
for attrp in "xyvhpg":
setattr(self, attrp+"dop", default(attrp+"dop", NaN, DOP_SET))
if "satellites" in self.data.keys():
if "satellites" in list(self.data.keys()):
self.satellites = []
for sat in self.data['satellites']:
self.satellites.append(gps.satellite(PRN=sat['PRN'], elevation=sat['el'], azimuth=sat['az'], ss=sat['ss'], used=sat['used']))
Expand Down Expand Up @@ -314,7 +314,7 @@ def poll(self):
self.valid |= PACKET_SET
return 0

def next(self):
def __next__(self):
if self.poll() == -1:
raise StopIteration
if hasattr(self, "data"):
Expand Down Expand Up @@ -356,7 +356,7 @@ def stream(self, flags=0, outfile=None):
if switch == '-v':
verbose = True
if len(arguments) > 2:
print 'Usage: gps.py [-v] [host [port]]'
print('Usage: gps.py [-v] [host [port]]')
sys.exit(1)

opts = { "verbose" : verbose }
Expand All @@ -369,6 +369,6 @@ def stream(self, flags=0, outfile=None):
session.set_raw_hook(lambda s: sys.stdout.write(s.strip() + "\n"))
session.stream(WATCH_ENABLE|WATCH_NEWSTYLE)
for report in session:
print report
print(report)

# gps.py ends here
11 changes: 7 additions & 4 deletions killerbee_extras_tools/openear/gps/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,10 @@ def CalcRad(lat):
r = r * 1000.0 # Convert to meters
return r

def EarthDistance((lat1, lon1), (lat2, lon2)):
def EarthDistance(xxx_todo_changeme, xxx_todo_changeme1):
"Distance in meters between two points specified in degrees."
(lat1, lon1) = xxx_todo_changeme
(lat2, lon2) = xxx_todo_changeme1
x1 = CalcRad(lat1) * math.cos(Deg2Rad(lon1)) * math.sin(Deg2Rad(90-lat1))
x2 = CalcRad(lat2) * math.cos(Deg2Rad(lon2)) * math.sin(Deg2Rad(90-lat2))
y1 = CalcRad(lat1) * math.sin(Deg2Rad(lon1)) * math.sin(Deg2Rad(90-lat1))
Expand All @@ -67,8 +69,10 @@ def EarthDistance((lat1, lon1), (lat2, lon2)):
elif a < -1: a = -1
return CalcRad((lat1+lat2) / 2) * math.acos(a)

def MeterOffset((lat1, lon1), (lat2, lon2)):
def MeterOffset(xxx_todo_changeme2, xxx_todo_changeme3):
"Return offset in meters of second arg from first."
(lat1, lon1) = xxx_todo_changeme2
(lat2, lon2) = xxx_todo_changeme3
dx = EarthDistance((lat1, lon1), (lat1, lon2))
dy = EarthDistance((lat1, lon1), (lat2, lon1))
if lat1 < lat2: dy *= -1
Expand All @@ -83,7 +87,7 @@ def isotime(s):
date = int(s)
msec = s - date
date = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s))
return date + "." + `msec`[2:]
return date + "." + repr(msec)[2:]
elif type(s) == type(""):
if s[-1] == "Z":
s = s[:-1]
Expand All @@ -98,4 +102,3 @@ def isotime(s):
raise TypeError

# End

59 changes: 30 additions & 29 deletions killerbee_extras_tools/openear/scanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@
# ZBScanner
# rmelgares 2011
# Promiscious capture on multiple channels at once
from __future__ import print_function

import gps, time, os, signal, sys, operator, threading
import string, socket, struct, datetime
import datetime
import queue
import signal
import threading

import gps

from killerbee import *
import Queue

# Globals
session = ""
Expand All @@ -24,7 +28,7 @@

def broadcast_event(data):
''' Send broadcast data to all active threads '''
print "\nShutting down threads."
print("\nShutting down threads.")
for q in active_queues:
q.put(data)

Expand All @@ -33,19 +37,19 @@ class LocationThread(threading.Thread):
def __init__(self):
global active_queues
threading.Thread.__init__(self)
self.mesg = Queue.Queue()
self.mesg = queue.Queue()
active_queues.append(self.mesg)

def run(self):
global session
global active_queues
global longitude, latitude, altitude, last_seen
message = ""
last_seen = datetime.datetime.now()
last_seen = datetime.datetime.utcnow()
while(1):
try:
message = self.mesg.get(timeout=.00001)
except Queue.Empty:
except queue.Empty:
pass
if message == "shutdown":
break
Expand All @@ -57,12 +61,12 @@ def run(self):
latitude = t_latitude
longitude = t_longitude
altitude = t_altitude
last_seen = datetime.datetime.now()
last_seen = datetime.datetime.utcnow()
else:
end_time = datetime.datetime.now()
end_time = datetime.datetime.utcnow()
elapsed_time = end_time - last_seen
print chr(0x1b) + "[2;5fElapsed time since last location change: %s" % str(elapsed_time)
print chr(0x1b) + "[3;5fLat: %f, Long: %f, Alt: %f." % (latitude, longitude, altitude)
print(chr(0x1b) + "[2;5fElapsed time since last location change: %s" % str(elapsed_time))
print(chr(0x1b) + "[3;5fLat: %f, Long: %f, Alt: %f." % (latitude, longitude, altitude))
time.sleep(1)


Expand All @@ -71,7 +75,7 @@ class CaptureThread(threading.Thread):
def __init__(self, dev, channel, pd):
global active_queues
threading.Thread.__init__(self)
self.mesg = Queue.Queue()
self.mesg = queue.Queue()
active_queues.append(self.mesg)
self.channel = channel
self.freq = (channel - 10) * 5 + 2400
Expand All @@ -91,7 +95,7 @@ def run(self):
while (True):
try:
message = self.mesg.get(timeout=.00001)
except Queue.Empty:
except queue.Empty:
pass
if message == "shutdown":
break
Expand All @@ -100,19 +104,19 @@ def run(self):
self.packetcount+=1
if arg_gps:
gpsdata = (longitude, latitude, altitude)
self.pd.pcap_dump(packet['bytes'], ant_dbm=packet['dbm'], freq_mhz=self.freq, location=map(float, gpsdata))
self.pd.pcap_dump(packet['bytes'], ant_dbm=packet['dbm'], freq_mhz=self.freq, location=list(map(float, gpsdata)))
if arg_db:self.kb.dblog.add_packet(full=packet, location=gpsdata)
else:
self.pd.pcap_dump(packet['bytes'])
if arg_db:self.kb.dblog.add_packet(full=packet)
print chr(0x1b) + "[%d;5fChannel %d: %d packets captured." % (self.channel - 6, self.channel, self.packetcount)
print(chr(0x1b) + "[%d;5fChannel %d: %d packets captured." % (self.channel - 6, self.channel, self.packetcount))
# trigger threading.Event set to false, so shutdown thread
if arg_verbose:
print "%s on channel %d shutting down..." % (threading.currentThread().getName(), self.channel)
print("%s on channel %d shutting down..." % (threading.currentThread().getName(), self.channel))
self.kb.sniffer_off()
self.kb.close()
self.pd.close()
print "%d packets captured on channel %d" % (self.packetcount, self.channel)
print("%d packets captured on channel %d" % (self.packetcount, self.channel))

def signal_handler(signal, frame):
''' Signal handler called on keyboard interrupt to exit threads and exit scanner script'''
Expand Down Expand Up @@ -146,37 +150,34 @@ def main(args):
else:
kbdev_info = kbutils.devlist()
channel = 11
print "Found %d devices." % len(kbdev_info)
print("Found %d devices." % len(kbdev_info))
if len(kbdev_info) < 1:
exit(1)
if arg_gps == True:
print "Initializing GPS device %s ... "% (arg_gps_devstring),
print("Initializing GPS device %s ... "% (arg_gps_devstring), end=' ')
session = gps.gps()
session.poll()
session.stream()
print "Waiting for fix... ",
print("Waiting for fix... ", end=' ')
while(session.fix.mode == 1):
session.poll()
print "Fix acquired!"
print("Fix acquired!")
t = LocationThread()
t.start()
time.sleep(2)
for i in range(0, len(kbdev_info)):
if kbdev_info[i][0] == arg_gps_devstring:
print "Skipping device %s" % arg_gps_devstring
print("Skipping device %s" % arg_gps_devstring)
else:
print 'Device at %s: \'%s\'' % (kbdev_info[i][0], kbdev_info[i][1])
print('Device at %s: \'%s\'' % (kbdev_info[i][0], kbdev_info[i][1]))
if channel <= 26:
print '\tAssigning to channel %d.' % channel
timeLabel = datetime.datetime.now().strftime('%Y%m%d-%H%M')
print('\tAssigning to channel %d.' % channel)
timeLabel = datetime.datetime.utcnow().strftime('%Y%m%d-%H%M')
fname = 'zb_c%s_%s.pcap' % (channel, timeLabel) #fname is -w equiv
pcap = PcapDumper(DLT_IEEE802_15_4, fname, ppi=arg_ppi)
t = CaptureThread(kbdev_info[i][0], channel, pcap)
t.start()
channel += 1
os.system('clear')
print chr(0x1b) + "[1;5fLive Stats:"
print(chr(0x1b) + "[1;5fLive Stats:")
while True: pass

if __name__ == '__main__':
main(sys.argv)
Loading