How can I login to Ubuntu via ssh and automatically sudo su? [closed]

Refresh

April 2019

Views

2.5k time

1

From my Mac Terminal I can login via ssh to my various Ubuntu servers without entering a password. That's fine. But the work I do in Ubuntu requires me to have root access, so immediately after login I always execute sudo suwhich is an extra step and requires manually entering my password at that point.

What's a good way to avoid that extra step so I login with my user name as I do now, but immediately have the sudo su executed for me (or anything with an equivalent result)?

Thanks.

2 answers

3

What you are trying to do seems very insecure; essentially you are providing root privs to anyone who logs in as you. However, it can be done.

On the Ubuntu machine that you are ssh'ing into:

  1. Grant yourself passwordless sudo permissions. You can do this for all commands, or you can be a little more secure and define a specific command. First, launch the sudo configuration editor:

    $ sudo visudo

Then define what user you want to be able to run the su command without a password. I'll assume your username is doug (based on your stackoverflow handle), and that the server hostname is ubuntubox:

doug ubuntubox = (root) NOPASSWD: /bin/su

Now you should be able to execute this command without a password:

sudo su
  1. In order for that command to occur immediately upon login, add the command to the very top of your ~/.bash_profile. If you have no such file, create one:

    $ touch ~/.bash_profile $ echo "sudo su -" > ~/.bash_profile

  2. Log out of your ubuntu server, because bash_profile only gets sourced upon login.

  3. Log into your server. As soon as your shell opens, it should sudo su you into a root shell.

If ~/.bash_profile isn't getting sourced at login:

$ echo ". $HOME/.bash_profile" >> ~/.bashrc
1

Suggestion: if you're doing this, at least disable password login for SSH, and use keys instead. Otherwise, as others have already observed, your system is a single password away from being wide open. With keys, at least the attacker needs to filch your identity key first.

Securing SSH: in /etc/ssh/sshd_config, set the lines

PermitRootLogin         no
RSAAuthentication       yes
PubkeyAuthentication    yes
PasswordAuthentication  no

To automatically run sudo, you can put the command in your .loginrc or .bashrc file (or .profile if you're running other shells; Ubuntu also has dash in addition to bash. See this article).

# This is my .bashrc. There are many like it, but this is mine.

# You can also set some variables if you ever need them.
#export LC_ALL=en_US.utf-8
#export SVN_EDITOR=/usr/bin/vim
#export VISUAL=/usr/bin/vim

sudo su

Then to also remove the password from su, you need to run visudo on each server and add, say,

Cmnd_Alias  INSECURE_ROOTSHELL   = /bin/su

ubuntu      ALL=(ALL)   NOPASSWD: INSECURE_ROOTSHELL