How do I become root on a remote server until I am disconnected from that server?

Nosscire asked:

So far I have this:

sshpass -p "password" ssh -q username@ " [ "$(whoami)" != "root" ] && exec sudo -- "$0" "$@" ; whoami ; [run some commands as root]"

I keeps giving me username as answer from whoami. I want to be root as soon as I am connected to the server (but I can only connect to it with username). How can I be root throughout the connection to the server?


I want to access a remote server. It is mandatory that I connect as “username” and then switch to root to run and copy files that only root is able to do. So while I am connected to that server via ssh, I want to be root until my commands are over in the remote server. My problem is that I am not able to do so because I don’t have the knowledge, hence I am posting it here.


  • can’t use rsync.

  • have to connect to the server as “username” and then switch to root

  • this code is in a for loop so I don’t want to use su because it will keep asking for a password

My answer:

Use sudo -i for an interactive root shell.

Use sudo command or sudo -i command to run a command as root. The -i option sets up a shell and environment before running the command.

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.