Merge pull request #47 from deix/Python-PEP8-Part-1

Some code changes from Python PEP8.....
This commit is contained in:
derv
2018-02-25 23:18:27 -08:00
committed by GitHub
16 changed files with 75 additions and 93 deletions

View File

@@ -45,11 +45,10 @@ class Wifite(object):
if not os.path.exists(name): if not os.path.exists(name):
Color.pl('{!} {O}file {C}%s{O} not found{W}' % name) Color.pl('{!} {O}file {C}%s{O} not found{W}' % name)
return return
f = open(name, 'r') with open(name, 'r') as fid:
json = loads(f.read()) json = loads(fid.read())
f.close() for idx, item in enumerate(json, start=1):
for (index, item) in enumerate(json): Color.pl('\n{+} Cracked target #%d:' % (idx))
Color.pl('\n{+} Cracked target #%d:' % (index + 1))
cr = CrackResult.load(item) cr = CrackResult.load(item)
cr.dump() cr.dump()
@@ -89,11 +88,11 @@ class Wifite(object):
attacked_targets = 0 attacked_targets = 0
targets_remaining = len(targets) targets_remaining = len(targets)
for index, t in enumerate(targets): for idx, t in enumerate(targets, start=1):
attacked_targets += 1 attacked_targets += 1
targets_remaining -= 1 targets_remaining -= 1
Color.pl('\n{+} ({G}%d{W}/{G}%d{W})' % (index + 1, len(targets)) + Color.pl('\n{+} ({G}%d{W}/{G}%d{W})' % (idx, len(targets)) +
' starting attacks against {C}%s{W} ({C}%s{W})' ' starting attacks against {C}%s{W} ({C}%s{W})'
% (t.bssid, t.essid if t.essid_known else "{O}ESSID unknown")) % (t.bssid, t.essid if t.essid_known else "{O}ESSID unknown"))
if 'WEP' in t.encryption: if 'WEP' in t.encryption:

View File

@@ -26,23 +26,21 @@ class Aircrack(object):
def is_running(self): def is_running(self):
return self.pid.poll() == None return self.pid.poll() is None
def is_cracked(self): def is_cracked(self):
return os.path.exists(self.cracked_file) return os.path.exists(self.cracked_file)
def stop(self): def stop(self):
''' Stops aircrack process ''' ''' Stops aircrack process '''
if self.pid.poll() == None: if self.pid.poll() is None:
self.pid.interrupt() self.pid.interrupt()
def get_key_hex_ascii(self): def get_key_hex_ascii(self):
if not self.is_cracked(): if not self.is_cracked():
raise Exception('Cracked file not found') raise Exception('Cracked file not found')
f = open(self.cracked_file, 'r') with open(self.cracked_file, 'r') as fid:
hex_raw = f.read() hex_raw = fid.read()
f.close()
hex_key = '' hex_key = ''
ascii_key = '' ascii_key = ''
while len(hex_raw) > 0: while len(hex_raw) > 0:
@@ -58,7 +56,7 @@ class Aircrack(object):
# Hex key is non-printable in ascii # Hex key is non-printable in ascii
ascii_key = None ascii_key = None
continue continue
elif ascii_key == None: elif ascii_key is None:
# We can't generate an Ascii key # We can't generate an Ascii key
continue continue
# Convert decimal to char # Convert decimal to char

View File

