I want to add a user to Red Hat Linux that will not use a password for logging in, but instead use a public key for ssh. This would be on the command line.
Start with creating a user:
useradd -m -d /home/username -s /bin/bash username
Create a key pair from the client which you will use to
ssh-keygen -t rsa
Copy the public key
/home/username/.ssh/id_rsa.pub onto the RedHat host into
Set correct permissions on the files on the RedHat host:
chown -R username:username /home/username/.ssh
chmod 700 /home/username/.ssh
chmod 600 /home/username/.ssh/authorized_keys
Ensure that Public Key authentication is enabled on the RedHat host:
grep PubkeyAuthentication /etc/ssh/sshd_config
If not, change that directive to yes and restart the
sshd service on the RedHat host.
From the client start an
It should automatically look for the key
~/.ssh/. You can also specify an identity file using:
ssh -i ~/.ssh/id_rsa username@redhathost
You could use:
usermod --lock <username>
From the man page:
Lock a user's password. This puts a '!' in front of the encrypted password, effectively disabling the password. You can't use this option with -p or -U. Note: if you wish to lock the account (not only access with a password), you should also set the EXPIRE_DATE to 1.
Complete script (
<SSH_PUB_KEY> is in format of
sudo adduser --disabled-password "$NEW_USER"
sudo -i -u "$NEW_USER"
# now you are under the new user's shell
mkdir -p .ssh
chmod 0700 .ssh
echo "<SSH_PUB_KEY>" > .ssh/authorized_keys
chmod 600 .ssh/authorized_keys
I was looking for a script that I can fearlessly run creating a new user with proper SSH permissions, so if you do too, I believe this should help you :)