How to add a linux user with a random or invalid password from a script
Solution 1:
If you do not specify a password to useradd
it won't get set (and the user will thus not be able to log in via password). Note that useradd
and adduser
are two different commands.
The following should create the new user with its own group, create it's home directory (at the default location, as we do not specify any location) and copy skeleton files.
useradd --create-home <user>
Then you just create the directory .ssh
in its home directory, chmod
it to 0700
(SSH will want this for security), and put the users public key in .ssh/authorized_keys
(the private/public key pair should be generated by the user him-/herself, on his/her own computer).
If you want to disable the password of an already existing account you can use the following.
usermod --lock <user>
Solution 2:
Utility /usr/sbin/useradd always created users for me without requiring passwords. I've written many a script that took another system's /etc/passwd and created users for me.
Alternatively, if you look at the documentation for mercurial-server, you'll see how to set up many SSH keys (clients) to run programs as just one user on the server side.
Solution 3:
# cat user-pw_list
john:p455W0rD
geany:p455W0rD
# cat CreateUsers.sh
#!/bin/bash
#
# filename: CreateUsers.sh
# usage: cat "User:passwd" | $0
#
set -e
# set -x
while read ; do
USER=${REPLY%%:*}
PWD=${REPLY##*:}
# alternative for random passwd, where $RANDOM is a bash function
#PWD=${REPLY%%:*}$RANDOM$RANDOM
echo -e "adding User $USER "
# for disabled users: /usr/sbin/nologin, otherwise /bin/bash
/usr/sbin/useradd -c automaticUser -m -k/dev/null -s /usr/sbin/nologin $USER
echo "$USER:$PWD" | chpasswd --md5 $USER
## also add user to samba:
#echo -e "$PWD\n$PWD" | pdbedit -t -u $USER
done
Ok, lets add our users:
cat user-pw_list | ./CreateUsers.sh
Solution 4:
If you want just builtin commands for generating random passwords, you can try this:
dd if=/dev/urandom bs=16 count=1 2>/dev/null | uuencode - | head -n 2 | grep -v begin | cut -b 2-10
This will read 16 bytes of random data, uuencode them to convert them to printable characters, cut through the uuencode extra output, then only take the random characters from the encoding. Here is an example output:
$ dd if=/dev/urandom bs=16 count=1 2>/dev/null | uuencode - | head -n 2 | grep -v begin | cut -b 2-10
RJ<B6QYRO