3-commerce
3-commerce

Reputation: 159

Passing a quoted string to ssh

So, i want to run this command in terminal

pssh -h hosts -i "echo "DenyUsers $1" >> /etc/ssh/sshd_config && service sshd config"

as you can see, " before echo words will be broken and it will be ended by " before DenyUsers $1 command. I have changed " before echo and after config words and it doesn't still work like what i want.

I am newcomer in this scripting and i don't know what keywords should i put into the search engine :-)

Upvotes: 1

Views: 929

Answers (3)

jfMR
jfMR

Reputation: 24738

If the source of $1 can be trusted, then you can simply escape the inner double quotes with \:

pssh -h hosts -i "echo \"DenyUsers $1\" >> /etc/ssh/sshd_config && service sshd config"

The drawback to the approach above is what happens if the $1 expands to something malicious, for example, to $(rm -fr *). Then, /etc/ssh/sshd_config will end up containing:

echo "DenyUsers $(rm -fr *)"

which will run rm -fr * when executed.

For this reason, consider this answer for a safer solution based on printf %q.

Upvotes: 1

Charles Duffy
Charles Duffy

Reputation: 295373

Doing this in a manner that is safe even if you don't trust your input is a bit more involved.

Use printf %q to generate an eval-safe version of your data:

#!/usr/bin/env bash
#              ^^^^- Requires an extension not available in /bin/sh

# printf %q is also available on ksh, but there you would write:
#   echo_str=$(printf 'DenyUsers %q' "$1")
#   cmd=$(printf '%q ' printf '%s\n' "$echo_str")
# as the ksh version doesn't have -v, but optimizes away the subshell instead.

printf -v echo_str 'DenyUsers %q' "$1"
printf -v cmd '%q ' printf '%s\n' "$echo_str"
pssh -h hosts -i "$cmd >> /etc/ssh/sshd_config && service sshd config"

Note that printf is used instead of echo for greater predictability; see the APPLICATION USAGE section of the POSIX specification for echo.

Upvotes: 6

rkrankus
rkrankus

Reputation: 99

Did you try
pssh -h hosts -i "echo \"DenyUsers $1\" >> /etc/ssh/sshd_config && service sshd config" or
pssh -h hosts -i 'echo "DenyUsers $1" >> /etc/ssh/sshd_config && service sshd config'

Upvotes: 1

Related Questions