最近需要用到Linux下脚本交互方式添加用户,自己整了三个脚本分享并记录一下,便于后续使用,同时也分享下,希望能帮到和我一样的Shell脚本菜鸟。
示例一:优雅方式添加用户
根据提示,输入你要添加的用户,如果用户存在,则提示后,退出脚本;#!/bin/sh
# This scripts is created by miaocbin
# QQ:289303323
# blog:http://miaocbin.blog.51cto.com
# 优雅方式添加用户:如果用户存在,则提示已存在,并退出,如果不存在就增加,并且设置密码;
echo -n "Please input your username:"
read username
grep "$username" /etc/passwd > /dev/null 2>&1
if [ $? -eq 0 ] ;
then
echo $username exist.
exit 0
else
echo $username is not exist.
echo "now create user $username"
/usr/sbin/useradd $username
echo -n "Please input your password:"
read password
echo “${password}123” |passwd --stdin $username
echo "User $username have been added,the password is ${password}123"
fi
示例二:优雅方式添加用户
与示例一类似,只是实现方式不同而已,由此可知,Linux中条条道路通罗马,各种实现方式需要不断研究,寻找合适自己的才是最好的。#!/bin/sh
# This scripts is created by miaocbin
# QQ:289303323
# blog:http://miaocbin.blog.51cto.com
#优雅方式添加用户
echo -n "Please input your username:"
read username
if cat /etc/passwd | awk -F : '{print $1}' | grep $username >/dev/null 2>&1
then
echo "User $username already exists"
else
/usr/sbin/useradd $username
echo -n "enter your password:"
read password
echo "${password}123" |passwd --stdin $username
echo "User $username have been added,the password is ${password}123"
fi
示例三:优雅方式添加用户(简单、推荐)#!/bin/sh
# This scripts is created by miaocbin
# QQ:289303323
# blog:http://miaocbin.blog.51cto.com
#优雅方式添加用户
echo -n "Please input your username:"
read username
id $username >/dev/null 2>&1
if [ $? -ne 0 ] ;
then
echo $username is not exist.
echo "now create user $username"
/usr/sbin/useradd $username
echo -n "Please input your password:"
read password
echo “${password}123” |passwd --stdin $username
echo "User $username have been added,the password is ${password}123"
else
echo $username exist.
exit 0
fi
示例四:暴力方式添加用户(慎用!)
先递归删除你输入的用户,然后重新添加,并设置密码,生产环境中请慎用此脚本,此脚本会递归删除用户及其相关的所有数据。#!/bin/sh
# This scripts is created by miaocbin
# QQ:289303323
# blog:http://miaocbin.blog.51cto.com
#暴力方式添加用户,如用户存在,怎删除后,重新添加
echo -n "Please input your username:"
read username
grep "$username" /etc/passwd > /dev/null 2>&1
if [ $? -eq 0 ] ;
then
echo $username exist.
echo "now delete the user $username and Readd the user $username"
/usr/sbin/userdel -r $username
/usr/sbin/useradd $username
echo -n "Please input your password:"
read password
echo “${password}123” |passwd --stdin $username
echo "User $username have been added,the password is ${password}123"
fi