How to use SSH to run a shell script on a remote machine?

5,122

Solution 1

This can occur when Defaults requiretty is uncommented in /etc/sudoers.

The fix is to comment that line:

#Defaults    requiretty

Remember to only edit /etc/sudoers using the visudo** command.

**The visudo command may only be run by the root user.

Solution 2

You can try this as well:

ssh -t user@remoteip <<'EOF'
command1
command2
command3
EOF

Although it would probably be best to save the script with the commands you want on the remote machine and just call it once you log in.

Share:
5,122

Related videos on Youtube

BDN
Author by

BDN

Sysadmin

Updated on September 18, 2022

Comments

  • BDN
    BDN almost 2 years

    I'd like to execute some sudo privilege commands using bash script from local to remote server via ssh without passing multiple commands separating from semicolons on ssh. I've tried below step but got error.

    ssh -t user@remoteip 'bash -s' < services.sh
    

    Though I've used -t option here it still shows error message.

    sudo: sorry, you must have a tty to run sudo
    
    • AlexP
      AlexP almost 7 years
      The missing tty can easily be allocated with ssh -t. The basic problems are (1) that you are not running a script, you are sourcing it, which is very different sometimes, and (2) sudo will want to authenticate you, but your input is redirected to the script.
    • Deathgrip
      Deathgrip almost 7 years
      Learn Ansible - ansible.com and you'll be happy you did.
    • Dalvenjia
      Dalvenjia almost 7 years
      Use ssh -tt to force the tty allocation, but make sure that sudo will not ask for a password, if sudo ask for a password it will return control to the tty for password input and will fail there. If you can not set sudo without password your only option besides ansible or similar is to use expect and have your password in clear text which is not good at all.
    • BDN
      BDN almost 7 years
      I'm still stuck on sudo: sorry, you must have a tty to run sudo error though I followed your step @MelBurslan
  • BDN
    BDN almost 7 years
    It will not be possible to change sudoers file in every server manually. Is there any alternative solution for that ?
  • BDN
    BDN almost 7 years
    I also wanted to call the script full of commands but still stuck on the error.