Linux: How to Create a User and Add to Group in a Single Line?

This is a common question for Linux Admins. It would be necessary to memorize the syntax of this command (assuming non Active Directory or LDAP integrated machines):

sudo adduser <username> -g <groupname>

This similar keyword command would also work

sudo useradd <username> <groupname>

Which can also be achieved using a related command:

sudo usermod -aG <groupname> <username>

Beyond answering the basic question, it’s important to understand the application and implication of those commands. Let’s discuss that below.

In the real world, Linux Admins receive onboarding requests often. Besides creating a user, it’s also important to set the home directory, shell environment, group memberships, etc.  Therefore, it would be necessary to have a bash shell handy to automate accounts generation such as this one:

#!/bin/bash

# Declare an array of string called username.
# Note that bash shell interprets comma or space as delimiters
usernames=("kimconnect" "somethingconnect")

# group
group = "permitssh"

# use openssl to generate md5 hash string as password
password=$(openssl passwd -1 "DEFAULT_INIT_PASSWORD")

# iterate through the array
for user in "${usernames[@]}"
do
# Create user with password, group, home directory, and login bash environment.
useradd $user -p $password -g $group -d /home/$user -s /bin/bash
done

When dealing with multiple servers, use this method to add users to multiple machines.

a. Create a List of users:

General format:

username:passwd:UID:GID:"Full_Name","Room_Number","Work_Phone","Home_Phone","Other":"Home_Directory":"Shell_Environment"

Example (null values for UID & GID to assume defaults):

kimconnect:passy1:::"Kim Connect","001","555-555-5555","555-555-5555","Accounting":"/home/kimconnect":"/bin/bash"
dragoncoin:passy2:::"Jimmy Bond","007","555-555-5555",,"Information Technology":"home/dragoncoin":"/bin/bash"

b. Create a list of Servers

cat << ENDCAT > /home/kimconnect/servers.txt
192.166.166.1
192.166.166.15
webserver007.kimconnect.com
ENDCAT

b. Create shell script, set it as executable, and run it

# Create Shell File
cat << ENDCAT > /home/kimconnect/addusers.sh
#!/bin/bash
ssh-keygen -t rsa
while read server;
do ssh-copy-id -i ~/.ssh/id_rsa.pub root@$server;
done < servers.txt
ENDCAT

# Set script as executable
chmod a+x /home/kimconnect/addusers.sh

# Execute the script on the predetermined list of servers
addusers.sh < servers.txt

The usage of scripting to generate domain or LDAP accounts is outside the scope of this document. That should be covered it this blog somewhere.

Posted on Categories Linux

Leave a Reply

Your email address will not be published. Required fields are marked *