Skip to content

Commit

Permalink
code compatible with python2 and python3
Browse files Browse the repository at this point in the history
  • Loading branch information
pgawlowicz committed Jul 15, 2016
1 parent ac5eda8 commit 97f0095
Show file tree
Hide file tree
Showing 10 changed files with 85 additions and 68 deletions.
16 changes: 8 additions & 8 deletions examples/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def execute(dev,itype):
# ensure dev is a wireless interfaces
wifaces = pyw.winterfaces()
if dev not in wifaces:
print "Device {0} is not wireless, use one of {1}".format(dev,wifaces)
print("Device {0} is not wireless, use one of {1}".format(dev,wifaces))

# get info dicts
dinfo = pyw.devinfo(dev)
Expand All @@ -31,7 +31,7 @@ def execute(dev,itype):
msg += "\tInet: {0} Bcast: {1} Mask: {2}\n".format(iinfo['inet'],
iinfo['bcast'],
iinfo['mask'])
print msg
print(msg)

if itype == 'all' or itype == 'dev':
msg = "Device {0}\n".format(card.dev)
Expand All @@ -46,7 +46,7 @@ def execute(dev,itype):
dinfo['RF'],
dinfo['CHW'],
dinfo['CF'])
print msg
print(msg)

if itype == 'all' or itype == 'phy':
msg = "Wiphy phy{0}\n".format(card.phy)
Expand Down Expand Up @@ -78,11 +78,11 @@ def execute(dev,itype):
msg += " (disabled)\n"
else:
msg += "\n"
print msg
print(msg)

if __name__ == '__main__':
# create arg parser and parse command line args
print "Wireless Device Info Display using PyRIC v{0}".format(pyric.__version__)
print("Wireless Device Info Display using PyRIC v{0}".format(pyric.__version__))
argp = ap.ArgumentParser(description="Wireless Device Data")
argp.add_argument('-d','--dev',help="Wireless Device")
argp.add_argument('-t','--type',help="Info type one of {all|if|dev|phy}")
Expand All @@ -91,12 +91,12 @@ def execute(dev,itype):
dname = args.dev
infotype = args.type
if dname is None:
print "usage: python info.py -d <dev> [-t one of {all|if|dev|phy}]"
print("usage: python info.py -d <dev> [-t one of {all|if|dev|phy}]")
sys.exit(0)
if infotype is None: infotype = 'all'
if infotype not in ['all','if','dev','phy']:
print "usage: python info.py -d <dev> [-t one of {all|if|dev|phy}]"
print("usage: python info.py -d <dev> [-t one of {all|if|dev|phy}]")
sys.exit(0)
execute(dname,infotype)
except pyric.error as e:
print e
print(e)
40 changes: 20 additions & 20 deletions examples/pentest.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,18 @@
from pyric.utils.channels import rf2ch # rf to channel conversion

def execute(dev):
print 'Setting up...'
print('Setting up...')
# ensure dev is a wireless interfaces
ifaces = pyw.interfaces()
wifaces = pyw.winterfaces()
if dev not in ifaces:
print "Device {0} is not valid, use one of {1}".format(dev,ifaces)
print("Device {0} is not valid, use one of {1}".format(dev,ifaces))
return
elif dev not in wifaces:
print "Device {0} is not wireless, use one of {1}".format(dev,wifaces)
print("Device {0} is not wireless, use one of {1}".format(dev,wifaces))

# get a Card & info for dev
print "Regulatory Domain currently: ", pyw.regget()
print("Regulatory Domain currently: ", pyw.regget())
dinfo = pyw.devinfo(dev)
card = dinfo['card']
pinfo = pyw.phyinfo(card)
Expand All @@ -44,59 +44,59 @@ def execute(dev):
msg += "\tSupports modes {0}\n".format(pinfo['modes'])
msg += "\tSupports commands {0}".format(pinfo['commands'])
msg += "\thw addr {0}".format(pyw.macget(card))
print msg
print(msg)

