Created
April 10, 2022 11:43
-
-
Save woolpeeker/86fe9dc768e9902fbcce7fbe42d7dcc1 to your computer and use it in GitHub Desktop.
create users with keys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Usage: | |
# bash create_users.sh users.txt | |
# each line in users.txt is a username | |
# | |
# Requires: | |
# apt install pwgen | |
user_exists(){ id $1 &>/dev/null; } | |
has_pwgen=`which pwgen` | |
if [ -z $has_pwgen ] | |
then | |
echo "install pwgen firstly: apt install pwgen" | |
exit -1 | |
fi | |
if [ -d keys ] | |
then | |
echo "keys dir exists, you must del it" | |
exit -1 | |
fi | |
mkdir keys | |
for name in `cat $1` | |
do | |
echo "===========================================================" | |
echo "creating user $name ... " | |
if user_exists $name | |
then | |
echo "user $name exists, skip it ...." | |
echo "" | |
echo "" | |
continue | |
fi | |
adduser --disabled-password --gecos "" $name | |
# generate key | |
phrase=`pwgen 16 1` | |
echo "passphrase: $phrase" | |
ssh-keygen -b 2048 -t rsa -N $phrase -f ./keys/id_rsa_$name | |
cp ./keys/id_rsa_$name ./keys/id_rsa_$name.copy | |
cp ./keys/id_rsa_$name.pub ./keys/id_rsa_$name.pub.copy | |
# register key | |
mkdir /home/$name/.ssh | |
mv ./keys/id_rsa_$name /home/$name/.ssh/id_rsa | |
mv ./keys/id_rsa_${name}.pub /home/$name/.ssh/id_rsa.pub | |
cat /home/$name/.ssh/id_rsa.pub > /home/$name/.ssh/authorized_keys | |
chown -R $name:$name /home/$name/.ssh/ | |
chmod 700 /home/$name/.ssh | |
chmod 600 /home/$name/.ssh/authorized_keys | |
echo "$name $phrase" >> keys/passphrase | |
echo "" | |
echo "" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment