Richard Jones' Log: Using Solaris "priv" with Fabric

Tue, 26 Jul 2011

I needed support for "priv" instead of Fabric's built-in "sudo" support. I went through a number of (sometimes quite horrific) iterations before I settled on this relatively simple solution:

import contextlib

@contextlib.contextmanager
def priv(user):
    '''Context manager to cause all run()'ed operations to be
    priv('user')'ed.
    
    Replaces env.shell with the priv command for the duration of the
    context.
    '''
    save_shell = env.shell
    env.shell = 'priv su - %s -c' % user
    yield
    env.shell = save_shell

This is then used in a fabfile like so:

    with priv('remote_user'):
        run('do some remote command as remote_user')
        run('another remote command as remote_user')