# prepare a virtual interface named pent0 in monitor mode
# delete all ifaces on the phy to avoid interference
print 'Preparing pent0 for monitor mode'
print('Preparing pent0 for monitor mode')
pdev = 'pent0'
for iface in pyw.ifaces(card):
print "deleting {0} in mode {1}".format(iface[0],iface[1])
print("deleting {0} in mode {1}".format(iface[0],iface[1]))
pyw.devdel(iface[0])

# not we use the card that was deleted here. We can do this because
# devadd uses the physical index so even though the ifindex and dev are
# no longer valid, the physical index still is
pcard = pyw.devadd(card, pdev, 'monitor')
pyw.up(pcard)
print "Using", pcard
print("Using", pcard)

print "Setting channel to 6 NOHT"
print("Setting channel to 6 NOHT")
pyw.chset(pcard,6,None)
msg = "Virtual interface {0} in monitor mode on ch 6".format(pcard)
print msg + ", using hwaddr: {0}".format(pyw.macget(pcard))
print(msg + ", using hwaddr: {0}".format(pyw.macget(pcard)))

# DO stuff here
try:
print 'Now ready to do stuff'
print 'For example, run wireshark to verify card is seeing all packets'
print 'Hit Ctrl-C to quit and restore'
print('Now ready to do stuff')
print('For example, run wireshark to verify card is seeing all packets')
print('Hit Ctrl-C to quit and restore')
while True: time.sleep(1)
except KeyboardInterrupt:
pass

# restore original
print "Restoring..."
print "deleting ", pcard
print("Restoring...")
print("deleting ", pcard)
pyw.devdel(pcard)

print 'Restoring', card, 'mode =', dinfo['mode'], 'mac =', dinfo['mac']
print('Restoring', card, 'mode =', dinfo['mode'], 'mac =', dinfo['mac'])
card = pyw.devadd(card,card.dev,dinfo['mode'])
pyw.macset(card,dinfo['mac'])
pyw.up(card)
print "card ", card, " restored"
print("card ", card, " restored")

if __name__ == '__main__':
# create arg parser and parse command line args
print "Wireless Pentest Environment using PyRIC v{0}".format(pyric.version)
print("Wireless Pentest Environment using PyRIC v{0}".format(pyric.version))
argp = ap.ArgumentParser(description="Wireless Pentest")
argp.add_argument('-d','--dev',help="Pentesting Wireless Device")
args = argp.parse_args()
try:
dname = args.dev
if dname is None:
print "usage: python pentest.py -d <dev>"
print("usage: python pentest.py -d <dev>")
else:
execute(dname)
except pyric.error as e:
print e
print(e)
6 changes: 5 additions & 1 deletion pyric/lib/libnl.py
Original file line number Diff line number Diff line change
Expand Up @@ -686,7 +686,11 @@ def _attrpack_(a,v,d):
elif d == nlh.NLA_U16: attr = struct.pack("H",v)
elif d == nlh.NLA_U32: attr = struct.pack("I",v)
elif d == nlh.NLA_U64: attr = struct.pack("Q",v)
elif d == nlh.NLA_STRING: attr = struct.pack("{0}sx".format(len(v)),v)
elif d == nlh.NLA_STRING:
try:
attr = struct.pack("{0}sx".format(len(v)),v)
except:
attr = struct.pack("{0}sx".format(len(v)), bytes(v, 'utf-8'))
elif d == nlh.NLA_FLAG: attr = '' # a 0 sized attribute
elif d == nlh.NLA_MSECS: attr = struct.pack("Q",v)
elif d == nlh.NLA_NESTED:
Expand Down
5 changes: 4 additions & 1 deletion pyric/net/if_h.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,10 @@ def ifreq(ifrn,ifru=None,param=None):
# pack the nic
try:
# NOTE: don't need to keep the name to 16 chars as struct does it for us
ifr = struct.pack(ifr_name,ifrn)
try:
ifr = struct.pack(ifr_name,ifrn)
except:
ifr = struct.pack(ifr_name, bytes(ifrn, 'utf-8'))
except struct.error:
raise AttributeError("ifr_ifrn (dev name) {0} is invalid".format(ifrn))

