Folks,

I needed to audit who had access to which projects and with what permissions, 
so I wrote a script (see below).  This works for me for Trac 0.12.5 but I would 
welcome your suggestions on how to improve it:

 * make it more pythonic
 * make it work for other versions of trac
 * fix any issues I haven't noticed.

Note it is based on various snippets I have collected over the last few years 
of using Trac.  Also, we have a limited number of users, so the output is fine 
for me but may be unwieldy for you (suggestions welcome!)

Many thanks!

~ Mark C

{{{
"""list_users

A python script to list which users have access to which projects.
"""

import os
import sys
import traceback

from optparse import OptionParser

from trac.env import Environment
from trac.perm import PermissionSystem

def doArgs():
    """Parse command line options"""
    description = ( "%prog is used to list users and projects for a Trac root "
                    "collection of environments." )

    parser = OptionParser(usage="usage: %prog [options]",
                          version="1.0", description=description)
    parser.add_option("-r", "--root", dest="envroot", type="string",
                      help="Path to a Trac parent folder", metavar="<path>")
    (options, args) = parser.parse_args()

    if options.envroot is None:
        options.envroot = '.'
    if not os.path.exists(options.envroot):
        print "The path >%s< does not exist.  Please specify an existing path." 
% (fpath,)
        sys.exit(1)

    return options

# --------------------------------------------------------------------------- #

def get_user_name( env, userid ):
    """get_user_name( env, userid )
    
    Return the "Full Name" for the specified userid.
    """
    fullname = ''

    for usr in env.get_known_users():
        if usr[0] == userid:
            fullname = usr[1]
            break
    return fullname

# --------------------------------------------------------------------------- #

def process_env( env, data ):
    """process_env( env, data )
    
    Process the permissions in `env` and stroe the results into data:
    { <user-id> : { <project-1> : [ <p1>, ..., <pn> ] },
                  ...
                  { <project-n> : [ <p1>, ..., <pn> ] },
      ...
      <user-id> : { <project-1> : [ <p1>, ..., <pn> ] },
                  ...
                  { <project-n> : [ <p1>, ..., <pn> ] }
    }
    """
    print 'Processing ', env.project_name

    pname = env.project_name
    perms = PermissionSystem(env)
    for row in perms.get_all_permissions():
        # returns a list of (subject, action) formatted tuples.
        uname = row[0]
        if not data.has_key(uname):
            data[uname] = dict()
            data[uname]['user_name'] = ''
        dd = data[uname]
        if not data[uname]['user_name']:
            data[uname]['user_name'] = get_user_name(env, uname)
        if not dd.has_key(pname):
            dd[pname] = list()
        ll = dd[pname]
        ll.append( row[1] )

# --------------------------------------------------------------------------- #

def process_folder( fpath, data ):
    """process_folder( fpath, opts )
    
    Try to load a Trac Environment in the specified folder.  Retrieve the user
    permission data if successful...
    """
    try:
        env = Environment( fpath )

        # Get the user's full name...
        process_env( env, data )

    except:
        print 'Unable to process environment in "%s":' % (fpath, )
        print '-'*60
        traceback.print_exc(file=sys.stdout)
        print '-'*60


# =========================================================================== #

if __name__ == '__main__':
    opts = doArgs()
    data = dict()
    if opts.envroot:
        # try to walk the first layer of folders...
        for root, dirs, files in os.walk( opts.envroot ):
            for dir in dirs:
                envpath = os.path.join(opts.envroot, dir)
                process_folder( envpath, data )

            # only do the top level of folders
            break

    print

    # Display the results...
    users = data.keys()
    users.sort()
    skipped = []
    for user in users:
        # ignore built-in and site-standard permission groups:
        if user in ('authenticated', 'authorised', 'gPigs', 'gChickens'):
            skipped.append( user )
        else:
            dd = data[user]
            print 'User: %s (%s)' % ( user, dd['user_name'] )
            # Display permissions nicely in alpha-sorted project order:
            projects = dd.keys()
            projects.remove('user_name')
            projects.sort()
            mlen = max( [len(x) for x in projects] )
            for proj in projects:
                print '    :', proj.ljust(mlen), ' : ', ', '.join(dd[proj])
    print
    if skipped:
        print 'Skipped users:', skipped
    sys.exit()
}}}

-- 
You received this message because you are subscribed to the Google Groups "Trac 
Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to trac-users+unsubscr...@googlegroups.com.
To post to this group, send email to trac-users@googlegroups.com.
Visit this group at http://groups.google.com/group/trac-users.
For more options, visit https://groups.google.com/d/optout.

Reply via email to