Command line Parameters in bash shell script in ne

2019-02-26 12:40发布

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

标签: bash shell ssh
2条回答
该账号已被封号
2楼-- · 2019-02-26 13:23

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
查看更多
女痞
3楼-- · 2019-02-26 13:37

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).

查看更多
登录 后发表回答