Create users from a CSV with a script kept in Git
Task
Automate account creation: read a CSV of new starters, create each account with the right groups and home folder, skip anyone who already exists, and log what was done. Keep the script in a Git repository, change it once through a commit, and roll the change back -- scripts are code and get code's discipline.
Steps
- Write
lab/users/starters.csvwith headerusername,fullname,groupand eight made-up users across two groups. Create both groups. - Write
lab/users/create-users.shthat reads the CSV, skips the header, checks withidwhether each user exists, and otherwise runsuseradd -m -c <fullname> -G <group> <username>, loggingcreatedorskippedwith a timestamp tolab/users/run.log. It exits non-zero if the CSV is missing. - Initialise a Git repository in
lab/users, commit the script and CSV, and run the script twice. Save the second run's log lines tolab/users/second-run.log. - Change the script to also set an expiry date on each new account, commit it, then revert that commit with
git revert. Savegit log --onelinetolab/users/history.txt. - Delete the test accounts and their home folders.
Verify
These checks run in a POSIX shell: Terminal on macOS or Linux, and on Windows Git Bash (it comes with Git for Windows) or WSL. A stock Windows PowerShell or Command Prompt has no awk or grep, so there the first line fails.
grep -c 'created' lab/users/run.log
grep -c 'skipped' lab/users/second-run.log
grep -c 'created' lab/users/second-run.log
grep -Eic 'revert' lab/users/history.txt
wc -l < lab/users/history.txt
The first run created eight accounts, and the second skipped all eight and created none -- the script is safe to run twice, which is what makes it safe to schedule. The history shows at least three commits, including the revert: the change and its undoing are both on record.
Notes
The Windows equivalent is Import-Csv piped to New-ADUser in a domain, with the same rule: check before creating, log every action, and never put a password in the CSV or the script.
This is an independent study companion for CompTIA Server+ SK0-005 and is not produced by or endorsed by CompTIA.