Execute commands as different user via sudo over SSH in a justfile

850 Views Asked by At

I have this justfile:

remote:
    #!/usr/bin/env bash
    read -p 'Password:' -s password
    ssh -tt somewhere 'bash -l -s' << 'ENDSSH'
    whoami
    echo "$password" | sudo su someone 'bash -l -s' << 'ENDSUDO'
    whoami
    ENDSUDO
    ENDSSH

It should:

  • Ask me for a password
  • SSH into somewhere
  • sudo to change the user
  • execute some scripts

What it does:

It asks for a password a second time. It stucks on input (no error message).

How to solve this problem?

Update

As suggested by @xhienne, this does almost work, but it says, I use the wrong password:

remote:
    #!/usr/bin/env bash
    read -p 'Password:' -s password
    ssh -tt somewhere 'bash -l -s' << 'ENDSSH'
    sudo -S -i -u someone << ENDSUDO
    $password
    whoami
    ENDSUDO
    exit
    ENDSSH

But this does work:

remote:
    #!/usr/bin/env bash
    read -p 'Password:' -s password
    ssh -tt somewhere 'bash -l -s' << 'ENDSSH'
    sudo -S -i -u someone << ENDSUDO
    clear-text-password
    whoami
    ENDSUDO
    exit
    ENDSSH

Update 2

The answer of @xhienne does work.

2

There are 2 best solutions below

8
xhienne On BEST ANSWER

With

echo "$password" | sudo su someone 'bash -l -s' << 'ENDSUDO'
    whoami
ENDSUDO

You are redirecting stdin twice:

  • once with |
  • a second time with <<

Try this:

sudo -S -i -u someone << ENDSUDO
$password
whoami
ENDSUDO

sudo -S will read the password from stdin. sudo -i is a substitute for the ugly sudo su bash -l (but it needs that sudo be properly configured for -u someone)

Note that I removed the quotes around ENDSUDO. Beware of inadvertent substitutions. If you must keep ENDSUDO quoted, then you can try this instead:

{
    echo "$password"
    cat << 'ENDSUDO'
whoami
ENDSUDO
} | sudo -S -i -u someone
1
Shane Bishop On

I believe the following will work, if you only want to run whoami instead of several commands:

#!/usr/bin/env bash
read -s -p 'Password: ' password
ssh somewhere whoami
echo "$password" | ssh somewhere sudo -S -u someone whoami

The -S tells sudo to read the password from stdin.

If you want to run several commands with a here-document, see @xhienne's answer.