How to rename currently operating Linux user

David Obdržálek
2 min readJul 14, 2019

--

You can easily run into this with almost any VPS provider. You set up a new instance and login with a generic username and a certificate.

But you don’t want to be ubuntu, because you’re dave and your UID=1000 😉

Photo by Brad Neathery for Right Brain Factory, edit ΔO

How to rename yourself

The Hot Wire Way

Just modify the data in /etc/passwd, /etc/shadow and /etc/group. Then move your homedir and make your sudo passwordless.

Warning, this is dangerous. If you mess up, you’ll lose your access!

If you’ll careless enough, simply run this script

bash <(curl -s "https://tools.deltazero.cz/server/user.rename.sh")

Or run this by yourself

# your new username
newuser=dave
# root-run these all at once
sudo su -c "\
sed -i s/$USER/$newuser/g /etc/group \
&& sed -i s/$USER/$newuser/g /etc/shadow \
&& sed -i s/$USER/$newuser/g /etc/passwd \
&& mv /home/$USER/ /home/$newuser \
&& echo \"$newuser ALL=(ALL) NOPASSWD:ALL\" > /etc/sudoers.d/$newuser"
# exit & reconnect under new username

Also, you should add your local~/.ssh/id_rsa.pub to your remote ~/.ssh/authorized_keys. If you dont have one, run ssh-keygen -t rsa on your local machine.

If you use the same username as on your local machine, this saves you from ssh -i ~/top_secret/my_secret_certificate.pem ubuntu@my.server.com
to just ssh my.server.com 😌

The Correct Way

You shouldn’t rename yourself while connected, for many obvious reasons. Rather, you should

  1. Make a new user for yourslef
    adduser temp
  2. Copy your ssh keys to new user
    sudo mkdir ~temp/.ssh
    sudo chown temp:temp ~dave/.ssh
    sudo cp ~/.ssh/authorized_keys ~temp/.ssh
    or copy your local ~/.ssh/id_rsa.pub
  3. Exit & reconnect as new user ssh temp@...
  4. Kill all processes of the old user sudo pkill -u ubuntu
  5. Rename the old user, old group & move home dir
    sudo usermod -l dave -d /home/dave -m ubuntu
    sudo groupmod -n dave ubuntu
  6. Exit & reconnect as dave
  7. Kill all processes of the temp user sudo pkill -u temp
  8. Remove the temp user
    sudo userdel temp
    sudo rm -r /home/temp
  9. Live shorter

More time savers for Linux servers

See my tools for 5-min Debian / Ubuntu server deployment:
https://github.com/deltazero-cz/linux-tools/tree/master/server

What do you think of scripts like these? Let me know in the comments 🙂

--

--