此脚本旨在实现以图形界面让用户得以添加新用户,具体要求如下:
用户名:
UID:需要默认ID,为passwd文件中最后一个(nobody外)ID号加1
全名
家目录:显示/home/,如果用户没再补充,要求其家目录为/home/用户名
shell类型:默认显示/bin/bash
再显示一个窗体,提示用户输入密码,但有默认信息(同用户名)
运行结果如下:
选择 OK ,进入添加密码界面 :
如果第二步选择 Cancle,则提示:
源码如下:
1 #!/bin/bash
2 # Author: Vivid
3 # Date & Time: 2010-12-26 19:57:10
4 # Description:
5
6 let NUID=$[`cut -d: -f3 /etc/passwd | grep -v "65534" | sort -n | tail -1`+1]
7 let GID=$[`cut -d: -f3 /etc/group | grep -v "65534" | sort -n | tail -1`+1]
8 let TODAY=$[`date +"%s"`/86400]
9
10
11 dialog --stdout --title "user infomation" --form "pIlease input userinfo:" 18 36 6 "UserName" 1 1 "E-guy" 1 13 13 0 "UID" 2 1 "$NUID" 2 13 13 0 " FullName" 3 1 "E-guy" 3 13 13 0 "Home" 4 1 "/home" 4 13 13 0 "Shell" 5 1 "/bin/bash" 5 13 13 0 > userinfo.out
12
13
14 USERNAME=`head -1 userinfo.out`
15 NUID=`head -2 userinfo.out | tail -1`
16 HOME=`head -4 userinfo.out | tail -1`
17 SHELL=`head -5 userinfo.out | tail -1`
18
19
20 if [ -z $USERNAME]; then
21 dialog --title "Tips" --msgbox "Field to add user !" 7 30
22 exit 1
23 else
24 PASSWORD=`dialog --stdout --insecure --passwordbox "PassWord" 7 30 $USERNAME`
25 if ! cut -d : -f1 /etc/passwd | grep "$USERNAME" &> /dev/null ; then
26 echo "$USERNAME:x:$NUID:$GID::"$HOME/$USERNAME":$SHELL " >> /etc/passwd
27 echo "$USERNAME:x:$GID:" >> /etc/group
28 echo "$USERNAME:!!:$TODAY:0:99999:7:::" >> /etc/shadow
29 else
30 echo "The user $USERNAME exist."
31 exit 1
32 fi
33
34
35 cp -r /etc/skel "$HOME/$USERNAME"
36 chown -R "$USERNAME":"$USERNAME" "$HOME/$USERNAME"
37 chmod -R go=--- "$HOME/$USERNAME"
38
39 echo $PASSWORD | passwd $USERNAME
40
41 dialog --title "Tips" --msgbox "$USERNAME is added !" 7 30
42
47 rm -f userinfo.out
48
49 fi
50
问题:其实这个作业只是实现在图形化,并没有很完美的实现添加用户。我的疑惑也在这里。运行完程序之后,etc文件下的passwd,group,shadow三个文件中都出现了对应的用户信息,但是当以root身份使用su命令转换用户时,就出现su: /bin/bash : Permission denied ,导致无法切换用户,不知道是不是和grub出问题有关
总结:在编写过程中,经常出一些意想不到的小错误,很多是变量使用过程中遇到的。在使用变量的过程中经常会用C++的思想去引用这些量,尤其是在做条件比较的过中,经常出错,然后就要花大量的时间去排错,这个过程 很痛苦也很费时间,所以今后要在语法细节上多注意一下,总结出来,方便以后使用!
转载于:https://blog.51cto.com/eguys/469230