Search code examples
linuxbashsshsudo

Running sudo scripts/bash commands on a remote


I need to remotely start bash scripts that perform sudo tasks, such as chmod and ntpdate and echoing to gpio.

A cron job might be the best solution for some of this, but cron is giving me headaches. I'd like to pass on this venue if I can...

I've confirmed that my scripts work locally (I can ssh into the machine and run them without a hiccup.)

However, If I try to run them remotely like so: (this is within a C++ system call)

ssh user@pc 'bash -s' < /home/user/myScript.sh

Commands with sudo fail.

sudo chmod fails with: no tty present and no askpass program specified echo to gpio fails with: write error: Device or resource busy sudo ntpdate fails with: no tty present and no askpass program specified

Can anyone help explain, or help me determine whats happening here?

I'm open to band-aids and different approaches, thanks!


Solution

  • You already found the problem yourself:

    sudo chmod fails with: no tty present and no askpass program specified

    If you run you shell script via ssh and the script wants to run the command sudo, sudo itself will ask for the users password. But the ssh session is not a tty! How should sudo now prompt for a password and how to get your password?

    You can do it if you provide the password in the script ( what makes it very dangerous if someone else can read that script! )

    script.sh:

    echo "your passwd" | sudo -S

    As alternative solution you can run the ssh session with a more privileged user.

    ssh privileged_user@pc 'bash -s' < /home/user/myScript.sh

    All that comes with some danger. Running all commands from the cript with a more privileged user can also be dangerous!