使用ssh和EOF在bash脚本中将变量传递给远程主机 [英] Passing a variable to a remote host in a bash script with ssh and EOF

查看:1068
本文介绍了使用ssh和EOF在bash脚本中将变量传递给远程主机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本来解析服务器列表,查找一些东西,并在情况正确的情况下执行命令. 主服务器通过ssh连接到它们,执行EOF语句中的所有命令:

I have a script parsing a list of servers, looking for some stuff and executing commands if the circumstances are correct. The main server is connecting to them via ssh, executing all commands that are in the EOF statement:

#!/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

我知道如果我从EOF中删除单引号,则变量可以通过,但是如果我这样做,则mysql语句将无法正常工作,并且一切都会中断.

I know the variable can pass through if I remove the single quotes from the EOF, but if i do so the mysql statements wont work and everything breaks.

我知道有多种方法可以传输变量,但是带有;"的东西选项之间不适合我(脚本尝试将其作为命令执行)

I know there are ways to transmit a variable, but things with ";" between options wont work for me ( the script tries to execute it as a command )

有什么想法吗?

推荐答案

使用printf %qeval安全形式转义内容;之后,您可以在远程外壳程序的命令行上传递它们,并通过$1$2等在远程脚本中检索它们:

Use printf %q to escape content in an eval-safe form; after doing so, you can pass them on the command line of the remote shell, and retrieve them via $1, $2, etc. within the remote script:

# 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

这篇关于使用ssh和EOF在bash脚本中将变量传递给远程主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