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

查看:73
本文介绍了使用 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 安全形式转义内容;这样做后,您可以在远程shell的命令行上传递它们,并通过远程脚本中的$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天全站免登陆