1

我的脚本遇到了一些问题,该脚本应该通过 SSH 连接到我的服务器、运行 mysql 查询并返回特定值。

我的问题是,当我使用命令替换 [ $() 和 `` ] 时出现访问被拒绝错误 - 但如果没有命令替换,我不会将结果保存到变量中。

我有完全权限,而且密码是正确的。

  ssh root@SERVER.com  << EOFMARK
    example=$(mysql -h localhost -u root -p$MYSQL_PASSWORD myDatabase -e "SELECT now();")  
    echo "Variable is $example"
  EOFMARK

echo "My goal is to read the variable here: $example"
4

2 回答 2

1

您应该逃避必须在远程主机上完成的替换:

尝试:

 ssh root@SERVER.com  << EOFMARK
    example=\$(mysql -h localhost -u root -p$MYSQL_PASSWORD myDatabase -e "SELECT now();")  
    echo "Variable is \$example"
  EOFMARK

您可以按照@glglgl 的建议,将 ssh 命令的标准输出捕获到本地变量中。但我会使用本地 mysql 客户端,我会授予访问数据库的权限。如果您有防火墙阻止您远程访问 3306,我会 ssh 转发端口。

example=$(mysql -h SERVER.com -u root -p myDatabase -e "SELECT now();") 

这是正确的做法。没有 ssh 和交互式密码,无法通过ps -ef| grep mysql

于 2014-03-07T07:27:49.553 回答
1

你可能想要

  • 立即执行命令并
  • 给它应该执行的查询。

这边走:

example=$(ssh root@SERVER.com mysql -h localhost -u root -p"$MYSQL_PASSWORD" myDatabase -e '"SELECT now();"')
echo "My goal is to read the variable here: $example"

将是要走的路。

如果您真的在两个地方都需要它,您可能希望在服务器上有一个脚本,或者您可以尝试

example=$(ssh root@SERVER.com 'example=$(mysql -h localhost -u root -p"$MYSQL_PASSWORD" myDatabase -e "SELECT now();"); echo "Variable is $example")
echo "My goal is to read the variable here: $example"

为了坚持heredoc,您也可以尝试

example=$(ssh root@SERVER.com  << EOFMARK
    example=$(mysql -h localhost -u root -p$MYSQL_PASSWORD myDatabase -e "SELECT now();")  
    echo "Variable is $example"
EOFMARK)

echo "My goal is to read the variable here: $example"

为了在客户端也有变量。


由于任何原因,我无法理解 heredoc 示例。

但其他人应该看起来像

example=$(ssh root@SERVER.com 'mysql -NB -h localhost -u root -p"$MYSQL_PASSWORD" myDatabase -e "SELECT now();"')
echo "My goal is to read the variable here: $example"

将输出准确地提供给局部变量,或者

example=$(ssh root@SERVER.com 'example=$(mysql -NB -h localhost -u root -p"$MYSQL_PASSWORD" myDatabase -e "SELECT now();"); echo "Variable is $example")
echo "My goal is to read the variable here: $example"

但你应该知道,在这里,本地输出看起来像(例如)

My goal is to read the variable here: Variable is 2014-03-07 20:42:23

因为子字符串Variable is也得到输出。

于 2014-03-07T08:05:01.943 回答