Python Scripting with Sabayon

The goal of Sabayon is to be scriptable, that is, you can utilize Sabayon's functionality from your home-made scripts. This feature is still work in progress, though you can use this right now to apply profiles to your users.

* Documentation for Sabayon's API

Example: Applying a given profile to a given user

Assuming that the variable user stores the username and the variable profile stores the profilename, here's the code which lets you achieve this (the script needs to be run as root):

import os
import pwd

import sabayon

.... # do misc. stuff

# Create a new UserProfile object for profile
uprofile = sabayon.userprofile.UserProfile(profile)

# Get user id
uid = pwd.getpwnam(name)[2] 
# Get user's $HOME
home = pwd.getpwnam(name)[5] 
# Change working directory to $HOME of the user
os.chdir(home)
# Set current uid to the supplied username, 
# since the apply() method below only applies a 
# profile to the current user
os.setuid(uid) 

# And finally apply the profile 
uprofile.apply(False) 

Example: Applying a given profile to all members of a group

This is a small script which applies a given profile to all the members of a group. You need to run this as root.

# -*- coding: utf-8 -*-
#!/usr/bin/env python

import grp
import pwd
import os
import sys

import sabayon

# A quick hack to apply a given Sabayon profile to all the
# members of a group.
# Written by Sayamindu Dasgupta (sayamindu randomink org)

if len(sys.argv) < 3:
        print "Usage:\n\t %s <group> <profile>" % (sys.argv[0])
        sys.exit()

def apply_profile(user, profile):
        if os.fork():
                return() # Parent goes back to the loop.
        uprofile = sabayon.userprofile.UserProfile(profile)
        uid = pwd.getpwnam(user)[2]
        home = pwd.getpwnam(user)[5]
        os.chdir(home)
        os.setuid(uid)
        uprofile.apply(False)
        sys.exit() # get rid of child


group = sys.argv[1]
profile = sys.argv[2]

grp_members = grp.getgrnam(group)[3]
#TODO - user foo is usually implicitly a member of 
#       group foo. Need to implement that.

for user in grp_members:
        apply_profile(user, profile)

Apps/Sabayon/Python (last edited 2013-11-18 19:32:05 by WilliamJonMcCann)