Saturday, July 6, 2013

Create User Accounts From A csv File In Linux Using Python

Here's a script that I wrote that creates user accounts and home directories from a csv in Linux using Python.

This is a common system administration task that be done using shell scripts but is much easier using Python.

Python has a handy csv module that parses csv files so you do not have to worry about it yourself.

I plan to focus my studies on Linux after I complete the MCITP: Enterprise Messaging Administrator 2010 certification.  So there will be more scripts to come.

#!/usr/bin/python
#pyuseradd.py
#Read users from a csv file and create accounts and home directories.
#Sheldon Alman - sheldonalman@gmail.com
#csv file format : firstname, lastname, username, password
import sys, csv, subprocess

if len(sys.argv) != 2:
    print "Usage: " + str(sys.argv[0]) + " filename"
else:
    filename = str(sys.argv[1])
    with open(filename,  'rb') as csvfile:
        accounts = csv.reader(csvfile)
        for row in accounts:
            subprocess.call(['useradd', '-m' , '-s' + '/bin/bash','-c' + row[0] + row[1] ,  row[2]])
            subprocess.call('echo ' + row[2] +":" + row[3] + " | " + "chpasswd",  shell=True )