I have an a SSH server where root login is disabled. I'm hoping to run a privileged command that will want input from a file I have after being executed. I'm hoping to do all without user interaction via a oneliner command or a script

There is key auth setup, so the below password is requested only for running the command.

The closest I have gotten is this echo "mypass" |ssh -tt user@ip "sudo specialCommand"

The output will look like

[sudo] password for user: 
specialCommand requests inputfile contents

mypass is printed before and also accepted for the password prompt

I have the file commandInput which I'm trying to pipe in after the password is accepted

I've failed with various attempts that were really just a guessing game, how can I achieve this?


If your specialCommand does not really require a tty, and you forced ssh to make one only for sudo password prompting, then another alternative is:

(echo "mypass" ; cat commandInput) | ssh user@ip "sudo -Sp '' specialCommand"

Option -S of sudo makes it read the password from stdin, which is coming from your echo "mypass" in this case, while option -p '' ensures no password prompt is displayed either.

Then you might want to put your password in a file alone, protected by proper permissions. This is usually better practice than to hardwire your password in a script. The command would then become:

cat passwordFile commandInput | ssh user@ip "sudo -Sp '' specialCommand"

In this latter case, make sure the password file is exactly one line with the password alone and nothing else, otherwise what comes after the password line will pollute the input for your specialCommand.

| improve this answer | |

How about:

(echo "mypass"; cat commandInput) | ssh -tt user@ip "sudo specialCommand"

Or, since you apparently have sudo access to the remote host, how about using visudo there to add this line to the very end of /etc/sudoers (after the existing line that grants the passworded sudo access to user)?

user  ALL=(root) NOPASSWD: /full/path/of/specialCommand

This line grants user user (and nobody else) the permission to run specialCommand (and nothing else) as root without a password request. Trying to execute any other commands through sudo will still require a password as usual.

After this, you should be able to do simply:

ssh -tt user@ip "sudo specialCommand" < commandInput
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.