@@ -28,17 +28,17 @@ class WEPAttackType(object):
''' '''
self.value = None self.value = None
self.name = None self.name = None
if type(var) == int: if type(var) is int:
for (name,value) in WEPAttackType.__dict__.iteritems(): for (name,value) in WEPAttackType.__dict__.iteritems():
if type(value) == int: if type(value) is int:
if value == var: if value == var:
self.name = name self.name = name
self.value = value self.value = value
return return
raise Exception("Attack number %d not found" % var) raise Exception("Attack number %d not found" % var)
elif type(var) == str: elif type(var) is str:
for (name,value) in WEPAttackType.__dict__.iteritems(): for (name,value) in WEPAttackType.__dict__.iteritems():
if type(value) == int: if type(value) is int:
if name == var: if name == var:
self.name = name self.name = name
self.value = value self.value = value
@@ -81,11 +81,11 @@ class Aireplay(Thread):
self.start() self.start()
def is_running(self): def is_running(self):
return self.pid.poll() == None return self.pid.poll() is None
def stop(self): def stop(self):
''' Stops aireplay process ''' ''' Stops aireplay process '''
if hasattr(self, "pid") and self.pid and self.pid.poll() == None: if hasattr(self, "pid") and self.pid and self.pid.poll() is None:
self.pid.interrupt() self.pid.interrupt()
def get_output(self): def get_output(self):
@@ -96,14 +96,11 @@ class Aireplay(Thread):
while self.pid.poll() is None: while self.pid.poll() is None:
time.sleep(0.1) time.sleep(0.1)
if not os.path.exists(self.output_file): continue if not os.path.exists(self.output_file): continue
# Read output file # Read output file & clear output file
f = open(self.output_file, "r") with open(self.output_file, "r+") as fid:
lines = f.read() lines = fid.read()
f.close() fid.seek(0)
# Clear output file fid.truncate()
f = open(self.output_file, "w")
f.write("")
f.close()
for line in lines.split("\n"): for line in lines.split("\n"):
line = line.replace("\r", "").strip() line = line.replace("\r", "").strip()
if line == "": continue if line == "": continue
@@ -185,7 +182,7 @@ class Aireplay(Thread):
# Interface is required at this point # Interface is required at this point
Configuration.initialize() Configuration.initialize()
if Configuration.interface == None: if Configuration.interface is None:
raise Exception("Wireless interface must be defined (-i)") raise Exception("Wireless interface must be defined (-i)")
cmd = ["aireplay-ng"] cmd = ["aireplay-ng"]
@@ -262,7 +259,7 @@ class Aireplay(Thread):
cmd.extend(["-h", client_mac]) cmd.extend(["-h", client_mac])
elif attack_type == WEPAttackType.hirte: elif attack_type == WEPAttackType.hirte:
if client_mac == None: if client_mac is None:
# Unable to carry out hirte attack # Unable to carry out hirte attack
raise Exception("Client is required for hirte attack") raise Exception("Client is required for hirte attack")
cmd.extend([ cmd.extend([
@@ -270,7 +267,7 @@ class Aireplay(Thread):
"-h", client_mac "-h", client_mac
]) ])
elif attack_type == WEPAttackType.forgedreplay: elif attack_type == WEPAttackType.forgedreplay:
if client_mac == None or replay_file == None: if client_mac is None or replay_file is None:
raise Exception("Client_mac and Replay_File are required for arp replay") raise Exception("Client_mac and Replay_File are required for arp replay")
cmd.extend([ cmd.extend([
"--arpreplay", "--arpreplay",

View File

@@ -24,12 +24,12 @@ class Airmon(object):
def print_menu(self): def print_menu(self):
''' Prints menu ''' ''' Prints menu '''
print Interface.menu_header() print Interface.menu_header()
for (index, iface) in enumerate(self.interfaces): for idx, iface in enumerate(self.interfaces, start=1):
Color.pl(" {G}%d{W}. %s" % (index + 1, iface)) Color.pl(" {G}%d{W}. %s" % (idx, iface))
def get(self, index): def get(self, index):
''' Gets interface at index (starts at 1) ''' ''' Gets interface at index (starts at 1) '''
if type(index) == str: if type(index) is str:
index = int(index) index = int(index)
return self.interfaces[index - 1] return self.interfaces[index - 1]
@@ -44,9 +44,8 @@ class Airmon(object):
p = Process('airmon-ng') p = Process('airmon-ng')
for line in p.stdout().split('\n'): for line in p.stdout().split('\n'):
# Ignore blank/header lines # Ignore blank/header lines
if len(line) == 0: continue if len(line) == 0 or line.startswith('Interface') or line.startswith('PHY'):
if line.startswith('Interface'): continue continue
if line.startswith('PHY'): continue
# Strip out interface information # Strip out interface information
fields = line.split("\t") fields = line.split("\t")
@@ -89,7 +88,7 @@ class Airmon(object):
mon_iface = mon_iface.split(')')[0] mon_iface = mon_iface.split(')')[0]
break break
if mon_iface == None: if mon_iface is None:
# Airmon did not enable monitor mode on an interface # Airmon did not enable monitor mode on an interface
Color.pl("{R}failed{W}") Color.pl("{R}failed{W}")
@@ -242,8 +241,8 @@ class Airmon(object):
if re.search('^ *PID', line): if re.search('^ *PID', line):
hit_pids = True hit_pids = True
continue continue
if not hit_pids: continue if not hit_pids or line.strip() == '':
if line.strip() == '': continue continue
match = re.search('^[ \t]*(\d+)[ \t]*([a-zA-Z0-9_\-]+)[ \t]*$', line) match = re.search('^[ \t]*(\d+)[ \t]*([a-zA-Z0-9_\-]+)[ \t]*$', line)
if match: if match:
# Found process to kill # Found process to kill

View File

@@ -21,15 +21,15 @@ class Airodump(object):
Configuration.initialize() Configuration.initialize()
if interface == None: if interface is None:
interface = Configuration.interface interface = Configuration.interface
if interface == None: if interface is None:
raise Exception("Wireless interface must be defined (-i)") raise Exception("Wireless interface must be defined (-i)")
self.interface = interface self.interface = interface
self.targets = [] self.targets = []
if channel == None: if channel is None:
channel = Configuration.target_channel channel = Configuration.target_channel
self.channel = channel self.channel = channel
self.five_ghz = Configuration.five_ghz self.five_ghz = Configuration.five_ghz
@@ -120,9 +120,7 @@ class Airodump(object):
# Remove .cap and .xor files from pwd # Remove .cap and .xor files from pwd
for fil in os.listdir('.'): for fil in os.listdir('.'):
if fil.startswith('replay_') and fil.endswith('.cap'): if fil.startswith('replay_') and fil.endswith('.cap') or fil.endswith('.xor'):
os.remove(fil)
if fil.endswith('.xor'):
os.remove(fil) os.remove(fil)
def get_targets(self, apply_filter=True): def get_targets(self, apply_filter=True):
@@ -133,7 +131,7 @@ class Airodump(object):
# Found the file # Found the file
csv_filename = fil csv_filename = fil
break break
if csv_filename == None or not os.path.exists(csv_filename): if csv_filename is None or not os.path.exists(csv_filename):
# No file found # No file found
return self.targets return self.targets
@@ -298,9 +296,8 @@ if __name__ == '__main__':
targets = airodump.get_targets() targets = airodump.get_targets()
Target.print_header() Target.print_header()
for (index, target) in enumerate(targets): for idx, target in enumerate(targets, start=1):
index += 1 Color.pl(' {G}%s %s' % (str(idx).rjust(3), target))
Color.pl(' {G}%s %s' % (str(index).rjust(3), target))
Configuration.delete_temp() Configuration.delete_temp()

View File

@@ -39,7 +39,7 @@ class Attack(object):
airodump_target = t airodump_target = t
break break
if airodump_target == None: if airodump_target is None:
raise Exception( raise Exception(
'Could not find target (%s) in airodump' % self.target.bssid) 'Could not find target (%s) in airodump' % self.target.bssid)

View File

@@ -189,9 +189,8 @@ class AttackWPA(Attack):
Color.pl("") Color.pl("")
# Check crack result # Check crack result
if os.path.exists(key_file): if os.path.exists(key_file):
f = open(key_file, "r") with open(key_file, "r") as fid:
key = f.read().strip() key = fid.read().strip()
f.close()
os.remove(key_file) os.remove(key_file)
Color.pl("{+} {G}Cracked WPA Handshake{W} PSK: {G}%s{W}\n" % key) Color.pl("{+} {G}Cracked WPA Handshake{W} PSK: {G}%s{W}\n" % key)

View File

@@ -206,7 +206,7 @@ class Bully(Attack):
return False return False
def stop(self): def stop(self):
if hasattr(self, "pid") and self.pid and self.pid.poll() == None: if hasattr(self, "pid") and self.pid and self.pid.poll() is None:
self.pid.interrupt() self.pid.interrupt()
def __del__(self): def __del__(self):

View File

@@ -100,7 +100,7 @@ class Configuration(object):
@staticmethod @staticmethod
def get_interface(): def get_interface():
if Configuration.interface == None: if Configuration.interface is None:
# Interface wasn't defined, select it! # Interface wasn't defined, select it!
from Airmon import Airmon from Airmon import Airmon
Configuration.interface = Airmon.ask() Configuration.interface = Airmon.ask()
@@ -273,7 +273,7 @@ class Configuration(object):
@staticmethod @staticmethod
def temp(subfile=''): def temp(subfile=''):
''' Creates and/or returns the temporary directory ''' ''' Creates and/or returns the temporary directory '''
if Configuration.temp_dir == None: if Configuration.temp_dir is None:
Configuration.temp_dir = Configuration.create_temp() Configuration.temp_dir = Configuration.create_temp()
return Configuration.temp_dir + subfile return Configuration.temp_dir + subfile
@@ -289,7 +289,7 @@ class Configuration(object):
@staticmethod @staticmethod
def delete_temp(): def delete_temp():
''' Remove temp files and folder ''' ''' Remove temp files and folder '''
if Configuration.temp_dir == None: return if Configuration.temp_dir is None: return
if os.path.exists(Configuration.temp_dir): if os.path.exists(Configuration.temp_dir):
for f in os.listdir(Configuration.temp_dir): for f in os.listdir(Configuration.temp_dir):
os.remove(Configuration.temp_dir + f) os.remove(Configuration.temp_dir + f)
@@ -321,9 +321,8 @@ class Configuration(object):
result += Color.s('{W}%s------------------{W}\n' % ('-' * max_len)) result += Color.s('{W}%s------------------{W}\n' % ('-' * max_len))
for (key,val) in sorted(Configuration.__dict__.iteritems()): for (key,val) in sorted(Configuration.__dict__.iteritems()):
if key.startswith('__'): continue if key.startswith('__') or type(val) == staticmethod or val is None:
if type(val) == staticmethod: continue continue
if val == None: continue
result += Color.s("{G}%s {W} {C}%s{W}\n" % (key.ljust(max_len),val)) result += Color.s("{G}%s {W} {C}%s{W}\n" % (key.ljust(max_len),val))
return result return result

View File

@@ -74,11 +74,11 @@ class CrackHandshake(object):
Color.p(" " + ("-" * 17)) Color.p(" " + ("-" * 17))
Color.p(" " + ("-" * 19) + "\n") Color.p(" " + ("-" * 19) + "\n")
# Print all handshakes # Print all handshakes
for index, hs in enumerate(handshakes): for idx, hs in enumerate(handshakes, start=1):
bssid = hs["bssid"] bssid = hs["bssid"]
essid = hs["essid"] essid = hs["essid"]
date = datetime.strftime(datetime.fromtimestamp(hs["date"]), "%Y-%m-%dT%H:%M:%S") date = datetime.strftime(datetime.fromtimestamp(hs["date"]), "%Y-%m-%dT%H:%M:%S")
Color.p(" {G}%s{W}" % str(index + 1).rjust(3)) Color.p(" {G}%s{W}" % str(idx).rjust(3))
Color.p(" {C}%s{W}" % essid.ljust(max_essid_len)) Color.p(" {C}%s{W}" % essid.ljust(max_essid_len))
Color.p(" {C}%s{W}" % bssid) Color.p(" {C}%s{W}" % bssid)
Color.p(" {C}%s{W}\n" % date) Color.p(" {C}%s{W}\n" % date)

View File

@@ -27,17 +27,15 @@ class CrackResult(object):
name = CrackResult.cracked_file name = CrackResult.cracked_file
json = [] json = []
if os.path.exists(name): if os.path.exists(name):
f = open(name, 'r') with open(name, 'r') as fid:
text = f.read() text = fid.read()
f.close()
try: try:
json = loads(text) json = loads(text)
except Exception, e: except Exception, e:
Color.pl('{!} error while loading %s: %s' % (name, str(e))) Color.pl('{!} error while loading %s: %s' % (name, str(e)))
json.append(self.to_dict()) json.append(self.to_dict())
f = open(name, 'w') with open(name, 'w') as fid:
f.write(dumps(json, indent=2)) fid.write(dumps(json, indent=2))
f.close()
Color.pl('{+} saved crack result to {C}%s{W} ({G}%d total{W})' Color.pl('{+} saved crack result to {C}%s{W} ({G}%d total{W})'
% (name, len(json))) % (name, len(json)))

View File

@@ -100,7 +100,7 @@ class Handshake(object):
mac_regex = ('[a-zA-Z0-9]{2}:' * 6)[:-1] mac_regex = ('[a-zA-Z0-9]{2}:' * 6)[:-1]
match = re.search('(%s) [^ ]* (%s).*.*SSID=(.*)$' match = re.search('(%s) [^ ]* (%s).*.*SSID=(.*)$'
% (mac_regex, mac_regex), line) % (mac_regex, mac_regex), line)
if match == None: if match is None:
# Line doesn't contain src, dst, ssid # Line doesn't contain src, dst, ssid
continue continue
(src, dst, essid) = match.groups() (src, dst, essid) = match.groups()
@@ -139,7 +139,7 @@ class Handshake(object):
mac_regex = ('[a-zA-Z0-9]{2}:' * 6)[:-1] mac_regex = ('[a-zA-Z0-9]{2}:' * 6)[:-1]
match = re.search('(%s) (?:->|→) (%s).*Message.*(\d).*(\d)' match = re.search('(%s) (?:->|→) (%s).*Message.*(\d).*(\d)'
% (mac_regex, mac_regex), line) % (mac_regex, mac_regex), line)
if match == None: if match is None:
# Line doesn't contain src, dst, Message numbers # Line doesn't contain src, dst, Message numbers
continue continue
(src, dst, index, ttl) = match.groups() (src, dst, index, ttl) = match.groups()

View File

@@ -82,10 +82,10 @@ class Interface(object):
from Process import Process from Process import Process
import re import re
if iface == None: if iface is None:
Configuration.initialize() Configuration.initialize()
iface = Configuration.interface iface = Configuration.interface
if iface == None: if iface is None:
raise Exception('Interface must be defined (-i)') raise Exception('Interface must be defined (-i)')
output = Process(['ifconfig', iface]).stdout() output = Process(['ifconfig', iface]).stdout()

View File

@@ -23,7 +23,7 @@ class Process(object):
Returns tuple: Returns tuple:
(stdout, stderr) (stdout, stderr)
''' '''
if type(command) != str or ' ' in command or shell: if type(command) is not str or ' ' in command or shell:
shell = True shell = True
if Configuration.verbose > 1: if Configuration.verbose > 1:
Color.pe("\n {C}[?] {W} Executing (Shell): {B}%s{W}" % command) Color.pe("\n {C}[?] {W} Executing (Shell): {B}%s{W}" % command)
@@ -58,7 +58,7 @@ class Process(object):
def __init__(self, command, devnull=False, stdout=PIPE, stderr=PIPE, cwd=None, bufsize=0): def __init__(self, command, devnull=False, stdout=PIPE, stderr=PIPE, cwd=None, bufsize=0):
''' Starts executing command ''' ''' Starts executing command '''
if type(command) == str: if type(command) is str:
# Commands have to be a list # Commands have to be a list
command = command.split(' ') command = command.split(' ')
@@ -85,7 +85,7 @@ class Process(object):
Ran when object is GC'd. Ran when object is GC'd.
If process is still running at this point, it should die. If process is still running at this point, it should die.
''' '''
if self.pid and self.pid.poll() == None: if self.pid and self.pid.poll() is None:
self.interrupt() self.interrupt()
def stdout(self): def stdout(self):
@@ -110,9 +110,9 @@ class Process(object):
def get_output(self): def get_output(self):
''' Waits for process to finish, sets stdout & stderr ''' ''' Waits for process to finish, sets stdout & stderr '''
if self.pid.poll() == None: if self.pid.poll() is None:
self.pid.wait() self.pid.wait()
if self.out == None: if self.out is None:
(self.out, self.err) = self.pid.communicate() (self.out, self.err) = self.pid.communicate()
def poll(self): def poll(self):
@@ -139,7 +139,7 @@ class Process(object):
kill(pid, SIGINT) kill(pid, SIGINT)
wait_time = 0 # Time since Interrupt was sent wait_time = 0 # Time since Interrupt was sent
while self.pid.poll() == None: while self.pid.poll() is None:
# Process is still running # Process is still running
wait_time += 0.1 wait_time += 0.1
sleep(0.1) sleep(0.1)

View File

@@ -96,7 +96,7 @@ class Reaver(Attack):
(pin, psk, ssid) = self.get_pin_psk_ssid(stdout) (pin, psk, ssid) = self.get_pin_psk_ssid(stdout)
# Check if we cracked it, or if process stopped. # Check if we cracked it, or if process stopped.
if (pin and psk and ssid) or reaver.poll() != None: if (pin and psk and ssid) or reaver.poll() is not None:
reaver.interrupt() reaver.interrupt()
# Check one-last-time for PIN/PSK/SSID, in case of race condition. # Check one-last-time for PIN/PSK/SSID, in case of race condition.
@@ -240,10 +240,8 @@ class Reaver(Attack):
out = self.get_stdout() out = self.get_stdout()
# Clear output file # Clear output file
f = open(self.stdout_file, 'w') with open(self.stdout_file, 'w'):
f.write('') pass
f.close()
# CHECK FOR CRACK # CHECK FOR CRACK
(pin, psk, ssid) = Reaver.get_pin_psk_ssid(out) (pin, psk, ssid) = Reaver.get_pin_psk_ssid(out)
@@ -323,7 +321,7 @@ class Reaver(Attack):
pin_current = 11000 - pins_left pin_current = 11000 - pins_left
# Check if process is still running # Check if process is still running
if reaver.pid.poll() != None: if reaver.pid.poll() is not None:
Color.pl('{R}failed{W}') Color.pl('{R}failed{W}')
Color.pl('{!} {R}reaver{O} quit unexpectedly{W}') Color.pl('{!} {R}reaver{O} quit unexpectedly{W}')
self.success = False self.success = False
@@ -394,9 +392,8 @@ class Reaver(Attack):
''' Gets output from stdout_file ''' ''' Gets output from stdout_file '''
if not self.stdout_file: if not self.stdout_file:
return '' return ''
f = open(self.stdout_file, 'r') with open(self.stdout_file, 'r') as fid:
stdout = f.read() stdout = fid.read()
f.close()
return stdout.strip() return stdout.strip()

View File

@@ -30,7 +30,7 @@ class Scanner(object):
# Loop until interrupted (Ctrl+C) # Loop until interrupted (Ctrl+C)
while True: while True:
if airodump.pid.poll() != None: if airodump.pid.poll() is not None:
# Airodump process died! # Airodump process died!
raise Exception( raise Exception(
"Airodump exited unexpectedly! " + "Airodump exited unexpectedly! " +
@@ -76,7 +76,7 @@ class Scanner(object):
bssid = Configuration.target_bssid bssid = Configuration.target_bssid
essid = Configuration.target_essid essid = Configuration.target_essid
if bssid == None and essid == None: if bssid is None and essid is None:
return False return False
for target in self.targets: for target in self.targets:
@@ -125,10 +125,9 @@ class Scanner(object):
Color.p('\r') Color.p('\r')
Target.print_header() Target.print_header()
for (index, target) in enumerate(self.targets): for idx, target in enumerate(self.targets, start=1):
index += 1
Color.clear_entire_line() Color.clear_entire_line()
Color.pl(' {G}%s %s' % (str(index).rjust(3), target)) Color.pl(' {G}%s %s' % (str(idx).rjust(3), target))
@staticmethod @staticmethod
def get_terminal_height(): def get_terminal_height():