您的位置:首页 > 运维架构 > Linux

Linux进取之旅1: 第一个脚本-检查及创建用户

2016-09-17 20:23 405 查看
Linux新手,欢迎指点!!

目标:当以一个用户名为参数执行该脚本时,首先检查该用户是否已存在于系统,如果存在则返回一个提示;如果不存在则等待用户确认是否创建该用户;yes则创建;no则脚本终止,同时返回该结果的退出码(exitcord)。

思路:1. 检查用户是否在,id 或 getent命令;2. 如果用户不存在,则等待用户确认是否创建该用户。意味着该脚本需要与用户交互。说说这样做的理由. 对于无论你接受与否的就安装软件或修改你系统的行为,绝大多数人都会反感。而且这种行为很流氓。所以这个脚本增加了确认,让执行该脚本的人,有自行选择的权利。简而言之,尊重。那怕只是尊重自己。与代码,与技术无关。3. 用户创建完成之后,如果没有设置密码则该用户不能正常登入系统。意味关该脚本需要再次与用户交互设置密码,且设置密码时,密码字符不会回显。于是有了第一个脚本,命名chk_user.sh. 请自动忽略行号!

1)#!/bin/bash 2) 3)#use to checking and adding user. 4)#If user has just existing on system 5)#print user status. otherwise, adding that user. 6)#usage: chk_user.sh <username>. 7) 8)if (getent passwd "$1") 9) then 10) echo "Look like user $1 has just existing on system" 11) exit 0 12) 13) else 14) echo "No such user $1 on system yet. Are your want to adding $1 now ?" 15) 16) cat << EOF 17) Please enter "y"or "n" to confirm: 18) EOF 19) read CONFIRM 20) 21) case "$CONFIRM"in 22) y) 23) useradd $1 24) echo"User $1 has added on system " 25) cat << EOF 26) Please enter $1's password: 27) EOF 28) read -s PASSWD 29) 30) echo $PASSWD | passwd --stdin $1> /dev/null 31) echo"Adding user $1 successful completed!" 32) exit 0 33) ;; 34) 35) n) 36) echo"Task terminated" 37) exit 1 38) ;; 39) 40) *) 41) echo 'Ithink, Your should always type the "y" or "n" to comfirm ' 42) exit 1 43) ;; 44) esac 45) fi
测试脚本:



bob不存在于当前系统,所以提示是否创建,好像工作正常.


当确认为no或确认非yes和no 时,脚本终止。好像也没什么意外。再来……

然而,事实总非如此!当没指定参数(即用户名)时,该脚本也能执行,这个,这个好像不是太合理……理想的结果是,当没有指定参数(用户名)时,脚本在执行时会给出一个提示,同时脚本终止运行。于是有了修改后的脚本, 命名chusr:#!/bin/bash # use to checking and adding user. # If user has just existing on system# print the user's status. otherwise, adding that user.# usage: chusr <username>. if[ -z $1 ] then echo "Hey, guys! Yourshould be enter a username !" exit 1 elif(getent passwd "$1") then echo "Look like user $1 has just existing" exit 0 else echo "No such user $1 on system yet. Are your want to adding $1 now ?" cat << EOFPlease enter "y" or "n" to confirm:EOFread CONFIRM case "$CONFIRM" in y) useradd $1 echo"User $1 has added on system "cat << EOFPlease enter $1's password:EOFread-s PASSWD echo $PASSWD | passwd --stdin $1> /dev/null echo"Good job! adding user $1 successfulcompleted !" exit 0 ;; n) echo"Task terminated" exit 1 ;; *) echo 'Ithink, Your should always type the "y" or "n" to confirm' exit 1 ;; esacfi

再次测试:









好像都在按预期的方式工作……不过觉得还有改进的地方;理想的状态是。当提示“I think, You shouldalways type the y or n to confirm" 之后,应该再次重复提示用户确认,而不是终止脚本。关于脚本文件的放置。在当前的用户的初始化文件中有一条PATH变量:PATH=$PATH:$HOME/bin ,即用户home目录下的子目录bin,而这个目录默认并不存在。所以,最简单的方法是在该目录下创建一个bin的子目录,将脚本文件放置在这个目录里,并赋予脚本文件可执行权限,就能像执行其他系统命令一样执行该脚本。关于权限我在初始化文件中创建了一条umask 077命令(只针对自己,对系统上的其他用户无交),当创建目录时默认权限为700),创建文件时默认权限为600,即总是个人专有。毕竟你不希望你的脚本文件任何人都可以修改及执行。而对于一个不可执行的文件,也没有理由赋予其可执行的权限。

2016-09-17
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Linux 脚本