Skip to content

Instantly share code, notes, and snippets.

@benok
Forked from fn-alves/csv_import.py
Last active April 22, 2019 11:14
Show Gist options
  • Save benok/c1342272108ec00ee4b78a69733a1a70 to your computer and use it in GitHub Desktop.
Save benok/c1342272108ec00ee4b78a69733a1a70 to your computer and use it in GitHub Desktop.
Import users contained in csv in bulk to samba 4 AD. csv headers: name, lastname, email, password, department, company
#!/usr/bin/env python
# https://gist.github.com/benok/c1342272108ec00ee4b78a69733a1a70
# (just translated https://gist.github.com/moritzheiber/7b08e7c89508054f67f9 in English)
import csv, sys,os
try:
file = open(sys.argv[1], "rt")
reader = csv.DictReader(file)
# Function that adds the users in samba and sets to change the password at the next login
def add_user(username,password,email,lastname,name,descr,department,company,user_ou):
os.system("/usr/bin/samba-tool user add %s \
%s \
--mail-address=%s \
--surname='%s' \
--given-name='%s' \
--description='%s' \
--department='%s' \
--company='%s' \
--userou='%s'"\
% (username,password,email,lastname,name,descr,department,company,user_ou))
os.system("/usr/bin/samba-tool user setpassword \
--newpassword=%s \
--must-change-at-next-login \
--filter=samaccountname=%s" \
% (password,username))
return
for row in reader:
# Populate the variables with the csv data
email = row['email']
username = email.split('@')[0]
password = row['password']
name = row['name']
lastname = row['lastname']
department = row['department']
company = row['company']
seq = "_"
sp_company = company.split()
company_ou = seq.join(sp_company)
user_ou = 'OU=Users,OU=%s,OU=%s' % (department,company_ou) # simplified
descr = 'Emp: %s - %s' % (company, department)
# Call the function add user by passing the parameters
add_user(username,password,email,lastname,name,descr,department,company,user_ou)
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno,strerror)
finally:
file.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment