Advertisement
FocusedWolf

Python: Password Generator

Apr 3rd, 2022 (edited)
459
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.35 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. # Version 6
  4.  
  5. # POSTED ONLINE: https://pastebin.com/g10jVftx
  6.  
  7. # Windows: $ pip install pyperclip asciimatics
  8. # Linux:   $ sudo pacman -S python-pyperclip
  9. #          $ sudo pacman -S wl-clipboard    <-- Pyperclip has issues with KDE + Wayland. Installing this seems to get it to work.
  10. #          $ yay -S python-asciimatics
  11. # NOTE: For Linux you also need to install a copy/paste mechanism if you don't have one. KDE has /bin/klipper installed by default, otherwise try [$ sudo pacman -S xclip] or [$ sudo pacman -S xsel].
  12. #       If you get error "Cannot find '.setClipboardContents' in object /klipper at org.kde.klipper",
  13. #       its because klipper isn't running on startup. Try Start > klipper and see if the problem goes away.
  14. #       To display klipper in taskbar right click the ^ > Configure System Tray... > Entries > Clipboard: [Show when relevant].
  15.  
  16. import pyperclip
  17. from asciimatics.screen import Screen
  18. from asciimatics.event import KeyboardEvent
  19.  
  20. # -----
  21.  
  22. def draw_menu(screen, menuItems, selectedIndex, title=''):
  23.     # Clear screen.
  24.     clear(screen)
  25.  
  26.     # Draw title.
  27.     if title:
  28.         writeline(screen, title)
  29.  
  30.     # Draw menu items.
  31.     for i in range(len(menuItems)):
  32.         writeline(screen, f' {"●" if i == selectedIndex else "○"} {menuItems[i]}', Screen.COLOUR_GREEN if i == selectedIndex else Screen.COLOUR_CYAN)
  33.     writeline(screen)
  34.  
  35.     # Draw usage information.
  36.     writeline(screen, ' Make → Space', Screen.COLOUR_YELLOW)
  37.     writeline(screen, ' Copy → Enter', Screen.COLOUR_YELLOW)
  38.     writeline(screen, ' Rise → Up', Screen.COLOUR_YELLOW)
  39.     writeline(screen, ' Fall → Down', Screen.COLOUR_YELLOW)
  40.     writeline(screen, ' Smol → Left', Screen.COLOUR_YELLOW)
  41.     writeline(screen, ' Swol → Right', Screen.COLOUR_YELLOW)
  42.     writeline(screen, ' Quit → Escape', Screen.COLOUR_YELLOW)
  43.  
  44.     # Draw screen.
  45.     screen.refresh()
  46.  
  47. # -----
  48.  
  49. def clear(screen):
  50.     global current_line
  51.     current_line = 0
  52.     screen.clear()
  53.  
  54. # -----
  55.  
  56. current_line = 0
  57. def writeline(screen, text='', color=Screen.COLOUR_WHITE):
  58.     global current_line
  59.     lines = text.split('\n')
  60.     for i, line in enumerate(lines):
  61.         screen.print_at(line, 0, current_line, color)
  62.         current_line += 1
  63.  
  64. # -----
  65.  
  66. from datetime import datetime
  67. def generate_timestamped_passwords(password_length, count=5):
  68.     dt = datetime.now()
  69.     SHORT_TIME_STAMP = dt.strftime('%y%m%d')
  70.     SHORT_TIME_STAMP_LENGTH = len(SHORT_TIME_STAMP)
  71.     reducedLength = password_length - SHORT_TIME_STAMP_LENGTH
  72.     passwords = [SHORT_TIME_STAMP + generate_password(reducedLength) for i in range(count)]
  73.  
  74.     LARGE_TIME_STAMP = dt.strftime('%Y-%m-%d %H:%M:%S')
  75.     timestamp =  f' Created: {LARGE_TIME_STAMP}\n'
  76.     timestamp += f' Length: {password_length}\n'
  77.     return passwords, timestamp
  78.  
  79. # -----
  80.  
  81. import string
  82. import secrets
  83. def generate_password(password_length):
  84.     # Comment out or add usable characters here.
  85.     PASSWORD_CHARACTERS = [
  86.         string.ascii_lowercase,
  87.         string.ascii_uppercase,
  88.         string.digits,
  89.         string.punctuation,
  90.     ]
  91.  
  92.     characters = "".join(PASSWORD_CHARACTERS)
  93.  
  94.     # SOURCE: https://docs.python.org/3/library/secrets.html
  95.     password = ''.join(secrets.choice(characters) for i in range(password_length))
  96.     return password
  97.  
  98. # -----
  99.  
  100. def wait_for_any_keypress(screen):
  101.     writeline(screen, ' Press any key to continue . . . ')
  102.     screen.refresh()
  103.  
  104.     # Wait for user keyboard input indefinitely.
  105.     while True:
  106.         screen.wait_for_input(5) # Sleep for this many seconds while waiting for input. This prevents 100% CPU usage from the loop.
  107.         ev = screen.get_event()
  108.         if isinstance(ev, KeyboardEvent):
  109.             break
  110.  
  111. # -----
  112.  
  113. MIN_PASSWORD_LENGTH = 8
  114.  
  115. def main(screen):
  116.     password_length = 23
  117.     menuItems, timestamp = generate_timestamped_passwords(password_length)
  118.     selectedIndex = 0
  119.     draw_menu(screen, menuItems, selectedIndex, timestamp) # Initial drawing.
  120.  
  121.     while True:
  122.         # Get keyboard input.
  123.         screen.wait_for_input(5) # Sleep for this many seconds while waiting for input. This prevents 100% CPU usage from the loop.
  124.         ev = screen.get_event()
  125.         if not isinstance(ev, KeyboardEvent):
  126.             continue
  127.  
  128.         # If Escape key is pressed.
  129.         elif ev.key_code == -1:
  130.             break
  131.  
  132.         # If Space key is pressed.
  133.         elif ev.key_code == ord(' '):
  134.             menuItems, timestamp = generate_timestamped_passwords(password_length)
  135.  
  136.         # If Up key is pressed.
  137.         elif ev.key_code == Screen.KEY_UP:
  138.             # Loop around backwards.
  139.             selectedIndex = (selectedIndex - 1 + len(menuItems)) % len(menuItems)
  140.  
  141.         # If Down key is pressed.
  142.         elif ev.key_code == Screen.KEY_DOWN:
  143.             # Loop around forwards.
  144.             selectedIndex = (selectedIndex + 1) % len(menuItems)
  145.  
  146.         # If Left key is pressed.
  147.         elif ev.key_code == Screen.KEY_LEFT:
  148.             # Reduce length of passwords.
  149.             password_length = max(MIN_PASSWORD_LENGTH, password_length - 1)
  150.             menuItems, timestamp = generate_timestamped_passwords(password_length)
  151.  
  152.         # If Right key is pressed.
  153.         elif ev.key_code == Screen.KEY_RIGHT:
  154.             # Increase length of passwords.
  155.             password_length = password_length + 1
  156.             menuItems, timestamp = generate_timestamped_passwords(password_length)
  157.  
  158.         # If Enter key is pressed.
  159.         # NOTE: On Windows the enter key appears to be \r, and on Linux its \n.
  160.         elif ev.key_code == ord('\r') or ev.key_code == ord('\n'):
  161.             pyperclip.copy(menuItems[selectedIndex])
  162.             writeline(screen, f"\n Copied {menuItems[selectedIndex]} to clipboard.\n")
  163.             wait_for_any_keypress(screen)
  164.  
  165.         # Else an unexpected key is pressed.
  166.         #  else:
  167.         #      try:
  168.         #          writeline(screen, "\n The pressed key '{}' {} is not associated with a menu function.\n".format(chr(ev.key_code), ev.key_code))
  169.         #      except ValueError:
  170.         #          writeline(screen, "\n The pressed key {} is not associated with a menu function.\n".format(ev.key_code))
  171.         #      wait_for_any_keypress(screen)
  172.  
  173.         draw_menu(screen, menuItems, selectedIndex, timestamp)
  174.  
  175. if __name__ == '__main__':
  176.     Screen.wrapper(main)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement