tests: Use python3 compatible print statement

This patch is made by using 2to3 command.

$ find . -name *.py | xargs 2to3 -f print -w -n

Signed-off-by: Masashi Honma <masashi.honma@gmail.com>
This commit is contained in:
Masashi Honma 2019-01-24 16:45:42 +09:00 committed by Jouni Malinen
parent bab493b904
commit 89896c0008
33 changed files with 480 additions and 475 deletions

View file

@ -26,7 +26,7 @@ summary_file = None
success_file = None success_file = None
def summary(txt): def summary(txt):
print txt print(txt)
if summary_file: if summary_file:
with open(summary_file, 'a') as f: with open(summary_file, 'a') as f:
f.write(txt + "\n") f.write(txt + "\n")
@ -43,11 +43,11 @@ def wpas_connect():
try: try:
ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)] ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)]
except OSError as error: except OSError as error:
print "Could not find hostapd: ", error print("Could not find hostapd: ", error)
return None return None
if len(ifaces) < 1: if len(ifaces) < 1:
print "No hostapd control interface found" print("No hostapd control interface found")
return None return None
for ctrl in ifaces: for ctrl in ifaces:
@ -133,23 +133,23 @@ class HandoverServer(nfc.handover.HandoverServer):
def process_request(self, request): def process_request(self, request):
summary("HandoverServer - request received") summary("HandoverServer - request received")
try: try:
print "Parsed handover request: " + request.pretty() print("Parsed handover request: " + request.pretty())
except Exception as e: except Exception as e:
print e print(e)
print str(request).encode("hex") print(str(request).encode("hex"))
sel = nfc.ndef.HandoverSelectMessage(version="1.2") sel = nfc.ndef.HandoverSelectMessage(version="1.2")
for carrier in request.carriers: for carrier in request.carriers:
print "Remote carrier type: " + carrier.type print("Remote carrier type: " + carrier.type)
if carrier.type == "application/vnd.wfa.wsc": if carrier.type == "application/vnd.wfa.wsc":
summary("WPS carrier type match - add WPS carrier record") summary("WPS carrier type match - add WPS carrier record")
data = wpas_get_handover_sel() data = wpas_get_handover_sel()
if data is None: if data is None:
summary("Could not get handover select carrier record from hostapd") summary("Could not get handover select carrier record from hostapd")
continue continue
print "Handover select carrier record from hostapd:" print("Handover select carrier record from hostapd:")
print data.encode("hex") print(data.encode("hex"))
if "OK" in wpas_report_handover(carrier.record, data): if "OK" in wpas_report_handover(carrier.record, data):
success_report("Handover reported successfully") success_report("Handover reported successfully")
else: else:
@ -158,12 +158,12 @@ class HandoverServer(nfc.handover.HandoverServer):
message = nfc.ndef.Message(data); message = nfc.ndef.Message(data);
sel.add_carrier(message[0], "active", message[1:]) sel.add_carrier(message[0], "active", message[1:])
print "Handover select:" print("Handover select:")
try: try:
print sel.pretty() print(sel.pretty())
except Exception as e: except Exception as e:
print e print(e)
print str(sel).encode("hex") print(str(sel).encode("hex"))
summary("Sending handover select") summary("Sending handover select")
self.success = True self.success = True
@ -174,7 +174,7 @@ def wps_tag_read(tag):
success = False success = False
if len(tag.ndef.message): if len(tag.ndef.message):
for record in tag.ndef.message: for record in tag.ndef.message:
print "record type " + record.type print("record type " + record.type)
if record.type == "application/vnd.wfa.wsc": if record.type == "application/vnd.wfa.wsc":
summary("WPS tag - send to hostapd") summary("WPS tag - send to hostapd")
success = wpas_tag_read(tag.ndef.message) success = wpas_tag_read(tag.ndef.message)
@ -193,7 +193,7 @@ def rdwr_connected_write(tag):
global write_data global write_data
tag.ndef.message = str(write_data) tag.ndef.message = str(write_data)
success_report("Tag write succeeded") success_report("Tag write succeeded")
print "Done - remove tag" print("Done - remove tag")
global only_one global only_one
if only_one: if only_one:
global continue_loop global continue_loop
@ -211,7 +211,7 @@ def wps_write_config_tag(clf, wait_remove=True):
summary("Could not get WPS config token from hostapd") summary("Could not get WPS config token from hostapd")
return return
print "Touch an NFC tag" print("Touch an NFC tag")
clf.connect(rdwr={'on-connect': rdwr_connected_write}) clf.connect(rdwr={'on-connect': rdwr_connected_write})
@ -224,7 +224,7 @@ def wps_write_password_tag(clf, wait_remove=True):
summary("Could not get WPS password token from hostapd") summary("Could not get WPS password token from hostapd")
return return
print "Touch an NFC tag" print("Touch an NFC tag")
clf.connect(rdwr={'on-connect': rdwr_connected_write}) clf.connect(rdwr={'on-connect': rdwr_connected_write})
@ -233,11 +233,11 @@ def rdwr_connected(tag):
summary("Tag connected: " + str(tag)) summary("Tag connected: " + str(tag))
if tag.ndef: if tag.ndef:
print "NDEF tag: " + tag.type print("NDEF tag: " + tag.type)
try: try:
print tag.ndef.message.pretty() print(tag.ndef.message.pretty())
except Exception as e: except Exception as e:
print e print(e)
success = wps_tag_read(tag) success = wps_tag_read(tag)
if only_one and success: if only_one and success:
global continue_loop global continue_loop
@ -250,13 +250,13 @@ def rdwr_connected(tag):
def llcp_startup(clf, llc): def llcp_startup(clf, llc):
print "Start LLCP server" print("Start LLCP server")
global srv global srv
srv = HandoverServer(llc) srv = HandoverServer(llc)
return llc return llc
def llcp_connected(llc): def llcp_connected(llc):
print "P2P LLCP connected" print("P2P LLCP connected")
global wait_connection global wait_connection
wait_connection = False wait_connection = False
global srv global srv
@ -304,7 +304,7 @@ def main():
try: try:
if not clf.open("usb"): if not clf.open("usb"):
print "Could not open connection with an NFC device" print("Could not open connection with an NFC device")
raise SystemExit raise SystemExit
if args.command == "write-config": if args.command == "write-config":
@ -317,7 +317,7 @@ def main():
global continue_loop global continue_loop
while continue_loop: while continue_loop:
print "Waiting for a tag or peer to be touched" print("Waiting for a tag or peer to be touched")
wait_connection = True wait_connection = True
try: try:
if not clf.connect(rdwr={'on-connect': rdwr_connected}, if not clf.connect(rdwr={'on-connect': rdwr_connected},
@ -325,7 +325,7 @@ def main():
'on-connect': llcp_connected}): 'on-connect': llcp_connected}):
break break
except Exception as e: except Exception as e:
print "clf.connect failed" print("clf.connect failed")
global srv global srv
if only_one and srv and srv.success: if only_one and srv and srv.success:

View file

@ -75,11 +75,11 @@ class HWSimRadio(object):
def create(args): def create(args):
print 'Created radio %d' % c.create_radio(n_channels=args.channels, print('Created radio %d' % c.create_radio(n_channels=args.channels,
use_chanctx=args.chanctx) use_chanctx=args.chanctx))
def destroy(args): def destroy(args):
print c.destroy_radio(args.radio) print(c.destroy_radio(args.radio))
if __name__ == '__main__': if __name__ == '__main__':
import argparse import argparse

View file

@ -111,7 +111,7 @@ class RFKill(object):
@classmethod @classmethod
def block_all(cls, t=TYPE_ALL): def block_all(cls, t=TYPE_ALL):
rfk = open('/dev/rfkill', 'w') rfk = open('/dev/rfkill', 'w')
print rfk print(rfk)
s = struct.pack(_event_struct, 0, t, _OP_CHANGE_ALL, 1, 0) s = struct.pack(_event_struct, 0, t, _OP_CHANGE_ALL, 1, 0)
rfk.write(s) rfk.write(s)
rfk.close() rfk.close()
@ -145,6 +145,6 @@ class RFKill(object):
if __name__ == "__main__": if __name__ == "__main__":
for r, s, h in RFKill.list(): for r, s, h in RFKill.list():
print "%d: %s: %s" % (r.idx, r.name, r.type_name) print("%d: %s: %s" % (r.idx, r.name, r.type_name))
print "\tSoft blocked: %s" % ("yes" if s else "no") print("\tSoft blocked: %s" % ("yes" if s else "no"))
print "\tHard blocked: %s" % ("yes" if h else "no") print("\tHard blocked: %s" % ("yes" if h else "no"))

View file

