创建用户及设置密码等,设置sudoers普通用户sudo权限

[root@source files]# grep -i root  /etc/sudoers
## the root user, without needing the root password.
## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL
aaa 192.168.8.101=(root) ALL
yy 192.168.8.101=(root) ALL
xx 192.168.8.101=(root) ALL
ff 192.168.8.101=(root) ALL
dd 192.168.8.101=(root) ALL
ee 192.168.8.101=(root) ALL
cc 192.168.8.101=(root) ALL
yidong ALL=(root) ALL
bb 192.168.8.101=(root) NOPASSWD:ALL
aa 192.168.8.101=(root) ALL
## cdrom as root
 
@@@@@@@@@@@@@@@@@@@@脚本内容如下:################
[root@source files]# cat users.sh
#!/bin/bash
ipaddress=$(ifconfig eth0 |awk '/\<inet\>/{print $2}')
##设定没有输入参数脚本退出
if [ $# -eq 0 ]
then
    echo "未输入任何参数!!"
    echo "$0:usage error"
    exit 1
elif  grep -q $1 /etc/passwd
then
      echo "$1已存在于用户配置文件/etc/passwd中,创建$1忽略!!"
      exit 3
else
   useradd $1
   echo $2 |passwd --stdin $1
fi
##设定sudoers配置文件
num=$(grep -c ^$1  /etc/sudoers)
if [ $num -ne 0 ]
then
   echo "该$1已在/etc/sudoers配置文件中,已配置忽略!!"
else
   
   sed -i '/^root/a '$1' '$ipaddress'=(root) ALL' /etc/sudoers
   sleep 3
   grep ^$1 /etc/sudoers && echo "$1配置成功" || echo "$1配置失败"
fi
@@@@@@@@@@@@@@@@@@@@@@@@@脚本内容结束####################
@@创建用户测试:
[root@source files]# id gg
id: gg: no such user
[root@source files]# sh users.sh gg 123456
Changing password for user gg.
passwd: all authentication tokens updated successfully.
gg 192.168.8.101=(root) ALL
gg配置成功
[root@source files]# grep -i gg /etc/sudoers
gg 192.168.8.101=(root) ALL
[root@source files]#

 标准写法:

#!/bin/bash
ipaddress=$(ifconfig eth0|awk '/\<inet\>/{print $2}')
num=$(grep -c ^$1 /etc/sudoers)
if [ $# -eq 0 ];then
echo "未输入参数,请退出!!"
exit 1
elif grep -q $1 /etc/passwd
then
echo "$1已存在于/etc/passwd配置文件中,用户创建忽略!!"
exit 2
else
useradd $1
echo $2 |passwd --stdin $1
fi
if [ $num -ne 0 ];then
echo "配置文件sudoers已经配置$1普通用户了,忽略!!"
exit 3
else
echo "添加$1普通用户开始"
sed -i '/^root/a '$1' '$ipaddress'=(root) NOPASSWD:ALL' /etc/sudoers
grep -q ^$1 /etc/sudoers && echo "$1添加成功" || echo "添加$1用户失败"
fi

 
 
 
 
 
posted @ 2023-12-06 17:18  往事已成昨天  阅读(39)  评论(0编辑  收藏  举报