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
  • 1
    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.
    – AlexP
    Jul 7, 2017 at 20:41
  • Learn Ansible - ansible.com and you'll be happy you did.
    – Deathgrip
    Jul 7, 2017 at 21:16
  • 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.
    – Dalvenjia
    Jul 7, 2017 at 21:30
  • assuming your sudo commands are allowed for your username, under which you will run them and have a NOPASSWORD directive with them, my suggestion is not to run them from a local script with a redirect, like you did in the question, but write them to a file, copy the file to the remote server using scp and run them as ssh remote-machine-name /bin/bash -x /path/to/copied/script/file
    – MelBurslan
    Jul 7, 2017 at 22:14
  • I'm still stuck on sudo: sorry, you must have a tty to run sudo error though I followed your step @MelBurslan
    – BDN
    Jul 8, 2017 at 3:58

2 Answers 2


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.

  • It will not be possible to change sudoers file in every server manually. Is there any alternative solution for that ?
    – BDN
    Jul 8, 2017 at 3:43

You can try this as well:

ssh -t user@remoteip <<'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.

  • I also wanted to call the script full of commands but still stuck on the error.
    – BDN
    Jul 8, 2017 at 4:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .