Add/Modify Users
Operating systems have never provided a unified method of managing local user accounts. Every platform provides a unique interface for adding or modifying user accounts, and this has frequently been used as justification for abstracting all systems related changes using traditional configuration management tools.
A helper script for manage local users solves this problem by defining a single function that will add a user if it doesn't exist, or update an existing user if it is already defined.
OpenBSD
The calling convention employed in this function is specify positional
arguments followed by arguments that are only applicable to
useradd(8)
.
Remaining arguments are appended to add or modify conditions.
function userset { # args: username [useradd args ...] [usermod args ...] username=$1 shift if ! userinfo -e $username; then useradd "$@" $username else # knock off parameters that do not apply while [ $# -gt 1 ]; do case $1 in -m) shift ;; *) break ;; esac usermod "$@" $username done fi }
Examples:
userset eradman -u 1000 -G wheel,operator,wsrc,staff,dialer -c "Eric Radman" userset unlockwww -u 1003 -g 10 -c "AuthPF" -s /usr/sbin/authpf
GNU/Linux
Similar to the OpenBSD implementation, but detection of an existing user
using
id(1)
userset() { # args: username [useradd args ...] [usermod args ...] username=$1 shift if ! id $username > /dev/null; then useradd "$@" $username else # knock off parameters that do not apply while [ $# -gt 1 ]; do case $1 in -m) shift ;; *) break ;; esac usermod "$@" $username > /dev/null done fi }
Examples:
userset laura -m -u 1004 -g 1004 -s /bin/bash userset abigail -m -u 1006 -g 1006 -s /bin/bash
FreeBSD
On FreeBSD all system user commands are wrapped by
pw(8)
and the username is at the beginning rather than the end.
userset() { # args: username [useradd args ...] [usermod args ...] username=$1 shift if ! pw usershow $username 2>/dev/null 1>/dev/null; then pw useradd $username "$@" else # knock off parameters that do not apply while [ $# -gt 1 ]; do case $1 in -m) shift ;; *) break ;; esac pw usermod $username "$@" done fi }
Examples:
userset abigail -m -u 1006 -G guest -c "Abigail"