【问题标题】:Shell script to create linux users where username and password are read from a config file用于创建从配置文件中读取用户名和密码的 linux 用户的 Shell 脚本
【发布时间】:2016-05-19 20:01:08
【问题描述】:

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

我的配置文件包含 (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”个用户。

提前致谢。

【问题讨论】:

    标签: bash login configuration-files


    【解决方案1】:

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

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

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

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

    tempuser
    passXXX
    newuser
    ppwdXXX
    lastuser
    pass...
    

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

    username
    password
    username
    password
    ...
    

    这可以在while循环中使用:

    sed -n -e 's/\(password\|username\)="\(.*\)"/\2/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
    

    【讨论】:

    • ,我想改进脚本,以便在创建用户时我也可以通过组。我将使用 useradd -m -p $pass $username -g $usergroup -s /bin/bash 。我的配置文件 guest.cfg 也将包含用户组信息。即 usergroup=guest 以及以前存在的用户名和密码列表。当我尝试您建议的“sed”命令时,while 循环不起作用。你能提供一个解决方案吗
    • ,我想改进脚本,以便在创建用户时我也可以通过组。我将使用 useradd -m -p $pass $username -g $usergroup -s /bin/bash 。我的配置文件 guest.cfg 也将包含用户组信息。即 usergroup=guest 以及以前存在的用户名和密码列表。当我尝试您建议的“sed”命令时,while 循环不起作用。你能提供一个解决方案吗?
    猜你喜欢
    • 1970-01-01
    • 2014-07-18
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多