bashsshsudoheredocjust

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


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.


Solution

  • 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