Expand Down
4 changes: 2 additions & 2 deletions pyric/nlhelp/nlsearch.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
try:
# first three lines are comments, 4th line is empty
cin = open(cmdpath,'r')
for _ in xrange(4): _in = cin.readline()
for _ in range(4): _in = cin.readline()
commands = json.loads(cin.readline())
cmdlookup = json.loads(cin.readline())
except:
Expand All @@ -65,7 +65,7 @@
try:
# first three lines are comments, 3th line is empty
ain = open(attrpath,'r')
for _ in xrange(4): _in = ain.readline()
for _ in range(4): _in = ain.readline()
attributes = json.loads(ain.readline())
attrlookup = json.loads(ain.readline())
except:
Expand Down
14 changes: 7 additions & 7 deletions pyric/pyw.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,14 @@
import pyric # pyric exception
import re # check addr validity
from pyric.nlhelp.nlsearch import cmdbynum # get command name
from pyric.utils import channels # channel related
from pyric.utils import rfkill # block/unblock
import pyric.utils.channels as channels # channel related
import pyric.utils.rfkill as rfkill # block/unblock
import pyric.utils.hardware as hw # device related
from pyric.utils import ouifetch # get oui dict
import pyric.utils.ouifetch as ouifetch # get oui dict
import pyric.net.netlink_h as nlh # netlink definition
import pyric.net.genetlink_h as genlh # genetlink definition
import pyric.net.wireless.nl80211_h as nl80211h # nl80211 definition
from pyric.net.wireless import wlan # IEEE 802.11 Std definition
import pyric.net.wireless.wlan as wlan # IEEE 802.11 Std definition
import pyric.net.sockios_h as sioch # sockios constants
import pyric.net.if_h as ifh # ifreq structure
import pyric.lib.libnl as nl # netlink functions
Expand Down Expand Up @@ -1003,7 +1003,7 @@ def devchs(card, *argv):
except IndexError:
return _nlstub_(devchs, card)

return map(channels.rf2ch, phyinfo(card, nlsock)['freqs'])
return list(map(channels.rf2ch, phyinfo(card, nlsock)['freqs']))

