PageRenderTime 42ms CodeModel.GetById 20ms app.highlight 4ms RepoModel.GetById 16ms app.codeStats 0ms

/users.py

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