/users.py
https://bitbucket.org/techtonik/python-sysadmin · Python · 69 lines · 62 code · 3 blank · 4 comment · 2 complexity · e6a7c4533b28fa2ac3cb411afd5d4fdf MD5 · raw file
- #!/usr/bin/env python
- """
- Cross-platform operating system tool to 'work' with user accounts
- Placed in public domain by anatoly techtonik <techtonik@php.net>
- Also available under the terms of MIT License
- Supports: Unix, Windows, MacOS
- === Get names of all users on the system ===
- users.py
- """
- __version__ = '0.2'
- import optparse
- import os
- import subprocess
- import sys
- # --- helpers ---
- def run(command):
- """Run command, return output from stdout"""
- return subprocess.Popen(command, stdout=subprocess.PIPE).communicate()[0]
- # --- /helpers ---
- def users_list(humans=True):
- usernames = []
- if os.name == 'posix':
- import pwd
- # http://docs.python.org/2/library/pwd.html
- for name, passwd, uid, gid, gecos, dir, shell in pwd.getpwall():
- # users with UID < 1000 are not humans
- # http://askubuntu.com/questions/257421/list-all-human-users
- if humans and uid >= 1000:
- usernames.append(name)
- elif os.name == 'macos':
- usernames = run('dscl . list /users').splitlines()
- elif os.name == 'nt':
- output = run('net user')
- ''' # example of Windows output for parsing
- C:\>net user
- User accounts for \\DARKBOX
- -------------------------------------------------------------------------------
- Administrator anatoly Guest
- The command completed successfully.
- '''
- userline = output.splitlines()[4:-2]
- userline = ''.join(userline)
- usernames = [userline[i:i+25] for i in xrange(0, len(userline), 25)]
- else:
- sys.exit('Error: Nobody contributed code for "%s" command on os.name:%s yet'
- % ('users list', os.name))
- return usernames
- if __name__ == '__main__':
- if '-h' in sys.argv or '--help' in sys.argv:
- sys.exit('list user accounts\nusage: users [-h|--help]')
- for x in users_list():
- print(x)