Bash – SSH, Sudo, and Su into Login Shell

bashsshsudo

I have several machines I ssh into regularly only for the purpose of using sudo su to spend the rest of my session logged in as some special-purpose user. The general workflow is:

mymachine:~ me$ ssh me@othermachine
othermachine:~ me$ sudo su - specialuser # note: no password needed
othermachine:~ specialuser$ # do stuff

I'd like to boil this down into a one-liner that I can alias, so I can just set up an alias for each machine and get to where I need to be in a single command, without having to type the sudo su - specialuser boilerplate. I could maybe set up me@othermachine to sudo su on login, but I'd like to keep the flexibility to operate as me if I need to.

(Note: I don't have any control over othermachine or the way it's set up; this is an established workflow that I came in on when I was hired.)

My first thought was just

ssh me@othermachine "sudo su - specialuser"

and this sort of works, but it gets me no prompt, ^C kills it and logs me out, and I assume various other things are probably wrong too.

After reading Run Remote ssh command with Full Login Shell I tried a couple of more exotic things like

ssh me@othermachine 'bash -l -c "sudo su - specialuser"'

and

ssh me@othermachine 'bash -l -c "sudo su - specialuser"; bash'

— neither of which I expected to work, and they didn't, but I thought I should try them for completeness (and to avoid close-as-duplicate); they produced the same prompt-less shell (the second with an added bonus prompt-less shell for me after exit-ing from the one for specialuser). And I tried

ssh me@othermachine "sudo su - specialuser -c bash -l"

but it just got me

sudo: no tty present and no askpass program specified

Better ideas?

Best Answer

This line should works for you

ssh -t me@machine "sudo su - specialuser" 

This solution give me a prompt or not depending on -t switch

ssh -t me@machine "/bin/bash -l"   # Give me a prompt

ssh  me@machine "/bin/bash -l"     # Give me NO prompt
ssh  me@machine                    # Give me NO prompt

Notes from man ssh

-t
Force pseudo-tty allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty.

Related Question