Reputation: 707
I am trying to use $1, $2 variables which I have passed through command line to a bash shell script. These variables I am using within a ssh call. But its seems the variables within ssh are not getting replaced, the outer ones are getting replaced. Any workaround? Here's the code
#!/bin/bash
ssh -t "StrictHostKeyChecking=no" -i $1 user@ip<<'EOF1'
ssh -t -i $1 user2@ip2 <<'EOF2'
exit
EOF2
exit
EOF1
Here the first $1 gets replaced but the second one doesn't. Its basically key name for password less authentication
Upvotes: 3
Views: 1895
Reputation: 531075
Much simpler is to let ssh
handle the tunneling for you.
ssh -o ProxyCommand="ssh user1@ip1 nc -w 10 %h %p" user2@ip2
(This example found at http://undeadly.org/cgi?action=article&sid=20070925181947).
Upvotes: 1
Reputation: 295373
Use printf %q
to generate an eval
-safe string version of your argument list:
# generate a string which evals to list of command-line parameters
printf -v cmd_str '%q ' "$@"
# pass that list of parameters on the remote shell's command line
ssh "$host" "bash -s $cmd_str" <<'EOF'
echo "This is running on the remote host."
echo "Got arguments:"
printf '- %q\n' "$@"
EOF
For what you're really doing, the best practice is probably to use a ProxyCommand -- see the relevant documentation -- and to have your private key exposed via agent forwarding, rather than having it sitting on your bounce host on-disk. That said, it's straightforward enough to adopt the answer given above to fit the code in the question:
#!/bin/bash
printf -v args '%q ' "$@"
echo "Arguments on original host are:"
printf '- %q\n' "$@"
ssh -t "StrictHostKeyChecking=no" -i "$1" user@ip "bash -s $args" <<'EOF1'
printf -v args '%q ' "$@"
echo "Arguments on ip1 are:"
printf '- %q\n' "$@"
ssh -t -i "$1" user2@ip2 "bash -s $args" <<'EOF2'
echo "Arguments on ip2 are:"
printf '- %q\n' "$@"
EOF2
EOF1
Upvotes: 6