How to rename currently operating Linux user
--
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
😉
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
- Make a new user for yourslef
adduser temp
- Copy your ssh keys to new user
sudo mkdir ~temp/.ssh
or copy your local
sudo chown temp:temp ~dave/.ssh
sudo cp ~/.ssh/authorized_keys ~temp/.ssh~/.ssh/id_rsa.pub
- Exit & reconnect as new user
ssh temp@...
- Kill all processes of the old user
sudo pkill -u ubuntu
- Rename the old user, old group & move home dir
sudo usermod -l dave -d /home/dave -m ubuntu
sudo groupmod -n dave ubuntu - Exit & reconnect as
dave
- Kill all processes of the temp user
sudo pkill -u temp
- Remove the temp user
sudo userdel temp
sudo rm -r /home/temp - 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 🙂