@ -49,7 +49,7 @@ def reset_devs(dev, apdev):
d.reset() d.reset()
except Exception as e: except Exception as e:
logger.info("Failed to reset device " + d.ifname) logger.info("Failed to reset device " + d.ifname)
print str(e) print(str(e))
ok = False ok = False
wpas = None wpas = None
@ -76,7 +76,7 @@ def reset_devs(dev, apdev):
hapd.remove(ap['ifname']) hapd.remove(ap['ifname'])
except Exception as e: except Exception as e:
logger.info("Failed to remove hostapd interface") logger.info("Failed to remove hostapd interface")
print str(e) print(str(e))
ok = False ok = False
return ok return ok
@ -94,8 +94,8 @@ def add_log_file(conn, test, run, type, path):
conn.execute(sql, params) conn.execute(sql, params)
conn.commit() conn.commit()
except Exception as e: except Exception as e:
print "sqlite: " + str(e) print("sqlite: " + str(e))
print "sql: %r" % (params, ) print("sql: %r" % (params, ))
def report(conn, prefill, build, commit, run, test, result, duration, logdir, def report(conn, prefill, build, commit, run, test, result, duration, logdir,
sql_commit=True): sql_commit=True):
@ -113,8 +113,8 @@ def report(conn, prefill, build, commit, run, test, result, duration, logdir,
if sql_commit: if sql_commit:
conn.commit() conn.commit()
except Exception as e: except Exception as e:
print "sqlite: " + str(e) print("sqlite: " + str(e))
print "sql: %r" % (params, ) print("sql: %r" % (params, ))
if result == "FAIL": if result == "FAIL":
for log in [ "log", "log0", "log1", "log2", "log3", "log5", for log in [ "log", "log0", "log1", "log2", "log3", "log5",
@ -142,7 +142,7 @@ class DataCollector(object):
l += self._trace_cmd.stdout.read(1) l += self._trace_cmd.stdout.read(1)
res = self._trace_cmd.returncode res = self._trace_cmd.returncode
if res: if res:
print "Failed calling trace-cmd: returned exit status %d" % res print("Failed calling trace-cmd: returned exit status %d" % res)
sys.exit(1) sys.exit(1)
if self._dbus: if self._dbus:
output = os.path.abspath(os.path.join(self._logdir, '%s.dbus' % (self._testname, ))) output = os.path.abspath(os.path.join(self._logdir, '%s.dbus' % (self._testname, )))
@ -152,7 +152,7 @@ class DataCollector(object):
cwd=self._logdir) cwd=self._logdir)
res = self._dbus_cmd.returncode res = self._dbus_cmd.returncode
if res: if res:
print "Failed calling dbus-monitor: returned exit status %d" % res print("Failed calling dbus-monitor: returned exit status %d" % res)
sys.exit(1) sys.exit(1)
def __exit__(self, type, value, traceback): def __exit__(self, type, value, traceback):
if self._tracing: if self._tracing:
@ -249,12 +249,12 @@ def main():
args = parser.parse_args() args = parser.parse_args()
if (args.tests and args.testmodules) or (args.tests and args.mfile) or (args.testmodules and args.mfile): if (args.tests and args.testmodules) or (args.tests and args.mfile) or (args.testmodules and args.mfile):
print 'Invalid arguments - only one of (test, test modules, modules file) can be given.' print('Invalid arguments - only one of (test, test modules, modules file) can be given.')
sys.exit(2) sys.exit(2)
if args.database: if args.database:
if not sqlite3_imported: if not sqlite3_imported:
print "No sqlite3 module found" print("No sqlite3 module found")
sys.exit(2) sys.exit(2)
conn = sqlite3.connect(args.database) conn = sqlite3.connect(args.database)
conn.execute('CREATE TABLE IF NOT EXISTS results (test,result,run,time,duration,build,commitid)') conn.execute('CREATE TABLE IF NOT EXISTS results (test,result,run,time,duration,build,commitid)')
@ -295,17 +295,17 @@ def main():
for t in tests_to_run: for t in tests_to_run:
name = t.__name__.replace('test_', '', 1) name = t.__name__.replace('test_', '', 1)
if t.__doc__ is None: if t.__doc__ is None:
print name + " - MISSING DESCRIPTION" print(name + " - MISSING DESCRIPTION")
else: else:
print name + " - " + t.__doc__ print(name + " - " + t.__doc__)
if conn: if conn:
sql = 'INSERT OR REPLACE INTO tests(test,description) VALUES (?, ?)' sql = 'INSERT OR REPLACE INTO tests(test,description) VALUES (?, ?)'
params = (name, t.__doc__) params = (name, t.__doc__)
try: try:
conn.execute(sql, params) conn.execute(sql, params)
except Exception as e: except Exception as e:
print "sqlite: " + str(e) print("sqlite: " + str(e))
print "sql: %r" % (params,) print("sql: %r" % (params,))
if conn: if conn:
conn.commit() conn.commit()
conn.close() conn.close()
@ -385,7 +385,7 @@ def main():
count = 0 count = 0
if args.stdin_ctrl: if args.stdin_ctrl:
print "READY" print("READY")
sys.stdout.flush() sys.stdout.flush()
num_tests = 0 num_tests = 0
else: else:
@ -413,7 +413,7 @@ def main():
t = tt t = tt
break break
if not t: if not t:
print "NOT-FOUND" print("NOT-FOUND")
sys.stdout.flush() sys.stdout.flush()
continue continue
else: else:
@ -463,7 +463,7 @@ def main():
msg = "START {} {}/{}".format(name, count, num_tests) msg = "START {} {}/{}".format(name, count, num_tests)
logger.info(msg) logger.info(msg)
if args.loglevel == logging.WARNING: if args.loglevel == logging.WARNING:
print msg print(msg)
sys.stdout.flush() sys.stdout.flush()
if t.__doc__: if t.__doc__:
logger.info("Test: " + t.__doc__) logger.info("Test: " + t.__doc__)
@ -480,7 +480,7 @@ def main():
except Exception as e: except Exception as e:
logger.info("Failed to issue TEST-START before " + name + " for " + d.ifname) logger.info("Failed to issue TEST-START before " + name + " for " + d.ifname)
logger.info(e) logger.info(e)
print "FAIL " + name + " - could not start test" print("FAIL " + name + " - could not start test")
if conn: if conn:
conn.close() conn.close()
conn = None conn = None
@ -504,7 +504,7 @@ def main():
if country != "00": if country != "00":
d.dump_monitor() d.dump_monitor()
logger.info("Country code not reset back to 00: is " + country) logger.info("Country code not reset back to 00: is " + country)
print "Country code not reset back to 00: is " + country print("Country code not reset back to 00: is " + country)
result = "FAIL" result = "FAIL"
# Try to wait for cfg80211 regulatory state to # Try to wait for cfg80211 regulatory state to
@ -516,10 +516,10 @@ def main():
if country == "00": if country == "00":
break break
if country == "00": if country == "00":
print "Country code cleared back to 00" print("Country code cleared back to 00")
logger.info("Country code cleared back to 00") logger.info("Country code cleared back to 00")
else: else:
print "Country code remains set - expect following test cases to fail" print("Country code remains set - expect following test cases to fail")
logger.info("Country code remains set - expect following test cases to fail") logger.info("Country code remains set - expect following test cases to fail")
break break
except HwsimSkip as e: except HwsimSkip as e:
@ -535,7 +535,7 @@ def main():
logger.info(e) logger.info(e)
traceback.print_exc() traceback.print_exc()
if args.loglevel == logging.WARNING: if args.loglevel == logging.WARNING:
print "Exception: " + str(e) print("Exception: " + str(e))
result = "FAIL" result = "FAIL"
open('/dev/kmsg', 'w').write('TEST-STOP %s @%.6f\n' % (name, time.time())) open('/dev/kmsg', 'w').write('TEST-STOP %s @%.6f\n' % (name, time.time()))
for d in dev: for d in dev:
@ -547,7 +547,7 @@ def main():
logger.info(e) logger.info(e)
result = "FAIL" result = "FAIL"
if args.no_reset: if args.no_reset:
print "Leaving devices in current state" print("Leaving devices in current state")
else: else:
reset_ok = reset_devs(dev, apdev) reset_ok = reset_devs(dev, apdev)
wpas = None wpas = None
@ -566,8 +566,8 @@ def main():
try: try:
hapd = HostapdGlobal() hapd = HostapdGlobal()
except Exception as e: except Exception as e:
print "Failed to connect to hostapd interface" print("Failed to connect to hostapd interface")
print str(e) print(str(e))
reset_ok = False reset_ok = False
result = "FAIL" result = "FAIL"
hapd = None hapd = None
@ -609,11 +609,11 @@ def main():
result = "{} {} {} {}".format(result, name, diff.total_seconds(), end) result = "{} {} {} {}".format(result, name, diff.total_seconds(), end)
logger.info(result) logger.info(result)
if args.loglevel == logging.WARNING: if args.loglevel == logging.WARNING:
print result print(result)
sys.stdout.flush() sys.stdout.flush()
if not reset_ok: if not reset_ok:
print "Terminating early due to device reset failure" print("Terminating early due to device reset failure")
break break
if args.stdin_ctrl: if args.stdin_ctrl:
set_term_echo(sys.stdin.fileno(), True) set_term_echo(sys.stdin.fileno(), True)
@ -635,15 +635,15 @@ def main():
logger.info("skipped {} test case(s)".format(len(skipped))) logger.info("skipped {} test case(s)".format(len(skipped)))
logger.info("failed tests: " + ' '.join(failed)) logger.info("failed tests: " + ' '.join(failed))
if args.loglevel == logging.WARNING: if args.loglevel == logging.WARNING:
print "failed tests: " + ' '.join(failed) print("failed tests: " + ' '.join(failed))
sys.exit(1) sys.exit(1)
logger.info("passed all {} test case(s)".format(len(passed))) logger.info("passed all {} test case(s)".format(len(passed)))
if len(skipped): if len(skipped):
logger.info("skipped {} test case(s)".format(len(skipped))) logger.info("skipped {} test case(s)".format(len(skipped)))
if args.loglevel == logging.WARNING: if args.loglevel == logging.WARNING:
print "passed all {} test case(s)".format(len(passed)) print("passed all {} test case(s)".format(len(passed)))
if len(skipped): if len(skipped):
print "skipped {} test case(s)".format(len(skipped)) print("skipped {} test case(s)".format(len(skipped)))
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View file

@ -3365,7 +3365,7 @@ def test_ap_hs20_req_operator_icon(dev, apdev):
if "hs20_operator_icon_metadata" not in bss: if "hs20_operator_icon_metadata" not in bss:
raise Exception("hs20_operator_icon_metadata missing from BSS entry") raise Exception("hs20_operator_icon_metadata missing from BSS entry")
if bss["hs20_operator_icon_metadata"] != binascii.hexlify(value): if bss["hs20_operator_icon_metadata"] != binascii.hexlify(value):
print binascii.hexlify(value) print(binascii.hexlify(value))
raise Exception("Unexpected hs20_operator_icon_metadata value: " + raise Exception("Unexpected hs20_operator_icon_metadata value: " +
bss["hs20_operator_icon_metadata"]) bss["hs20_operator_icon_metadata"])

View file

@ -9292,7 +9292,7 @@ def test_ap_wps_upnp_web_oom(dev, apdev, params):
conn.request("GET", "/unknown") conn.request("GET", "/unknown")
try: try:
resp = conn.getresponse() resp = conn.getresponse()
print resp.status print(resp.status)
except: except:
pass pass

View file

@ -1695,7 +1695,7 @@ def test_gas_anqp_venue_url2(dev, apdev):
if 'anqp[277]' not in bss: if 'anqp[277]' not in bss:
raise Exception("Venue URL ANQP-element not seen") raise Exception("Venue URL ANQP-element not seen")
if bss['anqp[277]'] != venue_url: if bss['anqp[277]'] != venue_url:
print venue_url print(venue_url)
raise Exception("Unexpected Venue URL ANQP-element value: " + bss['anqp[277]']) raise Exception("Unexpected Venue URL ANQP-element value: " + bss['anqp[277]'])
if 'anqp_capability_list' not in bss: if 'anqp_capability_list' not in bss:

View file

@ -1316,7 +1316,7 @@ def test_p2p_msg_go_neg_req(dev, apdev):
hapd.mgmt_tx(msg) hapd.mgmt_tx(msg)
frame = hapd.mgmt_rx(timeout=0.1) frame = hapd.mgmt_rx(timeout=0.1)
if frame is not None: if frame is not None:
print frame print(frame)
raise Exception("Unexpected GO Neg Response") raise Exception("Unexpected GO Neg Response")
# missing atributes # missing atributes

View file

@ -1485,7 +1485,7 @@ def test_wpas_ctrl_dump(dev, apdev):
if res == 'FAIL\n': if res == 'FAIL\n':
res = "null" res = "null"
if res != vals[field]: if res != vals[field]:
print "'{}' != '{}'".format(res, vals[field]) print("'{}' != '{}'".format(res, vals[field]))
raise Exception("Mismatch in config field " + field) raise Exception("Mismatch in config field " + field)
if "beacon_int" not in vals: if "beacon_int" not in vals:
raise Exception("Missing config field") raise Exception("Missing config field")

View file

@ -6,6 +6,7 @@
# This software may be distributed under the terms of the BSD license. # This software may be distributed under the terms of the BSD license.
# See README for more details. # See README for more details.
from __future__ import print_function
import curses import curses
import fcntl import fcntl
import logging import logging
@ -374,7 +375,7 @@ def main():
if args.long: if args.long:
extra_args += [ '--long' ] extra_args += [ '--long' ]
if args.codecov: if args.codecov:
print "Code coverage - build separate binaries" print("Code coverage - build separate binaries")
logdir = os.path.join(dir, str(timestamp)) logdir = os.path.join(dir, str(timestamp))
os.makedirs(logdir) os.makedirs(logdir)
subprocess.check_call([os.path.join(scriptsdir, 'build-codecov.sh'), subprocess.check_call([os.path.join(scriptsdir, 'build-codecov.sh'),
@ -427,7 +428,8 @@ def main():
vm = {} vm = {}
for i in range(0, num_servers): for i in range(0, num_servers):
print("\rStarting virtual machine {}/{}".format(i + 1, num_servers)), print("\rStarting virtual machine {}/{}".format(i + 1, num_servers),
end='')
logger.info("Starting virtual machine {}/{}".format(i + 1, num_servers)) logger.info("Starting virtual machine {}/{}".format(i + 1, num_servers))
cmd = [os.path.join(scriptsdir, 'vm-run.sh'), '--delay', str(i), cmd = [os.path.join(scriptsdir, 'vm-run.sh'), '--delay', str(i),
'--timestamp', str(timestamp), '--timestamp', str(timestamp),
@ -448,7 +450,7 @@ def main():
fd = stream.fileno() fd = stream.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL) fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK) fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
print print('')
curses.wrapper(show_progress) curses.wrapper(show_progress)
@ -459,26 +461,26 @@ def main():
failed = get_failed(vm) failed = get_failed(vm)
if first_run_failures: if first_run_failures:
print "To re-run same failure sequence(s):" print("To re-run same failure sequence(s):")
for i in range(0, num_servers): for i in range(0, num_servers):
if len(vm[i]['failed']) == 0: if len(vm[i]['failed']) == 0:
continue continue
print "./vm-run.sh", print("./vm-run.sh", end=' ')
if args.long: if args.long:
print "--long", print("--long", end=' ')
skip = len(vm[i]['fail_seq']) skip = len(vm[i]['fail_seq'])
skip -= min(skip, 30) skip -= min(skip, 30)
for t in vm[i]['fail_seq']: for t in vm[i]['fail_seq']:
if skip > 0: if skip > 0:
skip -= 1 skip -= 1
continue continue
print t, print(t, end=' ')
print print('')
print "Failed test cases:" print("Failed test cases:")
for f in first_run_failures: for f in first_run_failures:
print f, print(f, end=' ')
logger.info("Failed: " + f) logger.info("Failed: " + f)
print print('')
double_failed = [] double_failed = []
for name in failed: for name in failed:
double_failed.append(name) double_failed.append(name)
@ -487,21 +489,21 @@ def main():
if not rerun_failures: if not rerun_failures:
pass pass
elif failed and not double_failed: elif failed and not double_failed:
print "All failed cases passed on retry" print("All failed cases passed on retry")
logger.info("All failed cases passed on retry") logger.info("All failed cases passed on retry")
elif double_failed: elif double_failed:
print "Failed even on retry:" print("Failed even on retry:")
for f in double_failed: for f in double_failed:
print f, print(f, end=' ')
logger.info("Failed on retry: " + f) logger.info("Failed on retry: " + f)
print print('')
res = "TOTAL={} PASS={} FAIL={} SKIP={}".format(total_started, res = "TOTAL={} PASS={} FAIL={} SKIP={}".format(total_started,
total_passed, total_passed,
total_failed, total_failed,
total_skipped) total_skipped)
print(res) print(res)
logger.info(res) logger.info(res)
print "Logs: " + dir + '/' + str(timestamp) print("Logs: " + dir + '/' + str(timestamp))
logger.info("Logs: " + dir + '/' + str(timestamp)) logger.info("Logs: " + dir + '/' + str(timestamp))
for i in range(0, num_servers): for i in range(0, num_servers):
@ -511,11 +513,11 @@ def main():
log = '{}/{}.srv.{}/console'.format(dir, timestamp, i + 1) log = '{}/{}.srv.{}/console'.format(dir, timestamp, i + 1)
with open(log, 'r') as f: with open(log, 'r') as f:
if "Kernel panic" in f.read(): if "Kernel panic" in f.read():
print "Kernel panic in " + log print("Kernel panic in " + log)
logger.info("Kernel panic in " + log) logger.info("Kernel panic in " + log)
if codecov: if codecov:
print "Code coverage - preparing report" print("Code coverage - preparing report")
for i in range(num_servers): for i in range(num_servers):
subprocess.check_call([os.path.join(scriptsdir, subprocess.check_call([os.path.join(scriptsdir,
'process-codecov.sh'), 'process-codecov.sh'),
@ -523,7 +525,7 @@ def main():
str(i)]) str(i)])
subprocess.check_call([os.path.join(scriptsdir, 'combine-codecov.sh'), subprocess.check_call([os.path.join(scriptsdir, 'combine-codecov.sh'),
logdir]) logdir])
print "file://%s/index.html" % logdir print("file://%s/index.html" % logdir)
logger.info("Code coverage report: file://%s/index.html" % logdir) logger.info("Code coverage report: file://%s/index.html" % logdir)
if double_failed or (failed and not rerun_failures): if double_failed or (failed and not rerun_failures):

View file

@ -240,7 +240,7 @@ class WpaSupplicant:
iter = iter + 1 iter = iter + 1
if iter == 60: if iter == 60:
logger.error(self.ifname + ": Driver scan state did not clear") logger.error(self.ifname + ": Driver scan state did not clear")
print "Trying to clear cfg80211/mac80211 scan state" print("Trying to clear cfg80211/mac80211 scan state")
status, buf = self.host.execute(["ifconfig", self.ifname, "down"]) status, buf = self.host.execute(["ifconfig", self.ifname, "down"])
if status != 0: if status != 0:
logger.info("ifconfig failed: " + buf) logger.info("ifconfig failed: " + buf)

View file

@ -30,10 +30,10 @@ from utils import HwsimSkip
from hwsim_wrapper import run_hwsim_test from hwsim_wrapper import run_hwsim_test
def usage(): def usage():
print "USAGE: " + sys.argv[0] + " -t devices" print("USAGE: " + sys.argv[0] + " -t devices")
print "USAGE: " + sys.argv[0] + " -t check_devices" print("USAGE: " + sys.argv[0] + " -t check_devices")
print "USAGE: " + sys.argv[0] + " -d <dut_name> -t <all|sanity|tests_to_run> [-r <ref_name>] [-c <cfg_file.py>] [-m <all|monitor_name>] [-h hwsim_tests][-R][-T][-P][-v]" print("USAGE: " + sys.argv[0] + " -d <dut_name> -t <all|sanity|tests_to_run> [-r <ref_name>] [-c <cfg_file.py>] [-m <all|monitor_name>] [-h hwsim_tests][-R][-T][-P][-v]")
print "USAGE: " + sys.argv[0] print("USAGE: " + sys.argv[0])
def get_devices(devices, duts, refs, monitors): def get_devices(devices, duts, refs, monitors):
for dut in duts: for dut in duts:
@ -215,15 +215,15 @@ def main():
# print help # print help
if requested_tests[0] == "help" and len(requested_hwsim_tests) == 0: if requested_tests[0] == "help" and len(requested_hwsim_tests) == 0:
usage() usage()
print "\nAvailable Devices:" print("\nAvailable Devices:")
for device in devices: for device in devices:
print "\t", device['name'] print("\t", device['name'])
print "\nAvailable tests:" print("\nAvailable tests:")
for test in test_names: for test in test_names:
print "\t", test print("\t", test)
print "\nAvailable hwsim tests:" print("\nAvailable hwsim tests:")
for hwsim_test in hwsim_tests: for hwsim_test in hwsim_tests:
print "\t", hwsim_test.__name__.replace('test_', '', 1) print("\t", hwsim_test.__name__.replace('test_', '', 1))
return return
# show/check devices # show/check devices

View file

@ -24,57 +24,57 @@ import hostapd
def show_devices(devices, setup_params): def show_devices(devices, setup_params):
"""Show/check available devices""" """Show/check available devices"""
print "Devices:" print("Devices:")
for device in devices: for device in devices:
host = rutils.get_host(devices, device['name']) host = rutils.get_host(devices, device['name'])
# simple check if authorized_keys works correctly # simple check if authorized_keys works correctly
status, buf = host.execute(["id"]) status, buf = host.execute(["id"])
if status != 0: if status != 0:
print "[" + host.name + "] - ssh communication: FAILED" print("[" + host.name + "] - ssh communication: FAILED")
continue continue
else: else:
print "[" + host.name + "] - ssh communication: OK" print("[" + host.name + "] - ssh communication: OK")
# check setup_hw works correctly # check setup_hw works correctly
rutils.setup_hw_host(host, setup_params) rutils.setup_hw_host(host, setup_params)
# show uname # show uname
status, buf = host.execute(["uname", "-s", "-n", "-r", "-m", "-o"]) status, buf = host.execute(["uname", "-s", "-n", "-r", "-m", "-o"])
print "\t" + buf print("\t" + buf)
# show ifconfig # show ifconfig
ifaces = re.split('; | |, ', host.ifname) ifaces = re.split('; | |, ', host.ifname)
for iface in ifaces: for iface in ifaces:
status, buf = host.execute(["ifconfig", iface]) status, buf = host.execute(["ifconfig", iface])
if status != 0: if status != 0:
print "\t" + iface + " failed\n" print("\t" + iface + " failed\n")
continue continue
lines = buf.splitlines() lines = buf.splitlines()
for line in lines: for line in lines:
print "\t" + line print("\t" + line)
# check hostapd, wpa_supplicant, iperf exist # check hostapd, wpa_supplicant, iperf exist
status, buf = host.execute([setup_params['wpa_supplicant'], "-v"]) status, buf = host.execute([setup_params['wpa_supplicant'], "-v"])
if status != 0: if status != 0:
print "\t" + setup_params['wpa_supplicant'] + " not find\n" print("\t" + setup_params['wpa_supplicant'] + " not find\n")
continue continue
lines = buf.splitlines() lines = buf.splitlines()
for line in lines: for line in lines:
print "\t" + line print("\t" + line)
print "" print("")
status, buf = host.execute([setup_params['hostapd'], "-v"]) status, buf = host.execute([setup_params['hostapd'], "-v"])
if status != 1: if status != 1:
print "\t" + setup_params['hostapd'] + " not find\n" print("\t" + setup_params['hostapd'] + " not find\n")
continue continue
lines = buf.splitlines() lines = buf.splitlines()
for line in lines: for line in lines:
print "\t" + line print("\t" + line)
print "" print("")
status, buf = host.execute([setup_params['iperf'], "-v"]) status, buf = host.execute([setup_params['iperf'], "-v"])
if status != 0 and status != 1: if status != 0 and status != 1:
print "\t" + setup_params['iperf'] + " not find\n" print("\t" + setup_params['iperf'] + " not find\n")
continue continue
lines = buf.splitlines() lines = buf.splitlines()
for line in lines: for line in lines:
print "\t" + line print("\t" + line)
print "" print("")
def check_device(devices, setup_params, dev_name, monitor=False): def check_device(devices, setup_params, dev_name, monitor=False):
host = rutils.get_host(devices, dev_name) host = rutils.get_host(devices, dev_name)

View file

@ -136,7 +136,7 @@ def main():
results = res[i].get(False) results = res[i].get(False)
except: except:
results = "N/A" results = "N/A"
print "%d: %s" % (i, results) print("%d: %s" % (i, results))
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View file

@ -1,5 +1,6 @@
#!/usr/bin/python #!/usr/bin/python
from __future__ import print_function
import dbus import dbus
import sys import sys
import time import time
@ -12,21 +13,24 @@ WPAS_DBUS_OPATH = "/fi/w1/wpa_supplicant1"
WPAS_DBUS_INTERFACES_INTERFACE = "fi.w1.wpa_supplicant1.Interface" WPAS_DBUS_INTERFACES_INTERFACE = "fi.w1.wpa_supplicant1.Interface"
def usage(): def usage():
print "Usage: %s <ifname>" % sys.argv[0] print("Usage: %s <ifname>" % sys.argv[0])
print "Press Ctrl-C to stop" print("Press Ctrl-C to stop")
def ProbeRequest(args): def ProbeRequest(args):
if 'addr' in args: if 'addr' in args:
print '%.2x:%.2x:%.2x:%.2x:%.2x:%.2x' % tuple(args['addr']), print('%.2x:%.2x:%.2x:%.2x:%.2x:%.2x' % tuple(args['addr']),
end=' ')
if 'dst' in args: if 'dst' in args:
print '-> %.2x:%.2x:%.2x:%.2x:%.2x:%.2x' % tuple(args['dst']), print('-> %.2x:%.2x:%.2x:%.2x:%.2x:%.2x' % tuple(args['dst']),
end=' ')
if 'bssid' in args: if 'bssid' in args:
print '(bssid %.2x:%.2x:%.2x:%.2x:%.2x:%.2x)' % tuple(args['dst']), print('(bssid %.2x:%.2x:%.2x:%.2x:%.2x:%.2x)' % tuple(args['dst']),
end=' ')
if 'signal' in args: if 'signal' in args:
print 'signal:%d' % args['signal'], print('signal:%d' % args['signal'], end=' ')
if 'ies' in args: if 'ies' in args:
print 'have IEs (%d bytes)' % len(args['ies']), print('have IEs (%d bytes)' % len(args['ies']), end=' ')
print '' print('')
if __name__ == "__main__": if __name__ == "__main__":
global bus global bus

View file

@ -25,11 +25,11 @@ def wpas_connect():
try: try:
ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)] ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)]
except OSError as error: except OSError as error:
print "Could not find wpa_supplicant: ", error print("Could not find wpa_supplicant: ", error)
return None return None
if len(ifaces) < 1: if len(ifaces) < 1:
print "No wpa_supplicant control interface found" print("No wpa_supplicant control interface found")
return None return None
for ctrl in ifaces: for ctrl in ifaces:
@ -55,27 +55,27 @@ def dpp_logcat():
continue continue
if not uri.startswith('DPP:'): if not uri.startswith('DPP:'):
continue continue
print "Found DPP bootstrap info URI:" print("Found DPP bootstrap info URI:")
print uri print(uri)
wpas = wpas_connect() wpas = wpas_connect()
if not wpas: if not wpas:
print "Could not connect to wpa_supplicant" print("Could not connect to wpa_supplicant")
print print('')
continue continue
res = wpas.request("DPP_QR_CODE " + uri); res = wpas.request("DPP_QR_CODE " + uri);
try: try:
id = int(res) id = int(res)
except ValueError: except ValueError:
print "QR Code URI rejected" print("QR Code URI rejected")
continue continue
print "QR Code URI accepted - ID=%d" % id print("QR Code URI accepted - ID=%d" % id)
print wpas.request("DPP_BOOTSTRAP_INFO %d" % id) print(wpas.request("DPP_BOOTSTRAP_INFO %d" % id))
del wpas del wpas
def dpp_display(curve): def dpp_display(curve):
wpas = wpas_connect() wpas = wpas_connect()
if not wpas: if not wpas:
print "Could not connect to wpa_supplicant" print("Could not connect to wpa_supplicant")
return return
res = wpas.request("STATUS") res = wpas.request("STATUS")
addr = None addr = None
@ -93,18 +93,18 @@ def dpp_display(curve):
try: try:
id = int(res) id = int(res)
except ValueError: except ValueError:
print "Failed to generate bootstrap info URI" print("Failed to generate bootstrap info URI")
return return
print "Bootstrap information - ID=%d" % id print("Bootstrap information - ID=%d" % id)
print wpas.request("DPP_BOOTSTRAP_INFO %d" % id) print(wpas.request("DPP_BOOTSTRAP_INFO %d" % id))
uri = wpas.request("DPP_BOOTSTRAP_GET_URI %d" % id) uri = wpas.request("DPP_BOOTSTRAP_GET_URI %d" % id)
print uri print(uri)
print "ID=%d" % id print("ID=%d" % id)
qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_M, qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_M,
border=3) border=3)
qr.add_data(uri, optimize=5) qr.add_data(uri, optimize=5)
qr.print_ascii(tty=True) qr.print_ascii(tty=True)
print "ID=%d" % id print("ID=%d" % id)
del wpas del wpas
def main(): def main():

