/users.py

https://bitbucket.org/techtonik/python-sysadmin · Python · 69 lines · 62 code · 3 blank · 4 comment · 2 complexity · e6a7c4533b28fa2ac3cb411afd5d4fdf MD5 · raw file

  1. #!/usr/bin/env python
  2. """
  3. Cross-platform operating system tool to 'work' with user accounts
  4. Placed in public domain by anatoly techtonik <techtonik@php.net>
  5. Also available under the terms of MIT License
  6. Supports: Unix, Windows, MacOS
  7. === Get names of all users on the system ===
  8. users.py
  9. """
  10. __version__ = '0.2'
  11. import optparse
  12. import os
  13. import subprocess
  14. import sys
  15. # --- helpers ---
  16. def run(command):
  17. """Run command, return output from stdout"""
  18. return subprocess.Popen(command, stdout=subprocess.PIPE).communicate()[0]
  19. # --- /helpers ---
  20. def users_list(humans=True):
  21. usernames = []
  22. if os.name == 'posix':
  23. import pwd
  24. # http://docs.python.org/2/library/pwd.html
  25. for name, passwd, uid, gid, gecos, dir, shell in pwd.getpwall():
  26. # users with UID < 1000 are not humans
  27. # http://askubuntu.com/questions/257421/list-all-human-users
  28. if humans and uid >= 1000:
  29. usernames.append(name)
  30. elif os.name == 'macos':
  31. usernames = run('dscl . list /users').splitlines()
  32. elif os.name == 'nt':
  33. output = run('net user')
  34. ''' # example of Windows output for parsing
  35. C:\>net user
  36. User accounts for \\DARKBOX
  37. -------------------------------------------------------------------------------
  38. Administrator anatoly Guest
  39. The command completed successfully.
  40. '''
  41. userline = output.splitlines()[4:-2]
  42. userline = ''.join(userline)
  43. usernames = [userline[i:i+25] for i in xrange(0, len(userline), 25)]
  44. else:
  45. sys.exit('Error: Nobody contributed code for "%s" command on os.name:%s yet'
  46. % ('users list', os.name))
  47. return usernames
  48. if __name__ == '__main__':
  49. if '-h' in sys.argv or '--help' in sys.argv:
  50. sys.exit('list user accounts\nusage: users [-h|--help]')
  51. for x in users_list():
  52. print(x)