玖叶教程网

前端编程开发入门

RHCE试题EX300详解(二十)创建一个添加用户的脚本

题目要求:创建一个添加用户的脚本

在 server0 上创建一个脚本,名为 /root/batchusers,此脚本能实现为系统 server0 创建本地用户,并且这些用户的用户名来自一个包含用户名列表的文件。同时满足下列要求:

  • l 此脚本要求提供一个参数,此参数就是包含用户名列表的文件
  • l 如果没有提供参数,此脚本应该给出下面的提示信息 Usage: /root/batchusers userfile 然后退出并返回相应的值
  • l 如果提供一个不存在的文件名,此脚本应该给出下面的提示信息 Input file not found 然后退出并返回相应的值
  • l 创建的用户登录 shell 为 /bin/false
  • l 此脚本不需要为用户设置密码
  • l 你可以从下面的 URL 获取用户名列表作为测试用 http://classroom.example.com/content/newusers

知识点小贴士:

Shell的基本语法:

(1)注释

Shell中的注释标志是井号 "#",除了脚本文件第一行的#不是注释之外,其他地方出现#,则说明#开始,到本行的末尾都是注释。

(2)指定脚本解释器

一般每个Shell脚本文件的第一行都是指定脚本解释器;

#!/bin/bash : 指定本脚本文件使用bash脚本解释器解释执行。

解题步骤:

(1)下载文件:

[root@server0 ~]# wget http://classroom.example.com/content/newusers
--2020-03-26 13:39:20--  http://classroom.example.com/content/newusers
Resolving classroom.example.com (classroom.example.com)... 172.25.254.254
Connecting to classroom.example.com (classroom.example.com)|172.25.254.254|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 349
Saving to: ‘newusers’
100%[=====================>] 349         --.-K/s   in 0s     
2020-03-26 13:39:20 (27.3 MB/s) - ‘newusers’ saved [349/349]

(2)遍历文件内容:

[root@server0 ~]# tail newusers
Willow
Reiko
Ismael
Iris
Tarah
Jong
Emelda
Wilford
Cassy
Trent

(3)编辑脚本文件:

[root@server0 ~]# vim /etc/bashrc



[root@server0 ~]# vim /root/batchusers



注释,脚本内容如下:

#!/bin/bash
if [ $# -eq 0 ]; then
  echo "Usage: /root/batchusers userfile "
  exit 100
elif [ ! -f $1 ]; then
  echo "Input file not found"
  exit 200
else
  for i in $(cat $1); do
    useradd -s /bin/false $i
  done
fi

(4)设置文件权限:

[root@server0 ~]# chmod a+x /root/batchusers

(5)测试验证:

[root@server0 ~]# /root/batchusers
Usage: /root/batchusers userfile
[root@server0 ~]# /root/batchusers a
Input file not found
[root@server0 ~]# /root/batchusers newusers
t[root@server0 ~]# tail -n 1 newusers;
Trent
[root@server0 ~]# tail -n 1 /etc/passwd
Trent:x:1053:1053::/home/Trent:/bin/false

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言