Better error handling and output format (#6)

* Update readme: fix small redirection mistake

* Use one output line per password

* More graceful error handling

* Only catch UnicodeErrors
This commit is contained in:
Toon 2019-03-14 15:33:15 +01:00 committed by Michael Pound
parent f2048b7d15
commit 3279ad4dd5
2 changed files with 15 additions and 9 deletions

View File

@ -1,7 +1,6 @@
# pwned-search # pwned-search
Pwned Password API lookup Pwned Password API lookup
- Required libaries: - Required libaries:
* requests: `pip install requests` * requests: `pip install requests`
@ -11,7 +10,7 @@ Usage:
* `python pwned.py` reads passwords from standard input; * `python pwned.py` reads passwords from standard input;
* `python pwned.py <[file-with-passwords]` reads passwords from * `python pwned.py <[file-with-passwords]` reads passwords from
a file; a file;
* `another-command | python pwned.py <[file-with-passwords]` reads * `another-command | python pwned.py` reads
passwords written to standard output by another command; passwords written to standard output by another command;
* `python pwned.py [password]` checks passwords given as command line * `python pwned.py [password]` checks passwords given as command line
arguments (beware the password may be saved in shell history and that arguments (beware the password may be saved in shell history and that
@ -20,4 +19,3 @@ Usage:
Thanks to those who fixed my dodgy code :) Thanks to those who fixed my dodgy code :)
Have fun! Oh, and if you find one of your own passwords, change it asap! Have fun! Oh, and if you find one of your own passwords, change it asap!

View File

@ -22,6 +22,7 @@ def lookup_pwned_api(pwd):
Raises: Raises:
RuntimeError: if there was an error trying to fetch data from pwned RuntimeError: if there was an error trying to fetch data from pwned
database. database.
UnicodeError: if there was an error UTF_encoding the password.
""" """
sha1pwd = hashlib.sha1(pwd.encode('utf-8')).hexdigest().upper() sha1pwd = hashlib.sha1(pwd.encode('utf-8')).hexdigest().upper()
head, tail = sha1pwd[:5], sha1pwd[5:] head, tail = sha1pwd[:5], sha1pwd[5:]
@ -39,13 +40,20 @@ def main(args):
ec = 0 ec = 0
for pwd in args or sys.stdin: for pwd in args or sys.stdin:
pwd = pwd.strip() pwd = pwd.strip()
sha1pwd, count = lookup_pwned_api(pwd) try:
if count: sha1pwd, count = lookup_pwned_api(pwd)
print("{} was found".format(pwd))
print("Hash {0}, {1} occurrences".format(sha1pwd, count)) if count:
foundmsg = "{0} was found with {1} occurrences (hash: {2})"
print(foundmsg.format(pwd, count, sha1pwd))
ec = 1
else:
print("{} was not found".format(pwd))
except UnicodeError:
errormsg = sys.exc_info()[1]
print("{0} could not be checked: {1}".format(pwd, errormsg))
ec = 1 ec = 1
else: continue
print("{} was not found".format(pwd))
return ec return ec