View file

@ -37,7 +37,7 @@ summary_file = None
success_file = None success_file = None
def summary(txt): def summary(txt):
print txt print(txt)
if summary_file: if summary_file:
with open(summary_file, 'a') as f: with open(summary_file, 'a') as f:
f.write(txt + "\n") f.write(txt + "\n")
@ -54,11 +54,11 @@ def wpas_connect():
try: try:
ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)] ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)]
except OSError as error: except OSError as error:
print "Could not find wpa_supplicant: ", error print("Could not find wpa_supplicant: ", error)
return None return None
if len(ifaces) < 1: if len(ifaces) < 1:
print "No wpa_supplicant control interface found" print("No wpa_supplicant control interface found")
return None return None
for ctrl in ifaces: for ctrl in ifaces:
@ -66,7 +66,7 @@ def wpas_connect():
if ifname not in ctrl: if ifname not in ctrl:
continue continue
try: try:
print "Trying to use control interface " + ctrl print("Trying to use control interface " + ctrl)
wpas = wpaspy.Ctrl(ctrl) wpas = wpaspy.Ctrl(ctrl)
return wpas return wpas
except Exception as e: except Exception as e:
@ -160,30 +160,30 @@ def p2p_handover_client(llc):
if (data == None): if (data == None):
summary("Could not get handover request carrier record from wpa_supplicant") summary("Could not get handover request carrier record from wpa_supplicant")
return return
print "Handover request carrier record from wpa_supplicant: " + data.encode("hex") print("Handover request carrier record from wpa_supplicant: " + data.encode("hex"))
datamsg = nfc.ndef.Message(data) datamsg = nfc.ndef.Message(data)
message.add_carrier(datamsg[0], "active", datamsg[1:]) message.add_carrier(datamsg[0], "active", datamsg[1:])
global include_wps_req global include_wps_req
if include_wps_req: if include_wps_req:
print "Handover request (pre-WPS):" print("Handover request (pre-WPS):")
try: try:
print message.pretty() print(message.pretty())
except Exception as e: except Exception as e:
print e print(e)
data = wpas_get_handover_req_wps() data = wpas_get_handover_req_wps()
if data: if data:
print "Add WPS request in addition to P2P" print("Add WPS request in addition to P2P")
datamsg = nfc.ndef.Message(data) datamsg = nfc.ndef.Message(data)
message.add_carrier(datamsg[0], "active", datamsg[1:]) message.add_carrier(datamsg[0], "active", datamsg[1:])
print "Handover request:" print("Handover request:")
try: try:
print message.pretty() print(message.pretty())
except Exception as e: except Exception as e:
print e print(e)
print str(message).encode("hex") print(str(message).encode("hex"))
client = nfc.handover.HandoverClient(llc) client = nfc.handover.HandoverClient(llc)
try: try:
@ -217,41 +217,41 @@ def p2p_handover_client(llc):
client.close() client.close()
return return
print "Received message" print("Received message")
try: try:
print message.pretty() print(message.pretty())
except Exception as e: except Exception as e:
print e print(e)
print str(message).encode("hex") print(str(message).encode("hex"))
message = nfc.ndef.HandoverSelectMessage(message) message = nfc.ndef.HandoverSelectMessage(message)
summary("Handover select received") summary("Handover select received")
try: try:
print message.pretty() print(message.pretty())
except Exception as e: except Exception as e:
print e print(e)
for carrier in message.carriers: for carrier in message.carriers:
print "Remote carrier type: " + carrier.type print("Remote carrier type: " + carrier.type)
if carrier.type == "application/vnd.wfa.p2p": if carrier.type == "application/vnd.wfa.p2p":
print "P2P carrier type match - send to wpa_supplicant" print("P2P carrier type match - send to wpa_supplicant")
if "OK" in wpas_report_handover(data, carrier.record, "INIT"): if "OK" in wpas_report_handover(data, carrier.record, "INIT"):
success_report("P2P handover reported successfully (initiator)") success_report("P2P handover reported successfully (initiator)")
else: else:
summary("P2P handover report rejected") summary("P2P handover report rejected")
break break
print "Remove peer" print("Remove peer")
client.close() client.close()
print "Done with handover" print("Done with handover")
global only_one global only_one
if only_one: if only_one:
print "only_one -> stop loop" print("only_one -> stop loop")
global continue_loop global continue_loop
continue_loop = False continue_loop = False
global no_wait global no_wait
if no_wait: if no_wait:
print "Trying to exit.." print("Trying to exit..")
global terminate_now global terminate_now
terminate_now = True terminate_now = True
@ -283,33 +283,33 @@ class HandoverServer(nfc.handover.HandoverServer):
def process_request(self, request): def process_request(self, request):
self.ho_server_processing = True self.ho_server_processing = True
clear_raw_mode() clear_raw_mode()
print "HandoverServer - request received" print("HandoverServer - request received")
try: try:
print "Parsed handover request: " + request.pretty() print("Parsed handover request: " + request.pretty())
except Exception as e: except Exception as e:
print e print(e)
sel = nfc.ndef.HandoverSelectMessage(version="1.2") sel = nfc.ndef.HandoverSelectMessage(version="1.2")
found = False found = False
for carrier in request.carriers: for carrier in request.carriers:
print "Remote carrier type: " + carrier.type print("Remote carrier type: " + carrier.type)
if carrier.type == "application/vnd.wfa.p2p": if carrier.type == "application/vnd.wfa.p2p":
print "P2P carrier type match - add P2P carrier record" print("P2P carrier type match - add P2P carrier record")
found = True found = True
self.received_carrier = carrier.record self.received_carrier = carrier.record
print "Carrier record:" print("Carrier record:")
try: try:
print carrier.record.pretty() print(carrier.record.pretty())
except Exception as e: except Exception as e:
print e print(e)
data = wpas_get_handover_sel() data = wpas_get_handover_sel()
if data is None: if data is None:
print "Could not get handover select carrier record from wpa_supplicant" print("Could not get handover select carrier record from wpa_supplicant")
continue continue
print "Handover select carrier record from wpa_supplicant:" print("Handover select carrier record from wpa_supplicant:")
print data.encode("hex") print(data.encode("hex"))
self.sent_carrier = data self.sent_carrier = data
if "OK" in wpas_report_handover(self.received_carrier, self.sent_carrier, "RESP"): if "OK" in wpas_report_handover(self.received_carrier, self.sent_carrier, "RESP"):
success_report("P2P handover reported successfully (responder)") success_report("P2P handover reported successfully (responder)")
@ -324,22 +324,22 @@ class HandoverServer(nfc.handover.HandoverServer):
for carrier in request.carriers: for carrier in request.carriers:
if found: if found:
break break
print "Remote carrier type: " + carrier.type print("Remote carrier type: " + carrier.type)
if carrier.type == "application/vnd.wfa.wsc": if carrier.type == "application/vnd.wfa.wsc":
print "WSC carrier type match - add WSC carrier record" print("WSC carrier type match - add WSC carrier record")
found = True found = True
self.received_carrier = carrier.record self.received_carrier = carrier.record
print "Carrier record:" print("Carrier record:")
try: try:
print carrier.record.pretty() print(carrier.record.pretty())
except Exception as e: except Exception as e:
print e print(e)
data = wpas_get_handover_sel_wps() data = wpas_get_handover_sel_wps()
if data is None: if data is None:
print "Could not get handover select carrier record from wpa_supplicant" print("Could not get handover select carrier record from wpa_supplicant")
continue continue
print "Handover select carrier record from wpa_supplicant:" print("Handover select carrier record from wpa_supplicant:")
print data.encode("hex") print(data.encode("hex"))
self.sent_carrier = data self.sent_carrier = data
if "OK" in wpas_report_handover_wsc(self.received_carrier, self.sent_carrier, "RESP"): if "OK" in wpas_report_handover_wsc(self.received_carrier, self.sent_carrier, "RESP"):
success_report("WSC handover reported successfully") success_report("WSC handover reported successfully")
@ -352,12 +352,12 @@ class HandoverServer(nfc.handover.HandoverServer):
found = True found = True
break break
print "Handover select:" print("Handover select:")
try: try:
print sel.pretty() print(sel.pretty())
except Exception as e: except Exception as e:
print e print(e)
print str(sel).encode("hex") print(str(sel).encode("hex"))
summary("Sending handover select") summary("Sending handover select")
self.success = True self.success = True
@ -396,7 +396,7 @@ def p2p_tag_read(tag):
success = False success = False
if len(tag.ndef.message): if len(tag.ndef.message):
for record in tag.ndef.message: for record in tag.ndef.message:
print "record type " + record.type print("record type " + record.type)
if record.type == "application/vnd.wfa.wsc": if record.type == "application/vnd.wfa.wsc":
summary("WPS tag - send to wpa_supplicant") summary("WPS tag - send to wpa_supplicant")
success = wpas_tag_read(tag.ndef.message) success = wpas_tag_read(tag.ndef.message)
@ -419,7 +419,7 @@ def rdwr_connected_p2p_write(tag):
global p2p_sel_data global p2p_sel_data
tag.ndef.message = str(p2p_sel_data) tag.ndef.message = str(p2p_sel_data)
success_report("Tag write succeeded") success_report("Tag write succeeded")
print "Done - remove tag" print("Done - remove tag")
global only_one global only_one
if only_one: if only_one:
global continue_loop global continue_loop
@ -428,7 +428,7 @@ def rdwr_connected_p2p_write(tag):
return p2p_sel_wait_remove return p2p_sel_wait_remove
def wps_write_p2p_handover_sel(clf, wait_remove=True): def wps_write_p2p_handover_sel(clf, wait_remove=True):
print "Write P2P handover select" print("Write P2P handover select")
data = wpas_get_handover_sel(tag=True) data = wpas_get_handover_sel(tag=True)
if (data == None): if (data == None):
summary("Could not get P2P handover select from wpa_supplicant") summary("Could not get P2P handover select from wpa_supplicant")
@ -440,14 +440,14 @@ def wps_write_p2p_handover_sel(clf, wait_remove=True):
p2p_sel_data = nfc.ndef.HandoverSelectMessage(version="1.2") p2p_sel_data = nfc.ndef.HandoverSelectMessage(version="1.2")
message = nfc.ndef.Message(data); message = nfc.ndef.Message(data);
p2p_sel_data.add_carrier(message[0], "active", message[1:]) p2p_sel_data.add_carrier(message[0], "active", message[1:])
print "Handover select:" print("Handover select:")
try: try:
print p2p_sel_data.pretty() print(p2p_sel_data.pretty())
except Exception as e: except Exception as e:
print e print(e)
print str(p2p_sel_data).encode("hex") print(str(p2p_sel_data).encode("hex"))
print "Touch an NFC tag" print("Touch an NFC tag")
clf.connect(rdwr={'on-connect': rdwr_connected_p2p_write}) clf.connect(rdwr={'on-connect': rdwr_connected_p2p_write})
@ -456,11 +456,11 @@ def rdwr_connected(tag):
summary("Tag connected: " + str(tag)) summary("Tag connected: " + str(tag))
if tag.ndef: if tag.ndef:
print "NDEF tag: " + tag.type print("NDEF tag: " + tag.type)
try: try:
print tag.ndef.message.pretty() print(tag.ndef.message.pretty())
except Exception as e: except Exception as e:
print e print(e)
success = p2p_tag_read(tag) success = p2p_tag_read(tag)
if only_one and success: if only_one and success:
global continue_loop global continue_loop
@ -475,15 +475,15 @@ def rdwr_connected(tag):
def llcp_worker(llc): def llcp_worker(llc):
global init_on_touch global init_on_touch
if init_on_touch: if init_on_touch:
print "Starting handover client" print("Starting handover client")
p2p_handover_client(llc) p2p_handover_client(llc)
return return
global no_input global no_input
if no_input: if no_input:
print "Wait for handover to complete" print("Wait for handover to complete")
else: else:
print "Wait for handover to complete - press 'i' to initiate ('w' for WPS only, 'p' for P2P only)" print("Wait for handover to complete - press 'i' to initiate ('w' for WPS only, 'p' for P2P only)")
global srv global srv
global wait_connection global wait_connection
while not wait_connection and srv.sent_carrier is None: while not wait_connection and srv.sent_carrier is None:
@ -506,21 +506,21 @@ def llcp_worker(llc):
else: else:
continue continue
clear_raw_mode() clear_raw_mode()
print "Starting handover client" print("Starting handover client")
p2p_handover_client(llc) p2p_handover_client(llc)
return return
clear_raw_mode() clear_raw_mode()
print "Exiting llcp_worker thread" print("Exiting llcp_worker thread")
def llcp_startup(clf, llc): def llcp_startup(clf, llc):
print "Start LLCP server" print("Start LLCP server")
global srv global srv
srv = HandoverServer(llc) srv = HandoverServer(llc)
return llc return llc
def llcp_connected(llc): def llcp_connected(llc):
print "P2P LLCP connected" print("P2P LLCP connected")
global wait_connection global wait_connection
wait_connection = False wait_connection = False
global init_on_touch global init_on_touch
@ -587,7 +587,7 @@ def main():
if args.ifname: if args.ifname:
global ifname global ifname
ifname = args.ifname ifname = args.ifname
print "Selected ifname " + ifname print("Selected ifname " + ifname)
if args.no_wps_req: if args.no_wps_req:
global include_wps_req global include_wps_req
@ -610,7 +610,7 @@ def main():
try: try:
if not clf.open("usb"): if not clf.open("usb"):
print "Could not open connection with an NFC device" print("Could not open connection with an NFC device")
raise SystemExit raise SystemExit
if args.command == "write-p2p-sel": if args.command == "write-p2p-sel":
@ -619,7 +619,7 @@ def main():
global continue_loop global continue_loop
while continue_loop: while continue_loop:
print "Waiting for a tag or peer to be touched" print("Waiting for a tag or peer to be touched")
wait_connection = True wait_connection = True
try: try:
if args.tag_read_only: if args.tag_read_only:
@ -637,7 +637,7 @@ def main():
terminate=terminate_loop): terminate=terminate_loop):
break break
except Exception as e: except Exception as e:
print "clf.connect failed" print("clf.connect failed")
global srv global srv
if only_one and srv and srv.success: if only_one and srv and srv.success:

