如果提供的用户存在,我将如何检查用户是否存在于bash脚本中并重新询问新用户?

时间:2018-06-20 19:34:12

标签: bash security scripting automation

我是bash脚本的新手,并且我试图制作一个脚本来在ubuntu服务器上设置一些基本的安全性。到目前为止,我有以下内容:

group="sudo"
read -p "Set new sudo user's name (Please try to avoid admin or administrator, some hosts have these reserved): " new_sudo_user_name
if [ -z "$(getent passwd $new_sudo_user_name)" ]; then
  echo "user does NOT exist."
else
  echo "user DOES exist."
fi

echo "Please enter the new password:"
read -s password1
echo "Please repeat the new password:"
read -s password2

if [ $password1 != $password2 ]; then
  echo "Passwords do not match"
  exit    
fi

sudo su -c "useradd $new_sudo_user_name -s /bin/bash -m -aG $group"

本质上,我要执行的操作是,在检查用户名是否已存在时,自动重新询问是否有新用户名。这可能吗?如果是这样,完成此任务的最佳实践是什么?

提前了解帮助:)

2 个答案:

答案 0 :(得分:2)

了解用户是否已经存在的Linux本机方式是像这样签入/etc/passwd文件:

if grep "${username}" /etc/passwd >/dev/null 2>&1; then
  # do something if the user exists
fi

另一种方法是使用finger命令(默认情况下并不总是安装该命令):

$ finger ineumann
Login: ineumann                 Name: Idriss Neumann
Directory: /home/ineumann               Shell: /bin/bash
On since Tue Jun 19 10:55 (CET) on tty2 from /dev/tty2
1 day 9 hours idle
No mail.
No Plan.
$ finger ineumanne
finger: ineumanne: no such user.

因此,您也可以尝试以下操作:

[[ $(finger "${username}" 2>&1) =~ "no such user" ]] && echo "User not exists" || "User exists"

要回答有关用户存在时重新询问的问题,您可以轻松地使用循环,例如while

read -p "Username: " username
while grep "${username}" /etc/passwd >/dev/null 2>&1; do
  read -p "Try again: " username
done
# Create the user...

例如until

read -p "Username: " username
until [[ $(finger "${username}" 2>&1) =~ "no such user" ]]; do
  read -p "Try again: " username
done
# Create the user...

终端中的演示

$ read -p "Username: " username; while grep "${username}" /etc/passwd >/dev/null 2>&1; do read -p "Try again: " username; done
Username: ineumann
Try again: ineumann
Try again: ineumann
Try again: Idonknow
$ read -p "Username: " username; until [[ $(finger "${username}" 2>&1) =~ "no such user" ]]; do read -p "Try again: " username; done
Username: ineumann
Try again: ineumann
Try again: ineumann
Try again: IdontKnow

顺便说一下,这是有关您的脚本的一些建议:

if [ $password1 != $password2 ]; then
  echo "Passwords do not match"
  exit    
fi

您应该使用双引号或$password1而不是$password2保护操作数[[[。请参阅this reminder,以获取更多详细信息。

答案 1 :(得分:0)

怎么样

while read -p "$prompt" user; getent passwd "$user" >/dev/null; do
    echo "user $user exists"
done
echo "proceeding with new user $user"
相关问题