1

I have a script that does various things, and among those things, it prompts the user for a password, stores it in the $password parameter and the executes this command:

ssh [host] 'cd someDir; echo "$password" | sudo -u nobody -S <command>'

The problem is that I get the error Sorry, try again and then the connection gets killed.

How can I execute a sudo command using ssh? It works if I first connect to the remote host and then run echo 'password_string' | sudo -u nobody -S <command>

2

You should try debugging/troubleshooting.  Change your current ssh command to

ssh host 'cd someDir; echo "The password is $password"'

You’ll get

The password is 
Now try
echo host 'cd someDir; echo "The password is $password"'
You’ll get

host cd someDir; echo "The password is $password"

On your ssh command, you’ve got $password surrounded by double quotes, and surrounded by single quotes around that.  Well, that turns the double quotes into plain, ordinary characters — no more syntactically significant than if you’d typed LDQ and RDQ — so $password is effectively wrapped in single quotes.  So $password gets sent to the remote host, and not the value of $password (i.e., the actual password).  Then the shell on the remote host tries to expand $password to a value, and it gets nothing, because that variable has not been set in that shell.

A command that might work is

ssh host 'cd someDir; echo "'"$password"'" | sudo -u nobody -S command'

Let’s examine that, adding spaces for illustration/clarity:

            … '…; echo "'    "$password"    '" | sudo …'

This still has the double quotes inside single quotes.  But, after specifying the literal double quote (after echo), it breaks out of the single quotes, so variable expansion/replacement can occur on the local command.  Then we have $password in double quotes.  Then we go back into single quotes for the second literal double quote, the vertical bar (|), and the sudo command.

Caveat: I don't currently have access to a host I can ssh into, so I haven’t completely tested this.

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.