View file

@ -13,40 +13,40 @@ from dbus.mainloop.glib import DBusGMainLoop
def usage(): def usage():
print "Usage:" print("Usage:")
print " %s -i <interface_name> -m <wps_method> \ " \ print(" %s -i <interface_name> -m <wps_method> \ " \
% sys.argv[0] % sys.argv[0])
print " -a <addr> [-p <pin>] [-g <go_intent>] \ " print(" -a <addr> [-p <pin>] [-g <go_intent>] \ ")
print " [-w <wpas_dbus_interface>]" print(" [-w <wpas_dbus_interface>]")
print "Options:" print("Options:")
print " -i = interface name" print(" -i = interface name")
print " -m = wps method" print(" -m = wps method")
print " -a = peer address" print(" -a = peer address")
print " -p = pin number (8 digits)" print(" -p = pin number (8 digits)")
print " -g = group owner intent" print(" -g = group owner intent")
print " -w = wpas dbus interface = fi.w1.wpa_supplicant1" print(" -w = wpas dbus interface = fi.w1.wpa_supplicant1")
print "Example:" print("Example:")
print " %s -i wlan0 -a 0015008352c0 -m display -p 12345670" % sys.argv[0] print(" %s -i wlan0 -a 0015008352c0 -m display -p 12345670" % sys.argv[0])
# Required Signals # Required Signals
def GONegotiationSuccess(status): def GONegotiationSuccess(status):
print "Go Negotiation Success" print("Go Negotiation Success")
def GONegotiationFailure(status): def GONegotiationFailure(status):
print 'Go Negotiation Failed. Status:' print('Go Negotiation Failed. Status:')
print format(status) print(format(status))
os._exit(0) os._exit(0)
def GroupStarted(properties): def GroupStarted(properties):
if properties.has_key("group_object"): if properties.has_key("group_object"):
print 'Group Formation Complete %s' \ print('Group Formation Complete %s' \
% properties["group_object"] % properties["group_object"])
os._exit(0) os._exit(0)
def WpsFailure(status, etc): def WpsFailure(status, etc):
print "WPS Authentication Failure".format(status) print("WPS Authentication Failure".format(status))
print etc print(etc)
os._exit(0) os._exit(0)
class P2P_Connect(): class P2P_Connect():
@ -157,12 +157,12 @@ class P2P_Connect():
if (self.pin != None): if (self.pin != None):
self.p2p_connect_arguements.update({'pin':self.pin}) self.p2p_connect_arguements.update({'pin':self.pin})
else: else:
print "Error:\n Pin required for wps_method=display" print("Error:\n Pin required for wps_method=display")
usage() usage()
quit() quit()
if (self.go_intent != None and int(self.go_intent) != 15): if (self.go_intent != None and int(self.go_intent) != 15):
print "go_intent overwritten to 15" print("go_intent overwritten to 15")
self.go_intent = '15' self.go_intent = '15'
@ -171,14 +171,14 @@ class P2P_Connect():
if (self.pin != None): if (self.pin != None):
self.p2p_connect_arguements.update({'pin':self.pin}) self.p2p_connect_arguements.update({'pin':self.pin})
else: else:
print "Error:\n Pin required for wps_method=keypad" print("Error:\n Pin required for wps_method=keypad")
usage() usage()
quit() quit()
if (self.go_intent != None and int(self.go_intent) == 15): if (self.go_intent != None and int(self.go_intent) == 15):
error = "Error :\n Group Owner intent cannot be" + \ error = "Error :\n Group Owner intent cannot be" + \
" 15 for wps_method=keypad" " 15 for wps_method=keypad"
print error print(error)
usage() usage()
quit() quit()
@ -186,15 +186,15 @@ class P2P_Connect():
# for ./wpa_cli, p2p_connect [mac] [pin#], wps_method=keypad # for ./wpa_cli, p2p_connect [mac] [pin#], wps_method=keypad
elif (self.wps_method == 'pin'): elif (self.wps_method == 'pin'):
if (self.pin != None): if (self.pin != None):
print "pin ignored" print("pin ignored")
# No pin is required for pbc so it is ignored # No pin is required for pbc so it is ignored
elif (self.wps_method == 'pbc'): elif (self.wps_method == 'pbc'):
if (self.pin != None): if (self.pin != None):
print "pin ignored" print("pin ignored")
else: else:
print "Error:\n wps_method not supported or does not exist" print("Error:\n wps_method not supported or does not exist")
usage() usage()
quit() quit()
@ -214,7 +214,7 @@ class P2P_Connect():
if (self.wps_method == 'pin' and \ if (self.wps_method == 'pin' and \
not self.p2p_connect_arguements.has_key('pin') ): not self.p2p_connect_arguements.has_key('pin') ):
print "Connect return with pin value of %d " % int(result_pin) print("Connect return with pin value of %d " % int(result_pin))
gobject.MainLoop().run() gobject.MainLoop().run()
if __name__ == "__main__": if __name__ == "__main__":
@ -268,19 +268,19 @@ if __name__ == "__main__":
# Required Arguements check # Required Arguements check
if (interface_name == None or wps_method == None or addr == None): if (interface_name == None or wps_method == None or addr == None):
print "Error:\n Required arguements not specified" print("Error:\n Required arguements not specified")
usage() usage()
quit() quit()
# Group Owner Intent Check # Group Owner Intent Check
if (go_intent != None and (int(go_intent) > 15 or int(go_intent) < 0) ): if (go_intent != None and (int(go_intent) > 15 or int(go_intent) < 0) ):
print "Error:\n Group Owner Intent must be between 0 and 15 inclusive" print("Error:\n Group Owner Intent must be between 0 and 15 inclusive")
usage() usage()
quit() quit()
# Pin Check # Pin Check
if (pin != None and len(pin) != 8): if (pin != None and len(pin) != 8):
print "Error:\n Pin is not 8 digits" print("Error:\n Pin is not 8 digits")
usage() usage()
quit() quit()
@ -289,7 +289,7 @@ if __name__ == "__main__":
addr,pin,wps_method,go_intent) addr,pin,wps_method,go_intent)
except: except:
print "Error:\n Invalid Arguements" print("Error:\n Invalid Arguements")
usage() usage()
quit() quit()

