Shell 创建 linux 用户的脚本,用户名和密码从配置文件中读取

Shell script to create linux users where username and password are read from a config file

我正在尝试开发一个 shell 脚本,它可以在 linux 机器上创建新用户。从配置文件中获取用户名和密码的位置。有人可以帮我创建一个脚本,使用配置文件中的所有用户名创建用户。

我的配置文件包含 (myconf.cfg)

username="tempuser"
password="passXXX"

username="newuser"
password="ppwdXXX"
.....
.....

username="lastuser"
password="pass..."

我正在尝试使用脚本创建具有上面列出的用户名和密码的用户。脚本是:

#!/bin/sh 

echo "Reading config...." >&2
. /root/Downloads/guest.cfg

pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)

sudo useradd -m -p $pass $username -s /bin/bash

我只能使用此脚本创建 1 个用户(即 lastuser)。有人可以帮我修改脚本和配置文件,以便创建配置文件中提到的所有用户。我的目标是保持脚本完好无损,只对配置文件进行更改。该脚本应该能够创建配置文件中列出的 'N' 个用户。

提前致谢。

问题是您来源 guest.cfg 将设置变量 usernamepassword 相乘多次,每次都覆盖前一组。您需要解析配置文件。

一种方法——假设用户名/密码中没有换行符——是使用 sed:

sed -n -e 's/\(password\|username\)="\(.*\)"//gp' guest.cfg

这将打印与模式匹配的行:username="..."password="..." 因此,例如对于您的示例,输出将是:

tempuser
passXXX
newuser
ppwdXXX
lastuser
pass...

如您所见,您现在得到了这个模式:

username
password
username
password
...

这可以在 while 循环中使用:

sed -n -e 's/\(password\|username\)="\(.*\)"//gp' guest.cfg \
  | while IFS= read -r line; do
    if [ -n "$username" ]; then
      password="$line"
      # Do stuff with $username and $password
      # ...
      # At the end you need to unset the username and password:
      username=
      password=
    else
      username="$line"
    fi
  done