(Linux-Bash) Create an account for each user and add the user to its group from a text file [closed] - linux

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a username.txt which contains their username and specific group. As of right now i'm trying to create a bash script which allows me to create an account for each user and add the user to its group in one command.
this is currently my failed bash script(i know pretty much everything is wrong but i hope you guys got a clear idea on it):
#!/bin/bash
sudo addgroup staff
sudo addgroup visitors
username="username.txt"
while read line; do
sudo useradd $-Eo '^[^,]+' $username;
if [grep staff $username]; then
sudo usermod -a -G staff
else
sudo usermod -a -G visitors
done < $username
This is what is inside my username.txt file:
ellipsiscoterie,visitor
magnetcommonest,visitor
belateddefensive,staff
bobstercaramelize,staff

Let's go through your script.
#!/bin/bash
sudo addgroup staff
sudo addgroup visitors
username="username.txt"
OK. There is some debate about using sudo in scripts, but I'm not against it.
while read line; do
You read the line from STDIN, which is your input file. The variable line contains ellipsiscoterie,visitor in the first iteration.
sudo useradd $-Eo '^[^,]+' $username;
$- prints The current set of options in your current shell. It will produce something like himBH. The next argument seems a regular expression, and the last argument is the filename that you use. So the command here is:
sudo useradd himBHEo '^[^,]+' username.txt
Hint: if you are unsure of the arguments, check with an echo (echo $-Eo '^[^,]+' $username) before you add them to a sudo-ed command.
This is not what you want. First, you probably want to use the variable line instead of username. Why would you otherwise loop through that file?
Second, read-up on variable expansion in bash. For now, try:
line=ellipsiscoterie,visitor
echo ${line%,*}
echo ${line#*,}
So the line would probably need to be:
sudo useradd ${line%,*}
if [grep staff $username]; then
This is wrong in almost everything.
the [ and ] require spaces to set them apart
but you dont want to do a test, you want to see if the grep succeeds, so the [ and ] are not needed anyway
you are again using the complete file. So the grep succeeds if there is any line with staff in it; even if the username would be johnfalstaff
What you really want to know is if the second column in your line is staff, so:
if [ "${line#*,}" = "staff" ] ; then
sudo usermod -a -G staff
else
sudo usermod -a -G visitors
So, where is the fi that closes the if statement?
done < $username
Also, quote the filename: done < "$username"

You can use awk to write it in one line. In this case, awk splits each row into different columns and you can access each field separately.
awk -F "," '{ if(system("grep -q -E "$2" /etc/group") != 0 ){system("groupadd "$2)}; system("useradd "$1" -G "$2)}' username.txt
The first argument (-F ",") defines the field-separator, but it could be also something else e.g. ";" or "/"
The part if(system("grep -q -E "$2" /etc/group") != 0 ) verifies if the group exist and if not, the part {system("groupadd "$2)} creates the group before the next command system("useradd "$1" -G "$2) creates the user and adds it to the group $2.
It's possible to simplify the command to remove the if part, but then you will get a warning message that the user already exists.
awk -F "," '{ system("groupadd "$2); system("useradd "$1" -G "$2)}' username.txt
groupadd: group 'visitor' already exists
groupadd: group 'staff' already exists
btw: the part system executes just an operating system command

The newusers command allows you to configure users from a file in batch:
https://www.man7.org/linux/man-pages/man8/newusers.8.html

Related

Useradd script in linux without using passwd

I have to write a useradd script which adds a new user and sets for him a home directory.
#!/bin/bash
echo "Name:"
read name
echo "Password:"
read password
echo "Group:"
read group
useradd -m -G $group -s /bin/bash -p $password $name
Everything works as intended but I have problems with the password in the following line -
useradd -m -G $group -s /bin/bash -p $password $name
It does not work so I need to use later in terminal passwd command.
How can I rebuild my script so I won't need to use passwd to setup password correctly? I have read that you can use stdin but I was not able to do this correctly.
If you prefer to pipe the user's password from STDIN, use chpasswd utility which is quick and simple.
as suggested by #Ardit.
This script should work for your purpose, assuming you meet the following conditions-
You are interacting as the root user
You have an existing group created for the purpose of your new user
#!/bin/bash
echo "Name:"
read name
echo "Password:"
read password
echo "Group:" # group must exist
read group
# add new user, set group, create new home directory
useradd -G $group -m $name
# update new user password by piping from STDIN
echo ""$name":"$password"" | chpasswd
# change the default user shell to bash
chsh -s /bin/bash $name
First we execute useradd command to create the new user and assign it to an existing group.
Then we pipe the name and password into chpasswd. If you're wondering why wrap those variable expansions with double quotes, check this answer out .
Finally chsh utility is used to update the user shell.
Why not execute everything in a single statement?
I prefer subdividing a problem into smaller tasks for easier understanding.

How can I automatically respond to a password prompt via the command line?

I'm looking to respond to a password prompt in the linux terminal. I know how to do this with echo and a non-password prompt. For example, let's say whatsyourname.sh prompted me for a string with my name after being ran, but didn't allow my name to be passed as an argument in the inital command. I would do the following:
echo -e "dan" | ./whatsyourname.sh
However, if I ran a command that asked me for a password after being ran, the following does not work:
echo -e "supersecurepassword" | sudo apt-get update
I'm guessing this has something to do with the fact that the characters are hidden while a password is being input in the command line. How would I respond to a password prompt within the inital command?
You're looking for sudo -S
Explaining -S - man sudo
-S, --stdin
Write the prompt to the standard error and read the password from the standard input instead of
using the terminal device. The password must be followed by a newline character.
Simple,
#!/bin/bash
echo "notsecure" | sudo -S apt-get update
Variable,
#!/bin/bash
pass="notsecure"
echo $pass | sudo -S apt-get update
Lets still type it,
#!/bin/bash
read -s -p "[sudo] sudo password for $(whoami): " pass
echo $pass | sudo -S apt-get update
Explaining -s and -p - help read
-r do not allow backslashes to escape any characters
-s do not echo input coming from a terminal
Handy if you make a script that logs into multiple servers to view route -n for example.

Script to check if user belongs to sudo group

I think I'm fairly close to checking if a user belongs to the sudo group in Ubuntu, then add a line to the sudoers file. Except when I look in the sudoers file, I see:
$IDUSER ALL=NOPASSWD: /usr/local/sbin/myscript
instead of that users name, eg.
bob ALL=NOPASSWD: /usr/local/sbin/myscript
Here is what I have:
#! /bin/sh
set -e
IDUSER=$(grep -Po '^sudo.+:\K.*$' /etc/group)
if [ `id -u $IDUSER 2>/dev/null || echo -1` -ge 0 ]; then
echo '$IDUSER ALL=NOPASSWD: /usr/local/sbin/myscript' >> /etc/sudoers
else
echo "Script failed..."
fi
Ideally, I'd like to add all users in the sudo group to the sudoers file.
Thank you.
In single quotes ', bash variables don't get expanded. Use double quotes " instead in the line with echo.
If you're just trying to let users in the group sudo run this command, though, just add the line:
%sudo ALL=NOPASSWD: /usr/local/sbin/myscript
to the /etc/sudoers file. The % sign denotes a group, here.

Creating a Script that will create user accounts (using useradd) from a .txt file of usernames [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I need to create a script that will create user accounts (using useradd) from a .txt file of usernames. Please help me because my professor has not been the best of help.
The text file's name is users.txt
The only in the file is usernames, we are suppose to set up a default password and have it where they must change it on the next logon. We are also supposed to add them into a group called interns.
Here is what I have so far:
#!/bin/bash
for i in users.txt
do
sudo echo $i
sudo useradd $i -m -d /home/$i -s /bin/bash $i -G sudo interns $i
passwd = echo "AIST2330password" | passwd -stdin $i
sudo passwd -e $i
echo "User must change password when they come back"
done
This line:
for i in users.txt
should be:
for i in $(cat users.txt)
Your code is iterating over the literal string users.txt, not the contents of the file.
And this line:
passwd = echo "AIST2330password" | passwd -stdin $i
should be:
echo "$i:AIST2330password" | chpasswd
because the --stdin option to passwd has been deprecated.

How to execute multiple commands with sudo in script [duplicate]

This question already has answers here:
How to run two commands with sudo?
(11 answers)
Closed 7 years ago.
Can we use heredocs to run multiple commands using sudo?
I am facing an issue (need to pass password for every command) while running
multiple commands:
echo 'password'| sudo -S ls
echo 'password'| sudo -S cat /var/log/abc.log
Can anyone help me how to automate this in a script? Like:
echo 'password' | sudo -S << ENDBLOCK
ls
cat
ENDBLOCK
you can run sh -c ..., but remember to quote properly.
sudo sh -c 'id; echo another command ; id'
sudo must see this as a single argument for the sh command.
Of course you can use new line instead of semicolon:
sudo sh -c '
echo "I am root"
id
echo "another command"
id
'
One way is to write a script with all the things you need to do with sudo and then run the script with sudo.
you could put all your commands in a script. Then
sudo ./script.sh
put permissions for script.sh in /etc/sudoers.d; that way you'll never need to type your password again (for that script)

Resources