我一直在寻找一种简单的方法来组合各种脚本来执行此操作。我不是最擅长编写脚本,但我正在努力改进,所以对我要轻松一些。如有任何帮助,我们将不胜感激。
我不是本文的作者,但我将其作为一个开始。我想了解针对 ip 列表运行此操作的最佳方法是什么。我最感兴趣的是简单性和理解用户是否已经存在以及是否出错。
#!/bin/bash
# Script to add a user to Linux system
if [ $(id -u) -eq 0 ]; then
read -p "Enter username : " username
read -s -p "Enter password : " password
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ]; then
echo "$username exists!"
exit 1
else
pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
useradd -m -p $pass $username
[ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
fi
else
echo "Only root may add a user to the system"
exit 2
fi
答案1
答案2
这是我刚刚创建的一个脚本,用于演示如何执行此操作。
#!/usr/bin/env bash
warn()
{
printf '%s\n' "$@" >&2
}
die()
{
local st="$?"
warn "$@"
exit "$st"
}
anotherUser() {
read -p "Add another user [y/n] " yn
if [[ $yn = *[yY]* ]]; then
checkUser
fi
exit
}
checkUser() {
while :
do
read -p "Enter user: " userName
if id $userName 2>/dev/null
then echo "User exists"
anotherUser
else
read -p 'Enter pass: ' passWord
adduser "$userName"
echo "$passWord" | passwd "$userName" --stdin
printf "User %s has been added\n" "$userName"
exit
fi
done
}
if (( EUID == 0 )); then
checkUser
else
die "You must be root"
fi
确保将脚本复制到远程服务器上并按如下方式执行
ssh -t root@remoteserver 'bash accountScript'