Per*_*ity 3 ssh bash heredoc remote-access
我有一个脚本解析服务器列表,寻找一些东西并在情况正确时执行命令.主服务器通过ssh连接到它们,执行EOF语句中的所有命令:
#!/bin/bash
# parsing servers
# defining one local variable $VAR
ssh -T -p 1234 root@"server-ip" "$variable" << 'EOF'
# doing some stuff...
var_result=$(mysql -hhost -uuser '-ppasswort' -Ddatabase -N -e "SELECT something FROM somewhere WHERE value=$VAR;")
EOF
Run Code Online (Sandbox Code Playgroud)
我知道如果我从EOF中删除单引号,变量可以通过,但如果我这样做,mysql语句将无法工作,一切都会中断.
我知道有传递变量的方法,但有";"的东西 选项之间不适用于我(脚本尝试将其作为命令执行)
有任何想法吗?
用于printf %q以eval-safe形式转义内容; 这样做之后,你可以通过它们远程shell命令行上,并通过检索它们$1,$2等远程脚本中:
# put contents of $VAR into $var_str in a format that a shell can interpret
printf -v var_str %q "$VAR"
# v- pass the value on the shell command line
# | v- keep escaping the heredoc securely
# | |
ssh -T -p 1234 root@"$host" "bash -s $var_str" <<'EOF'
# retrieve it off the shell command line
var=$1
# ...and use it as you like thereafter.
echo "Remotely using $var"
EOF
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4298 次 |
| 最近记录: |