def devstds(card, *argv):
"""
Expand Down Expand Up @@ -1730,15 +1730,15 @@ def link(card, *argv):
'failed': sinfo['tx-failed'],
'retries': sinfo['tx-retries'],
'bitrate': {'rate': sinfo['tx-bitrate']['rate']}}
if sinfo['tx-bitrate'].has_key('mcs-index'):
if 'mcs-index' in sinfo['tx-bitrate']:
info['tx']['bitrate']['mcs-index'] = sinfo['tx-bitrate']['mcs-index']
info['tx']['bitrate']['gi'] = sinfo['tx-bitrate']['gi']
info['tx']['bitrate']['width'] = sinfo['tx-bitrate']['width']

info['rx'] = {'bytes': sinfo['rx-bytes'],
'pkts':sinfo['rx-pkts'],
'bitrate': {'rate': sinfo['rx-bitrate']['rate']}}
if sinfo['rx-bitrate'].has_key('mcs-index'):
if 'mcs-index' in sinfo['rx-bitrate']:
info['rx']['bitrate']['mcs-index'] = sinfo['rx-bitrate']['mcs-index']
info['rx']['bitrate']['gi'] = sinfo['rx-bitrate']['gi']
info['rx']['bitrate']['width'] = sinfo['rx-bitrate']['width']
Expand Down
4 changes: 2 additions & 2 deletions pyric/utils/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,11 @@

def channels():
""" :returns:list of all channels """
return sorted(ISM_24_C2F.keys() + UNII_5_C2F.keys() + UNII_4_C2F.keys())
return sorted(list(ISM_24_C2F.keys()) + list(UNII_5_C2F.keys()) + list(UNII_4_C2F.keys()))

def freqs():
""" :returns:list of frequencies """
return sorted(ISM_24_F2C.keys() + UNII_5_F2C.keys()+ UNII_4_F2C.keys())
return sorted(list(ISM_24_F2C.keys()) + list(UNII_5_F2C.keys())+ list(UNII_4_F2C.keys()))

def ch2rf(c):
"""
Expand Down
6 changes: 3 additions & 3 deletions pyric/utils/hardware.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,10 @@ def randhw(ouis=None):
:returns: random hw address
"""
if ouis is None or ouis == []:
o = ":".join(['{0:02x}'.format(random.randint(0,255)) for _ in xrange(3)])
o = ":".join(['{0:02x}'.format(random.randint(0,255)) for _ in range(3)])
else:
o = random.choice(ouis.keys())
u = ":".join(['{0:02x}'.format(random.randint(0,255)) for _ in xrange(3)])
o = random.choice(list(ouis.keys()))
u = ":".join(['{0:02x}'.format(random.randint(0,255)) for _ in range(3)])
return o + ':' + u

def ifcard(dev):
Expand Down
36 changes: 23 additions & 13 deletions pyric/utils/ouifetch.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,17 @@
__email__ = '[email protected]'
__status__ = 'Production'

import urllib2,os,sys,datetime,time

import os,sys,datetime,time
try:
from urllib2 import Request
from urllib2 import urlopen
from urllib2 import URLError
except:
from urllib.request import Request
from urllib.request import urlopen
from urllib.error import URLError

#import argparse as ap
import pyric

Expand Down Expand Up @@ -75,22 +85,22 @@ def fetch(opath=None,verbose=False):
# determine if data path is legit
if opath is None: opath = OUIPATH
if not os.path.isdir(os.path.dirname(opath)):
print "Path to data is incorrect {0}".format(opath)
print("Path to data is incorrect {0}".format(opath))
sys.exit(1)

# fetch oui file from ieee
fout = None

# set up url request
req = urllib2.Request(OUIURL)
req = Request(OUIURL)
req.add_header('User-Agent',"PyRIC +https://github.com/wraith-wireless/PyRIC/")
try:
# retrieve the oui file and parse out generated date
if verbose: print 'Fetching ', OUIURL
res = urllib2.urlopen(req)
if verbose: print "Parsing OUI file"
if verbose: print('Fetching ', OUIURL)
res = urlopen(req)
if verbose: print("Parsing OUI file")

if verbose: print "Opening data file {0} for writing".format(opath)
if verbose: print("Opening data file {0} for writing".format(opath))
fout = open(opath,'w')
gen = datetime.datetime.utcnow().isoformat() # use current time as the first line
fout.write(gen+'\n')
Expand All @@ -110,14 +120,14 @@ def fetch(opath=None,verbose=False):
# write to file & update count
fout.write('{0}\t{1}\n'.format(oui,manuf))
cnt += 1
if verbose: print "{0}:\t{1}\t{2}".format(cnt,oui,manuf)
print "Wrote {0} OUIs in {1:.3} secs".format(cnt,time.time()-t)
except urllib2.URLError as e:
print "Error fetching oui file: {0}".format(e)
if verbose: print("{0}:\t{1}\t{2}".format(cnt,oui,manuf))
print("Wrote {0} OUIs in {1:.3} secs".format(cnt,time.time()-t))
except URLError as e:
print("Error fetching oui file: {0}".format(e))
except IOError as e:
print "Error opening output file {0}".format(e)
print("Error opening output file {0}".format(e))
except Exception as e:
print "Error parsing oui file: {0}".format(e)
print("Error parsing oui file: {0}".format(e))
finally:
if fout: fout.close()

Expand Down
Loading

0 comments on commit 97f0095

Please sign in to comment.