View file

@ -12,19 +12,19 @@ import getopt
from dbus.mainloop.glib import DBusGMainLoop from dbus.mainloop.glib import DBusGMainLoop
def usage(): def usage():
print "Usage:" print("Usage:")
print " %s -i <interface_name> \ " \ print(" %s -i <interface_name> \ " \
% sys.argv[0] % sys.argv[0])
print " [-w <wpas_dbus_interface>]" print(" [-w <wpas_dbus_interface>]")
print "Options:" print("Options:")
print " -i = interface name" print(" -i = interface name")
print " -w = wpas dbus interface = fi.w1.wpa_supplicant1" print(" -w = wpas dbus interface = fi.w1.wpa_supplicant1")
print "Example:" print("Example:")
print " %s -i p2p-wlan0-0" % sys.argv[0] print(" %s -i p2p-wlan0-0" % sys.argv[0])
# Required Signals # Required Signals
def GroupFinished(status, etc): def GroupFinished(status, etc):
print "Disconnected" print("Disconnected")
os._exit(0) os._exit(0)
class P2P_Disconnect (threading.Thread): class P2P_Disconnect (threading.Thread):
@ -84,7 +84,7 @@ class P2P_Disconnect (threading.Thread):
except dbus.DBusException as exc: except dbus.DBusException as exc:
error = 'Error:\n Interface ' + self.interface_name \ error = 'Error:\n Interface ' + self.interface_name \
+ ' was not found' + ' was not found'
print error print(error)
usage() usage()
os._exit(0) os._exit(0)
@ -142,7 +142,7 @@ if __name__ == "__main__":
# Interface name is required and was not given # Interface name is required and was not given
if (interface_name == None): if (interface_name == None):
print "Error:\n interface_name is required" print("Error:\n interface_name is required")
usage() usage()
quit() quit()
@ -152,7 +152,7 @@ if __name__ == "__main__":
wpas_dbus_interface,timeout) wpas_dbus_interface,timeout)
except: except:
print "Error:\n Invalid wpas_dbus_interface" print("Error:\n Invalid wpas_dbus_interface")
usage() usage()
quit() quit()
@ -165,5 +165,5 @@ if __name__ == "__main__":
except: except:
pass pass
print "Disconnect timed out" print("Disconnect timed out")
quit() quit()

View file

@ -13,23 +13,23 @@ import getopt
from dbus.mainloop.glib import DBusGMainLoop from dbus.mainloop.glib import DBusGMainLoop
def usage(): def usage():
print "Usage:" print("Usage:")
print " %s -i <interface_name> [-t <timeout>] \ " \ print(" %s -i <interface_name> [-t <timeout>] \ " \
% sys.argv[0] % sys.argv[0])
print " [-w <wpas_dbus_interface>]" print(" [-w <wpas_dbus_interface>]")
print "Options:" print("Options:")
print " -i = interface name" print(" -i = interface name")
print " -t = timeout = 0s (infinite)" print(" -t = timeout = 0s (infinite)")
print " -w = wpas dbus interface = fi.w1.wpa_supplicant1" print(" -w = wpas dbus interface = fi.w1.wpa_supplicant1")
print "Example:" print("Example:")
print " %s -i wlan0 -t 10" % sys.argv[0] print(" %s -i wlan0 -t 10" % sys.argv[0])
# Required Signals # Required Signals
def deviceFound(devicepath): def deviceFound(devicepath):
print "Device found: %s" % (devicepath) print("Device found: %s" % (devicepath))
def deviceLost(devicepath): def deviceLost(devicepath):
print "Device lost: %s" % (devicepath) print("Device lost: %s" % (devicepath))
class P2P_Find (threading.Thread): class P2P_Find (threading.Thread):
# Needed Variables # Needed Variables
@ -88,7 +88,7 @@ class P2P_Find (threading.Thread):
except dbus.DBusException as exc: except dbus.DBusException as exc:
error = 'Error:\n Interface ' + self.interface_name \ error = 'Error:\n Interface ' + self.interface_name \
+ ' was not found' + ' was not found'
print error print(error)
usage() usage()
os._exit(0) os._exit(0)
@ -150,7 +150,7 @@ if __name__ == "__main__":
if ( int(value) >= 0): if ( int(value) >= 0):
timeout = value timeout = value
else: else:
print "Error:\n Timeout cannot be negative" print("Error:\n Timeout cannot be negative")
usage() usage()
quit() quit()
# Dbus interface # Dbus interface
@ -161,7 +161,7 @@ if __name__ == "__main__":
# Interface name is required and was not given # Interface name is required and was not given
if (interface_name == None): if (interface_name == None):
print "Error:\n interface_name is required" print("Error:\n interface_name is required")
usage() usage()
quit() quit()
@ -170,7 +170,7 @@ if __name__ == "__main__":
p2p_find_test = P2P_Find(interface_name, wpas_dbus_interface, timeout) p2p_find_test = P2P_Find(interface_name, wpas_dbus_interface, timeout)
except: except:
print "Error:\n Invalid wpas_dbus_interface" print("Error:\n Invalid wpas_dbus_interface")
usage() usage()
quit() quit()

View file

@ -13,19 +13,19 @@ import getopt
from dbus.mainloop.glib import DBusGMainLoop from dbus.mainloop.glib import DBusGMainLoop
def usage(): def usage():
print "Usage:" print("Usage:")
print " %s -i <interface_name> \ " \ print(" %s -i <interface_name> \ " \
% sys.argv[0] % sys.argv[0])
print " [-w <wpas_dbus_interface>]" print(" [-w <wpas_dbus_interface>]")
print "Options:" print("Options:")
print " -i = interface name" print(" -i = interface name")
print " -w = wpas dbus interface = fi.w1.wpa_supplicant1" print(" -w = wpas dbus interface = fi.w1.wpa_supplicant1")
print "Example:" print("Example:")
print " %s -i wlan0" % sys.argv[0] print(" %s -i wlan0" % sys.argv[0])
# Required Signals\ # Required Signals\
def deviceLost(devicepath): def deviceLost(devicepath):
print "Device lost: %s" % (devicepath) print("Device lost: %s" % (devicepath))
class P2P_Flush (threading.Thread): class P2P_Flush (threading.Thread):
# Needed Variables # Needed Variables
@ -84,7 +84,7 @@ class P2P_Flush (threading.Thread):
except dbus.DBusException as exc: except dbus.DBusException as exc:
error = 'Error:\n Interface ' + self.interface_name \ error = 'Error:\n Interface ' + self.interface_name \
+ ' was not found' + ' was not found'
print error print(error)
usage() usage()
os._exit(0) os._exit(0)
@ -142,7 +142,7 @@ if __name__ == "__main__":
# Interface name is required and was not given # Interface name is required and was not given
if (interface_name == None): if (interface_name == None):
print "Error:\n interface_name is required" print("Error:\n interface_name is required")
usage() usage()
quit() quit()
@ -151,7 +151,7 @@ if __name__ == "__main__":
p2p_flush_test = P2P_Flush(interface_name, wpas_dbus_interface,timeout) p2p_flush_test = P2P_Flush(interface_name, wpas_dbus_interface,timeout)
except: except:
print "Error:\n Invalid wpas_dbus_interface" print("Error:\n Invalid wpas_dbus_interface")
usage() usage()
quit() quit()
@ -164,5 +164,5 @@ if __name__ == "__main__":
except: except:
pass pass
print "p2p_flush complete" print("p2p_flush complete")
quit() quit()

View file

@ -11,30 +11,30 @@ import threading
from dbus.mainloop.glib import DBusGMainLoop from dbus.mainloop.glib import DBusGMainLoop
def usage(): def usage():
print "Usage:" print("Usage:")
print " %s -i <interface_name> [-p <persistent>] \ " \ print(" %s -i <interface_name> [-p <persistent>] \ " \
% sys.argv[0] % sys.argv[0])
print " [-f <frequency>] [-o <group_object_path>] \ " print(" [-f <frequency>] [-o <group_object_path>] \ ")
print " [-w <wpas_dbus_interface>]" print(" [-w <wpas_dbus_interface>]")
print "Options:" print("Options:")
print " -i = interface name" print(" -i = interface name")
print " -p = persistant group = 0 (0=false, 1=true)" print(" -p = persistant group = 0 (0=false, 1=true)")
print " -f = frequency" print(" -f = frequency")
print " -o = persistent group object path" print(" -o = persistent group object path")
print " -w = wpas dbus interface = fi.w1.wpa_supplicant1" print(" -w = wpas dbus interface = fi.w1.wpa_supplicant1")
print "Example:" print("Example:")
print " %s -i wlan0" % sys.argv[0] print(" %s -i wlan0" % sys.argv[0])
# Required Signals # Required Signals
def GroupStarted(properties): def GroupStarted(properties):
if properties.has_key("group_object"): if properties.has_key("group_object"):
print 'Group Formation Complete %s' \ print('Group Formation Complete %s' \
% properties["group_object"] % properties["group_object"])
os._exit(0) os._exit(0)
def WpsFailure(status, etc): def WpsFailure(status, etc):
print "WPS Authentication Failure".format(status) print("WPS Authentication Failure".format(status))
print etc print(etc)
os._exit(0) os._exit(0)
class P2P_Group_Add (threading.Thread): class P2P_Group_Add (threading.Thread):
@ -102,7 +102,7 @@ class P2P_Group_Add (threading.Thread):
except dbus.DBusException as exc: except dbus.DBusException as exc:
error = 'Error:\n Interface ' + self.interface_name \ error = 'Error:\n Interface ' + self.interface_name \
+ ' was not found' + ' was not found'
print error print(error)
usage() usage()
os._exit(0) os._exit(0)
@ -127,7 +127,7 @@ class P2P_Group_Add (threading.Thread):
if (int(self.frequency) > 0): if (int(self.frequency) > 0):
self.P2PDictionary.update({'frequency':int(self.frequency)}) self.P2PDictionary.update({'frequency':int(self.frequency)})
else: else:
print "Error:\n Frequency must be greater than 0" print("Error:\n Frequency must be greater than 0")
usage() usage()
os._exit(0) os._exit(0)
@ -141,7 +141,7 @@ class P2P_Group_Add (threading.Thread):
self.p2p_interface.GroupAdd(self.P2PDictionary) self.p2p_interface.GroupAdd(self.P2PDictionary)
except: except:
print "Error:\n Could not preform group add" print("Error:\n Could not preform group add")
usage() usage()
os._exit(0) os._exit(0)
@ -188,7 +188,7 @@ if __name__ == "__main__":
elif (value == '1'): elif (value == '1'):
persistent = True persistent = True
else: else:
print "Error:\n Persistent can only be 1 or 0" print("Error:\n Persistent can only be 1 or 0")
usage() usage()
os._exit(0) os._exit(0)
# Frequency # Frequency
@ -205,7 +205,7 @@ if __name__ == "__main__":
# Interface name is required and was not given # Interface name is required and was not given
if (interface_name == None): if (interface_name == None):
print "Error:\n interface_name is required" print("Error:\n interface_name is required")
usage() usage()
quit() quit()
@ -213,10 +213,10 @@ if __name__ == "__main__":
p2p_group_add_test = P2P_Group_Add(interface_name,wpas_dbus_interface, p2p_group_add_test = P2P_Group_Add(interface_name,wpas_dbus_interface,
persistent,frequency,persistent_group_object) persistent,frequency,persistent_group_object)
except: except:
print "Error:\n Invalid Arguements" print("Error:\n Invalid Arguements")
p2p_group_add_test.constructArguements() p2p_group_add_test.constructArguements()
p2p_group_add_test.start() p2p_group_add_test.start()
time.sleep(5) time.sleep(5)
print "Error:\n Group formation timed out" print("Error:\n Group formation timed out")
os._exit(0) os._exit(0)

View file

@ -11,29 +11,29 @@ import threading
from dbus.mainloop.glib import DBusGMainLoop from dbus.mainloop.glib import DBusGMainLoop
def usage(): def usage():
print "Usage:" print("Usage:")
print " %s -i <interface_name> -a <addr> \ " \ print(" %s -i <interface_name> -a <addr> \ " \
% sys.argv[0] % sys.argv[0])
print " [-o <persistent_group_object>] [-w <wpas_dbus_interface>]" print(" [-o <persistent_group_object>] [-w <wpas_dbus_interface>]")
print "Options:" print("Options:")
print " -i = interface name" print(" -i = interface name")
print " -a = address of peer" print(" -a = address of peer")
print " -o = persistent group object path" print(" -o = persistent group object path")
print " -w = wpas dbus interface = fi.w1.wpa_supplicant1" print(" -w = wpas dbus interface = fi.w1.wpa_supplicant1")
print "Example:" print("Example:")
print " %s -i p2p-wlan0-0 -a 00150083523c" % sys.argv[0] print(" %s -i p2p-wlan0-0 -a 00150083523c" % sys.argv[0])
# Required Signals # Required Signals
def InvitationResult(invite_result): def InvitationResult(invite_result):
print "Inviation Result signal :" print("Inviation Result signal :")
status = invite_result['status'] status = invite_result['status']
print "status = ", status print("status = ", status)
if invite_result.has_key('BSSID'): if invite_result.has_key('BSSID'):
bssid = invite_result['BSSID'] bssid = invite_result['BSSID']
print "BSSID = ", hex(bssid[0]) , ":" , \ print("BSSID = ", hex(bssid[0]) , ":" , \
hex(bssid[1]) , ":" , hex(bssid[2]) , ":", \ hex(bssid[1]) , ":" , hex(bssid[2]) , ":", \
hex(bssid[3]) , ":" , hex(bssid[4]) , ":" , \ hex(bssid[3]) , ":" , hex(bssid[4]) , ":" , \
hex(bssid[5]) hex(bssid[5]))
os._exit(0) os._exit(0)
class P2P_Invite (threading.Thread): class P2P_Invite (threading.Thread):
@ -99,7 +99,7 @@ class P2P_Invite (threading.Thread):
except dbus.DBusException as exc: except dbus.DBusException as exc:
error = 'Error:\n Interface ' + self.interface_name \ error = 'Error:\n Interface ' + self.interface_name \
+ ' was not found' + ' was not found'
print error print(error)
usage() usage()
os._exit(0) os._exit(0)
@ -127,7 +127,7 @@ class P2P_Invite (threading.Thread):
self.p2p_interface.Invite(self.P2PDictionary) self.p2p_interface.Invite(self.P2PDictionary)
except: except:
print "Error:\n Invalid Arguements" print("Error:\n Invalid Arguements")
usage() usage()
os._exit(0) os._exit(0)
@ -176,12 +176,12 @@ if __name__ == "__main__":
# Interface name is required and was not given # Interface name is required and was not given
if (interface_name == None): if (interface_name == None):
print "Error:\n interface_name is required" print("Error:\n interface_name is required")
usage() usage()
quit() quit()
if (addr == None): if (addr == None):
print "Error:\n peer address is required" print("Error:\n peer address is required")
usage() usage()
quit() quit()
@ -190,12 +190,12 @@ if __name__ == "__main__":
P2P_Invite(interface_name,wpas_dbus_interface, P2P_Invite(interface_name,wpas_dbus_interface,
addr,persistent_group_object) addr,persistent_group_object)
except: except:
print "Error:\n Invalid Arguements" print("Error:\n Invalid Arguements")
usage() usage()
os._exit(1) os._exit(1)
p2p_invite_test.constructArguements() p2p_invite_test.constructArguements()
p2p_invite_test.start() p2p_invite_test.start()
time.sleep(10) time.sleep(10)
print "Error:\n p2p_invite timed out" print("Error:\n p2p_invite timed out")
os._exit(0) os._exit(0)

View file

@ -13,20 +13,20 @@ import getopt
from dbus.mainloop.glib import DBusGMainLoop from dbus.mainloop.glib import DBusGMainLoop
def usage(): def usage():
print "Usage:" print("Usage:")
print " %s -i <interface_name> [-t <timeout>] \ " \ print(" %s -i <interface_name> [-t <timeout>] \ " \
% sys.argv[0] % sys.argv[0])
print " [-w <wpas_dbus_interface>]" print(" [-w <wpas_dbus_interface>]")
print "Options:" print("Options:")
print " -i = interface name" print(" -i = interface name")
print " -t = timeout = 0s (infinite)" print(" -t = timeout = 0s (infinite)")
print " -w = wpas dbus interface = fi.w1.wpa_supplicant1" print(" -w = wpas dbus interface = fi.w1.wpa_supplicant1")
print "Example:" print("Example:")
print " %s -i wlan0 -t 5" % sys.argv[0] print(" %s -i wlan0 -t 5" % sys.argv[0])
# Required Signals # Required Signals
def p2pStateChange(status): def p2pStateChange(status):
print status print(status)
class P2P_Listen(threading.Thread): class P2P_Listen(threading.Thread):
# Needed Variables # Needed Variables
@ -85,7 +85,7 @@ class P2P_Listen(threading.Thread):
except dbus.DBusException as exc: except dbus.DBusException as exc:
error = 'Error:\n Interface ' + self.interface_name \ error = 'Error:\n Interface ' + self.interface_name \
+ ' was not found' + ' was not found'
print error print(error)
usage() usage()
os._exit(0) os._exit(0)
@ -140,7 +140,7 @@ if __name__ == "__main__":
if ( int(value) >= 0): if ( int(value) >= 0):
timeout = value timeout = value
else: else:
print "Error:\n Timeout cannot be negative" print("Error:\n Timeout cannot be negative")
usage() usage()
quit() quit()
# Dbus interface # Dbus interface
@ -151,7 +151,7 @@ if __name__ == "__main__":
# Interface name is required and was not given # Interface name is required and was not given
if (interface_name == None): if (interface_name == None):
print "Error:\n interface_name is required" print("Error:\n interface_name is required")
usage() usage()
quit() quit()
@ -160,7 +160,7 @@ if __name__ == "__main__":
p2p_listen_test = P2P_Listen(interface_name, wpas_dbus_interface, timeout) p2p_listen_test = P2P_Listen(interface_name, wpas_dbus_interface, timeout)
except: except:
print "Error:\n Invalid wpas_dbus_interface" print("Error:\n Invalid wpas_dbus_interface")
usage() usage()
quit() quit()

View file

@ -11,22 +11,22 @@ import getopt
from dbus.mainloop.glib import DBusGMainLoop from dbus.mainloop.glib import DBusGMainLoop
def usage(): def usage():
print "Usage:" print("Usage:")
print " %s -i <interface_name> \ " \ print(" %s -i <interface_name> \ " \
% sys.argv[0] % sys.argv[0])
print " [-w <wpas_dbus_interface>]" print(" [-w <wpas_dbus_interface>]")
print "Options:" print("Options:")
print " -i = interface name" print(" -i = interface name")
print " -w = wpas dbus interface = fi.w1.wpa_supplicant1" print(" -w = wpas dbus interface = fi.w1.wpa_supplicant1")
print "Example:" print("Example:")
print " %s -i wlan0" % sys.argv[0] print(" %s -i wlan0" % sys.argv[0])
# Required Signals # Required Signals
def deviceLost(devicepath): def deviceLost(devicepath):
print "Device lost: %s" % (devicepath) print("Device lost: %s" % (devicepath))
def p2pStateChange(status): def p2pStateChange(status):
print status print(status)
os._exit(0) os._exit(0)
class P2P_Stop_Find (threading.Thread): class P2P_Stop_Find (threading.Thread):
@ -86,7 +86,7 @@ class P2P_Stop_Find (threading.Thread):
except dbus.DBusException as exc: except dbus.DBusException as exc:
error = 'Error:\n Interface ' + self.interface_name \ error = 'Error:\n Interface ' + self.interface_name \
+ ' was not found' + ' was not found'
print error print(error)
usage() usage()
os._exit(0) os._exit(0)
@ -147,7 +147,7 @@ if __name__ == "__main__":
# Interface name is required and was not given # Interface name is required and was not given
if (interface_name == None): if (interface_name == None):
print "Error:\n interface_name is required" print("Error:\n interface_name is required")
usage() usage()
quit() quit()
@ -157,7 +157,7 @@ if __name__ == "__main__":
wpas_dbus_interface,timeout) wpas_dbus_interface,timeout)
except: except:
print "Error:\n Invalid wpas_dbus_interface" print("Error:\n Invalid wpas_dbus_interface")
usage() usage()
quit() quit()
@ -170,5 +170,5 @@ if __name__ == "__main__":
except: except:
pass pass
print "p2p find stopped" print("p2p find stopped")
quit() quit()

View file

@ -11,8 +11,8 @@ def main():
"/fi/w1/wpa_supplicant1") "/fi/w1/wpa_supplicant1")
props = wpas_obj.GetAll("fi.w1.wpa_supplicant1", props = wpas_obj.GetAll("fi.w1.wpa_supplicant1",
dbus_interface=dbus.PROPERTIES_IFACE) dbus_interface=dbus.PROPERTIES_IFACE)
print "GetAll(fi.w1.wpa_supplicant1, /fi/w1/wpa_supplicant1):" print("GetAll(fi.w1.wpa_supplicant1, /fi/w1/wpa_supplicant1):")
print props print(props)
if len(sys.argv) != 2: if len(sys.argv) != 2:
os._exit(1) os._exit(1)
@ -24,15 +24,15 @@ def main():
if_obj = bus.get_object("fi.w1.wpa_supplicant1", path) if_obj = bus.get_object("fi.w1.wpa_supplicant1", path)
props = if_obj.GetAll("fi.w1.wpa_supplicant1.Interface", props = if_obj.GetAll("fi.w1.wpa_supplicant1.Interface",
dbus_interface=dbus.PROPERTIES_IFACE) dbus_interface=dbus.PROPERTIES_IFACE)
print print('')
print "GetAll(fi.w1.wpa_supplicant1.Interface, %s):" % (path) print("GetAll(fi.w1.wpa_supplicant1.Interface, %s):" % (path))
print props print(props)
props = if_obj.GetAll("fi.w1.wpa_supplicant1.Interface.WPS", props = if_obj.GetAll("fi.w1.wpa_supplicant1.Interface.WPS",
dbus_interface=dbus.PROPERTIES_IFACE) dbus_interface=dbus.PROPERTIES_IFACE)
print print('')
print "GetAll(fi.w1.wpa_supplicant1.Interface.WPS, %s):" % (path) print("GetAll(fi.w1.wpa_supplicant1.Interface.WPS, %s):" % (path))
print props print(props)
res = if_obj.Get("fi.w1.wpa_supplicant1.Interface", 'BSSs', res = if_obj.Get("fi.w1.wpa_supplicant1.Interface", 'BSSs',
dbus_interface=dbus.PROPERTIES_IFACE) dbus_interface=dbus.PROPERTIES_IFACE)
@ -40,9 +40,9 @@ def main():
bss_obj = bus.get_object("fi.w1.wpa_supplicant1", res[0]) bss_obj = bus.get_object("fi.w1.wpa_supplicant1", res[0])
props = bss_obj.GetAll("fi.w1.wpa_supplicant1.BSS", props = bss_obj.GetAll("fi.w1.wpa_supplicant1.BSS",
dbus_interface=dbus.PROPERTIES_IFACE) dbus_interface=dbus.PROPERTIES_IFACE)
print print('')
print "GetAll(fi.w1.wpa_supplicant1.BSS, %s):" % (res[0]) print("GetAll(fi.w1.wpa_supplicant1.BSS, %s):" % (res[0]))
print props print(props)
res = if_obj.Get("fi.w1.wpa_supplicant1.Interface", 'Networks', res = if_obj.Get("fi.w1.wpa_supplicant1.Interface", 'Networks',
dbus_interface=dbus.PROPERTIES_IFACE) dbus_interface=dbus.PROPERTIES_IFACE)
@ -50,10 +50,9 @@ def main():
net_obj = bus.get_object("fi.w1.wpa_supplicant1", res[0]) net_obj = bus.get_object("fi.w1.wpa_supplicant1", res[0])
props = net_obj.GetAll("fi.w1.wpa_supplicant1.Network", props = net_obj.GetAll("fi.w1.wpa_supplicant1.Network",
dbus_interface=dbus.PROPERTIES_IFACE) dbus_interface=dbus.PROPERTIES_IFACE)
print print('')
print "GetAll(fi.w1.wpa_supplicant1.Network, %s):" % (res[0]) print("GetAll(fi.w1.wpa_supplicant1.Network, %s):" % (res[0]))
print props print(props)
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View file

@ -32,17 +32,17 @@ def list_interfaces(wpas_obj):
if_obj = bus.get_object(WPAS_DBUS_SERVICE, path) if_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
ifname = if_obj.Get(WPAS_DBUS_INTERFACES_INTERFACE, 'Ifname', ifname = if_obj.Get(WPAS_DBUS_INTERFACES_INTERFACE, 'Ifname',
dbus_interface=dbus.PROPERTIES_IFACE) dbus_interface=dbus.PROPERTIES_IFACE)
print ifname print(ifname)
def interfaceAdded(interface, properties): def interfaceAdded(interface, properties):
print "InterfaceAdded(%s): Ifname=%s" % (interface, properties['Ifname']) print("InterfaceAdded(%s): Ifname=%s" % (interface, properties['Ifname']))
def interfaceRemoved(interface): def interfaceRemoved(interface):
print "InterfaceRemoved(%s)" % (interface) print("InterfaceRemoved(%s)" % (interface))
def propertiesChanged(properties): def propertiesChanged(properties):
for i in properties: for i in properties:
print "PropertiesChanged: %s=%s" % (i, properties[i]) print("PropertiesChanged: %s=%s" % (i, properties[i]))
def showBss(bss): def showBss(bss):
net_obj = bus.get_object(WPAS_DBUS_SERVICE, bss) net_obj = bus.get_object(WPAS_DBUS_SERVICE, bss)
@ -80,48 +80,48 @@ def showBss(bss):
else: else:
maxrate = 0 maxrate = 0
print " %s :: ssid='%s' wpa=%s wpa2=%s signal=%d rate=%d freq=%d" % (bssid, ssid, wpa, wpa2, signal, maxrate, freq) print(" %s :: ssid='%s' wpa=%s wpa2=%s signal=%d rate=%d freq=%d" % (bssid, ssid, wpa, wpa2, signal, maxrate, freq))
def scanDone(success): def scanDone(success):
gobject.MainLoop().quit() gobject.MainLoop().quit()
print "Scan done: success=%s" % success print("Scan done: success=%s" % success)
def scanDone2(success, path=None): def scanDone2(success, path=None):
print "Scan done: success=%s [path=%s]" % (success, path) print("Scan done: success=%s [path=%s]" % (success, path))
def bssAdded(bss, properties): def bssAdded(bss, properties):
print "BSS added: %s" % (bss) print("BSS added: %s" % (bss))
showBss(bss) showBss(bss)
def bssRemoved(bss): def bssRemoved(bss):
print "BSS removed: %s" % (bss) print("BSS removed: %s" % (bss))
def blobAdded(blob): def blobAdded(blob):
print "BlobAdded(%s)" % (blob) print("BlobAdded(%s)" % (blob))
def blobRemoved(blob): def blobRemoved(blob):
print "BlobRemoved(%s)" % (blob) print("BlobRemoved(%s)" % (blob))
def networkAdded(network, properties): def networkAdded(network, properties):
print "NetworkAdded(%s)" % (network) print("NetworkAdded(%s)" % (network))
def networkRemoved(network): def networkRemoved(network):
print "NetworkRemoved(%s)" % (network) print("NetworkRemoved(%s)" % (network))
def networkSelected(network): def networkSelected(network):
print "NetworkSelected(%s)" % (network) print("NetworkSelected(%s)" % (network))
def propertiesChangedInterface(properties): def propertiesChangedInterface(properties):
for i in properties: for i in properties:
print "PropertiesChanged(interface): %s=%s" % (i, properties[i]) print("PropertiesChanged(interface): %s=%s" % (i, properties[i]))
def propertiesChangedBss(properties): def propertiesChangedBss(properties):
for i in properties: for i in properties:
print "PropertiesChanged(BSS): %s=%s" % (i, properties[i]) print("PropertiesChanged(BSS): %s=%s" % (i, properties[i]))
def propertiesChangedNetwork(properties): def propertiesChangedNetwork(properties):
for i in properties: for i in properties:
print "PropertiesChanged(Network): %s=%s" % (i, properties[i]) print("PropertiesChanged(Network): %s=%s" % (i, properties[i]))
def main(): def main():
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

View file

@ -15,23 +15,23 @@ WPAS_DBUS_WPS_INTERFACE = "fi.w1.wpa_supplicant1.Interface.WPS"
def propertiesChanged(properties): def propertiesChanged(properties):
if properties.has_key("State"): if properties.has_key("State"):
print "PropertiesChanged: State: %s" % (properties["State"]) print("PropertiesChanged: State: %s" % (properties["State"]))
def scanDone(success): def scanDone(success):
print "Scan done: success=%s" % success print("Scan done: success=%s" % success)
def bssAdded(bss, properties): def bssAdded(bss, properties):
print "BSS added: %s" % (bss) print("BSS added: %s" % (bss))
def bssRemoved(bss): def bssRemoved(bss):
print "BSS removed: %s" % (bss) print("BSS removed: %s" % (bss))
def wpsEvent(name, args): def wpsEvent(name, args):
print "WPS event: %s" % (name) print("WPS event: %s" % (name))
print args print(args)
def credentials(cred): def credentials(cred):
print "WPS credentials: %s" % (cred) print("WPS credentials: %s" % (cred))
def main(): def main():
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
@ -40,7 +40,7 @@ def main():
wpas_obj = bus.get_object(WPAS_DBUS_SERVICE, WPAS_DBUS_OPATH) wpas_obj = bus.get_object(WPAS_DBUS_SERVICE, WPAS_DBUS_OPATH)
if len(sys.argv) != 2: if len(sys.argv) != 2:
print "Missing ifname argument" print("Missing ifname argument")
os._exit(1) os._exit(1)
wpas = dbus.Interface(wpas_obj, WPAS_DBUS_INTERFACE) wpas = dbus.Interface(wpas_obj, WPAS_DBUS_INTERFACE)

View file

@ -31,11 +31,11 @@ def list_interfaces(wpas_obj):
if_obj = bus.get_object(WPAS_DBUS_SERVICE, path) if_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
ifname = if_obj.Get(WPAS_DBUS_INTERFACES_INTERFACE, 'Ifname', ifname = if_obj.Get(WPAS_DBUS_INTERFACES_INTERFACE, 'Ifname',
dbus_interface=dbus.PROPERTIES_IFACE) dbus_interface=dbus.PROPERTIES_IFACE)
print ifname print(ifname)
def propertiesChanged(properties): def propertiesChanged(properties):
if properties.has_key("State"): if properties.has_key("State"):
print "PropertiesChanged: State: %s" % (properties["State"]) print("PropertiesChanged: State: %s" % (properties["State"]))
def showBss(bss): def showBss(bss):
net_obj = bus.get_object(WPAS_DBUS_SERVICE, bss) net_obj = bus.get_object(WPAS_DBUS_SERVICE, bss)
@ -73,25 +73,25 @@ def showBss(bss):
else: else:
maxrate = 0 maxrate = 0
print " %s :: ssid='%s' wpa=%s wpa2=%s signal=%d rate=%d freq=%d" % (bssid, ssid, wpa, wpa2, signal, maxrate, freq) print(" %s :: ssid='%s' wpa=%s wpa2=%s signal=%d rate=%d freq=%d" % (bssid, ssid, wpa, wpa2, signal, maxrate, freq))
def scanDone(success): def scanDone(success):
print "Scan done: success=%s" % success print("Scan done: success=%s" % success)
res = if_obj.Get(WPAS_DBUS_INTERFACES_INTERFACE, 'BSSs', res = if_obj.Get(WPAS_DBUS_INTERFACES_INTERFACE, 'BSSs',
dbus_interface=dbus.PROPERTIES_IFACE) dbus_interface=dbus.PROPERTIES_IFACE)
print "Scanned wireless networks:" print("Scanned wireless networks:")
for opath in res: for opath in res:
print opath print(opath)
showBss(opath) showBss(opath)
def bssAdded(bss, properties): def bssAdded(bss, properties):
print "BSS added: %s" % (bss) print("BSS added: %s" % (bss))
showBss(bss) showBss(bss)
def bssRemoved(bss): def bssRemoved(bss):
print "BSS removed: %s" % (bss) print("BSS removed: %s" % (bss))
def main(): def main():
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

View file

@ -24,7 +24,7 @@ def byte_array_to_string(s):
def main(): def main():
if len(sys.argv) != 2: if len(sys.argv) != 2:
print "Usage: wpas-test.py <interface>" print("Usage: wpas-test.py <interface>")
os._exit(1) os._exit(1)
ifname = sys.argv[1] ifname = sys.argv[1]
@ -53,7 +53,7 @@ def main():
time.sleep(5) time.sleep(5)
res = iface.scanResults() res = iface.scanResults()
print "Scanned wireless networks:" print("Scanned wireless networks:")
for opath in res: for opath in res:
net_obj = bus.get_object(WPAS_DBUS_SERVICE, opath) net_obj = bus.get_object(WPAS_DBUS_SERVICE, opath)
net = dbus.Interface(net_obj, WPAS_DBUS_BSSID_INTERFACE) net = dbus.Interface(net_obj, WPAS_DBUS_BSSID_INTERFACE)
@ -80,7 +80,7 @@ def main():
noise = props["noise"] noise = props["noise"]
maxrate = props["maxrate"] / 1000000 maxrate = props["maxrate"] / 1000000
print " %s :: ssid='%s' wpa=%s wpa2=%s quality=%d%% rate=%d freq=%d" % (bssid, ssid, wpa, wpa2, qual, maxrate, freq) print(" %s :: ssid='%s' wpa=%s wpa2=%s quality=%d%% rate=%d freq=%d" % (bssid, ssid, wpa, wpa2, qual, maxrate, freq))
wpas.removeInterface(dbus.ObjectPath(path)) wpas.removeInterface(dbus.ObjectPath(path))
# Should fail here with unknown interface error # Should fail here with unknown interface error

View file

@ -30,7 +30,7 @@ summary_file = None
success_file = None success_file = None
def summary(txt): def summary(txt):
print txt print(txt)
if summary_file: if summary_file:
with open(summary_file, 'a') as f: with open(summary_file, 'a') as f:
f.write(txt + "\n") f.write(txt + "\n")
@ -47,11 +47,11 @@ def wpas_connect():
try: try:
ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)] ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)]
except OSError as error: except OSError as error:
print "Could not find wpa_supplicant: ", error print("Could not find wpa_supplicant: ", error)
return None return None
if len(ifaces) < 1: if len(ifaces) < 1:
print "No wpa_supplicant control interface found" print("No wpa_supplicant control interface found")
return None return None
for ctrl in ifaces: for ctrl in ifaces:
@ -163,22 +163,22 @@ class HandoverServer(nfc.handover.HandoverServer):
self.ho_server_processing = True self.ho_server_processing = True
summary("HandoverServer - request received") summary("HandoverServer - request received")
try: try:
print "Parsed handover request: " + request.pretty() print("Parsed handover request: " + request.pretty())
except Exception as e: except Exception as e:
print e print(e)
sel = nfc.ndef.HandoverSelectMessage(version="1.2") sel = nfc.ndef.HandoverSelectMessage(version="1.2")
for carrier in request.carriers: for carrier in request.carriers:
print "Remote carrier type: " + carrier.type print("Remote carrier type: " + carrier.type)
if carrier.type == "application/vnd.wfa.wsc": if carrier.type == "application/vnd.wfa.wsc":
summary("WPS carrier type match - add WPS carrier record") summary("WPS carrier type match - add WPS carrier record")
data = wpas_get_handover_sel(self.uuid) data = wpas_get_handover_sel(self.uuid)
if data is None: if data is None:
summary("Could not get handover select carrier record from wpa_supplicant") summary("Could not get handover select carrier record from wpa_supplicant")
continue continue
print "Handover select carrier record from wpa_supplicant:" print("Handover select carrier record from wpa_supplicant:")
print data.encode("hex") print(data.encode("hex"))
self.sent_carrier = data self.sent_carrier = data
if "OK" in wpas_report_handover(carrier.record, self.sent_carrier, "RESP"): if "OK" in wpas_report_handover(carrier.record, self.sent_carrier, "RESP"):
success_report("Handover reported successfully (responder)") success_report("Handover reported successfully (responder)")
@ -188,12 +188,12 @@ class HandoverServer(nfc.handover.HandoverServer):
message = nfc.ndef.Message(data); message = nfc.ndef.Message(data);
sel.add_carrier(message[0], "active", message[1:]) sel.add_carrier(message[0], "active", message[1:])
print "Handover select:" print("Handover select:")
try: try:
print sel.pretty() print(sel.pretty())
except Exception as e: except Exception as e:
print e print(e)
print str(sel).encode("hex") print(str(sel).encode("hex"))
summary("Sending handover select") summary("Sending handover select")
self.success = True self.success = True
@ -207,19 +207,19 @@ def wps_handover_init(llc):
if (data == None): if (data == None):
summary("Could not get handover request carrier record from wpa_supplicant") summary("Could not get handover request carrier record from wpa_supplicant")
return return
print "Handover request carrier record from wpa_supplicant: " + data.encode("hex") print("Handover request carrier record from wpa_supplicant: " + data.encode("hex"))
message = nfc.ndef.HandoverRequestMessage(version="1.2") message = nfc.ndef.HandoverRequestMessage(version="1.2")
message.nonce = random.randint(0, 0xffff) message.nonce = random.randint(0, 0xffff)
datamsg = nfc.ndef.Message(data) datamsg = nfc.ndef.Message(data)
message.add_carrier(datamsg[0], "active", datamsg[1:]) message.add_carrier(datamsg[0], "active", datamsg[1:])
print "Handover request:" print("Handover request:")
try: try:
print message.pretty() print(message.pretty())
except Exception as e: except Exception as e:
print e print(e)
print str(message).encode("hex") print(str(message).encode("hex"))
client = nfc.handover.HandoverClient(llc) client = nfc.handover.HandoverClient(llc)
try: try:
@ -253,23 +253,23 @@ def wps_handover_init(llc):
client.close() client.close()
return return
print "Received message" print("Received message")
try: try:
print message.pretty() print(message.pretty())
except Exception as e: except Exception as e:
print e print(e)
print str(message).encode("hex") print(str(message).encode("hex"))
message = nfc.ndef.HandoverSelectMessage(message) message = nfc.ndef.HandoverSelectMessage(message)
summary("Handover select received") summary("Handover select received")
try: try:
print message.pretty() print(message.pretty())
except Exception as e: except Exception as e:
print e print(e)
for carrier in message.carriers: for carrier in message.carriers:
print "Remote carrier type: " + carrier.type print("Remote carrier type: " + carrier.type)
if carrier.type == "application/vnd.wfa.wsc": if carrier.type == "application/vnd.wfa.wsc":
print "WPS carrier type match - send to wpa_supplicant" print("WPS carrier type match - send to wpa_supplicant")
if "OK" in wpas_report_handover(data, carrier.record, "INIT"): if "OK" in wpas_report_handover(data, carrier.record, "INIT"):
success_report("Handover reported successfully (initiator)") success_report("Handover reported successfully (initiator)")
else: else:
@ -278,9 +278,9 @@ def wps_handover_init(llc):
#wifi = nfc.ndef.WifiConfigRecord(carrier.record) #wifi = nfc.ndef.WifiConfigRecord(carrier.record)
#print wifi.pretty() #print wifi.pretty()
print "Remove peer" print("Remove peer")
client.close() client.close()
print "Done with handover" print("Done with handover")
global only_one global only_one
if only_one: if only_one:
global continue_loop global continue_loop
@ -288,7 +288,7 @@ def wps_handover_init(llc):
global no_wait global no_wait
if no_wait: if no_wait:
print "Trying to exit.." print("Trying to exit..")
global terminate_now global terminate_now
terminate_now = True terminate_now = True
@ -296,7 +296,7 @@ def wps_tag_read(tag, wait_remove=True):
success = False success = False
if len(tag.ndef.message): if len(tag.ndef.message):
for record in tag.ndef.message: for record in tag.ndef.message:
print "record type " + record.type print("record type " + record.type)
if record.type == "application/vnd.wfa.wsc": if record.type == "application/vnd.wfa.wsc":
summary("WPS tag - send to wpa_supplicant") summary("WPS tag - send to wpa_supplicant")
success = wpas_tag_read(tag.ndef.message) success = wpas_tag_read(tag.ndef.message)
@ -308,7 +308,7 @@ def wps_tag_read(tag, wait_remove=True):
success_report("Tag read succeeded") success_report("Tag read succeeded")
if wait_remove: if wait_remove:
print "Remove tag" print("Remove tag")
while tag.is_present: while tag.is_present:
time.sleep(0.1) time.sleep(0.1)
@ -320,7 +320,7 @@ def rdwr_connected_write(tag):
global write_data global write_data
tag.ndef.message = str(write_data) tag.ndef.message = str(write_data)
success_report("Tag write succeeded") success_report("Tag write succeeded")
print "Done - remove tag" print("Done - remove tag")
global only_one global only_one
if only_one: if only_one:
global continue_loop global continue_loop
@ -330,41 +330,41 @@ def rdwr_connected_write(tag):
time.sleep(0.1) time.sleep(0.1)
def wps_write_config_tag(clf, id=None, wait_remove=True): def wps_write_config_tag(clf, id=None, wait_remove=True):
print "Write WPS config token" print("Write WPS config token")
global write_data, write_wait_remove global write_data, write_wait_remove
write_wait_remove = wait_remove write_wait_remove = wait_remove
write_data = wpas_get_config_token(id) write_data = wpas_get_config_token(id)
if write_data == None: if write_data == None:
print "Could not get WPS config token from wpa_supplicant" print("Could not get WPS config token from wpa_supplicant")
sys.exit(1) sys.exit(1)
return return
print "Touch an NFC tag" print("Touch an NFC tag")
clf.connect(rdwr={'on-connect': rdwr_connected_write}) clf.connect(rdwr={'on-connect': rdwr_connected_write})
def wps_write_er_config_tag(clf, uuid, wait_remove=True): def wps_write_er_config_tag(clf, uuid, wait_remove=True):
print "Write WPS ER config token" print("Write WPS ER config token")
global write_data, write_wait_remove global write_data, write_wait_remove
write_wait_remove = wait_remove write_wait_remove = wait_remove
write_data = wpas_get_er_config_token(uuid) write_data = wpas_get_er_config_token(uuid)
if write_data == None: if write_data == None:
print "Could not get WPS config token from wpa_supplicant" print("Could not get WPS config token from wpa_supplicant")
return return
print "Touch an NFC tag" print("Touch an NFC tag")
clf.connect(rdwr={'on-connect': rdwr_connected_write}) clf.connect(rdwr={'on-connect': rdwr_connected_write})
def wps_write_password_tag(clf, wait_remove=True): def wps_write_password_tag(clf, wait_remove=True):
print "Write WPS password token" print("Write WPS password token")
global write_data, write_wait_remove global write_data, write_wait_remove
write_wait_remove = wait_remove write_wait_remove = wait_remove
write_data = wpas_get_password_token() write_data = wpas_get_password_token()
if write_data == None: if write_data == None:
print "Could not get WPS password token from wpa_supplicant" print("Could not get WPS password token from wpa_supplicant")
return return
print "Touch an NFC tag" print("Touch an NFC tag")
clf.connect(rdwr={'on-connect': rdwr_connected_write}) clf.connect(rdwr={'on-connect': rdwr_connected_write})
@ -373,11 +373,11 @@ def rdwr_connected(tag):
summary("Tag connected: " + str(tag)) summary("Tag connected: " + str(tag))
if tag.ndef: if tag.ndef:
print "NDEF tag: " + tag.type print("NDEF tag: " + tag.type)
try: try:
print tag.ndef.message.pretty() print(tag.ndef.message.pretty())
except Exception as e: except Exception as e:
print e print(e)
success = wps_tag_read(tag, not only_one) success = wps_tag_read(tag, not only_one)
if only_one and success: if only_one and success:
global continue_loop global continue_loop
@ -393,7 +393,7 @@ def llcp_worker(llc):
global arg_uuid global arg_uuid
if arg_uuid is None: if arg_uuid is None:
wps_handover_init(llc) wps_handover_init(llc)
print "Exiting llcp_worker thread" print("Exiting llcp_worker thread")
return return
global srv global srv
@ -405,19 +405,19 @@ def llcp_worker(llc):
def llcp_startup(clf, llc): def llcp_startup(clf, llc):
global arg_uuid global arg_uuid
if arg_uuid: if arg_uuid:
print "Start LLCP server" print("Start LLCP server")
global srv global srv
srv = HandoverServer(llc) srv = HandoverServer(llc)
if arg_uuid is "ap": if arg_uuid is "ap":
print "Trying to handle WPS handover" print("Trying to handle WPS handover")
srv.uuid = None srv.uuid = None
else: else:
print "Trying to handle WPS handover with AP " + arg_uuid print("Trying to handle WPS handover with AP " + arg_uuid)
srv.uuid = arg_uuid srv.uuid = arg_uuid
return llc return llc
def llcp_connected(llc): def llcp_connected(llc):
print "P2P LLCP connected" print("P2P LLCP connected")
global wait_connection global wait_connection
wait_connection = False wait_connection = False
global arg_uuid global arg_uuid
@ -426,7 +426,7 @@ def llcp_connected(llc):
srv.start() srv.start()
else: else:
threading.Thread(target=llcp_worker, args=(llc,)).start() threading.Thread(target=llcp_worker, args=(llc,)).start()
print "llcp_connected returning" print("llcp_connected returning")
return True return True
@ -482,7 +482,7 @@ def main():
try: try:
if not clf.open("usb"): if not clf.open("usb"):
print "Could not open connection with an NFC device" print("Could not open connection with an NFC device")
raise SystemExit raise SystemExit
if args.command == "write-config": if args.command == "write-config":
@ -499,7 +499,7 @@ def main():
global continue_loop global continue_loop
while continue_loop: while continue_loop:
print "Waiting for a tag or peer to be touched" print("Waiting for a tag or peer to be touched")
wait_connection = True wait_connection = True
try: try:
if not clf.connect(rdwr={'on-connect': rdwr_connected}, if not clf.connect(rdwr={'on-connect': rdwr_connected},
@ -508,7 +508,7 @@ def main():
terminate=terminate_loop): terminate=terminate_loop):
break break
except Exception as e: except Exception as e:
print "clf.connect failed" print("clf.connect failed")
global srv global srv
if only_one and srv and srv.success: if only_one and srv and srv.success:

View file

@ -28,7 +28,7 @@ if __name__ == "__main__":
input = sys.argv[1] input = sys.argv[1]
pcap = sys.argv[2] pcap = sys.argv[2]
except IndexError: except IndexError:
print "Usage: %s <log file> <pcap file>" % sys.argv[0] print("Usage: %s <log file> <pcap file>" % sys.argv[0])
sys.exit(2) sys.exit(2)
input_file = open(input, 'r') input_file = open(input, 'r')

View file

@ -21,18 +21,18 @@ def wpas_connect(host=None, port=9877):
wpas = wpaspy.Ctrl(host, port) wpas = wpaspy.Ctrl(host, port)
return wpas return wpas
except: except:
print "Could not connect to host: ", host print("Could not connect to host: ", host)
return None return None
if os.path.isdir(wpas_ctrl): if os.path.isdir(wpas_ctrl):
try: try:
ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)] ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)]
except OSError as error: except OSError as error:
print "Could not find wpa_supplicant: ", error print("Could not find wpa_supplicant: ", error)
return None return None
if len(ifaces) < 1: if len(ifaces) < 1:
print "No wpa_supplicant control interface found" print("No wpa_supplicant control interface found")
return None return None
for ctrl in ifaces: for ctrl in ifaces:
@ -45,21 +45,21 @@ def wpas_connect(host=None, port=9877):
def main(host=None, port=9877): def main(host=None, port=9877):
print "Testing wpa_supplicant control interface connection" print("Testing wpa_supplicant control interface connection")
wpas = wpas_connect(host, port) wpas = wpas_connect(host, port)
if wpas is None: if wpas is None:
return return
print "Connected to wpa_supplicant" print("Connected to wpa_supplicant")
print wpas.request('PING') print(wpas.request('PING'))
mon = wpas_connect(host, port) mon = wpas_connect(host, port)
if mon is None: if mon is None:
print "Could not open event monitor connection" print("Could not open event monitor connection")
return return
mon.attach() mon.attach()
print "Scan" print("Scan")
print wpas.request('SCAN') print(wpas.request('SCAN'))
count = 0 count = 0
while count < 10: while count < 10:
@ -67,10 +67,10 @@ def main(host=None, port=9877):
time.sleep(1) time.sleep(1)
while mon.pending(): while mon.pending():
ev = mon.recv() ev = mon.recv()
print ev print(ev)
if 'CTRL-EVENT-SCAN-RESULTS' in ev: if 'CTRL-EVENT-SCAN-RESULTS' in ev:
print 'Scan completed' print('Scan completed')
print wpas.request('SCAN_RESULTS') print(wpas.request('SCAN_RESULTS'))
count = 10 count = 10
pass pass