微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linux – 如何在脚本化的ssh命令中使用简单和双引号

我正在编写一个小的bash脚本,并希望通过ssh执行以下命令

sudo -i MysqL -uroot -pPASSWORD --execute "select user, host, password_last_changed from MysqL.user where password_last_changed <= '2016-9-00 11:00:00' order by password_last_changed ASC;"

不幸的是,这个命令包含简单和双引号,所以我做不到

ssh user@host "command";

什么是解决此问题的推荐方法

解决方法:

使用heredoc

你可以在shell的stdin上传递确切的代码

ssh user@host bash -s <<'EOF'
sudo -i MysqL -uroot -pPASSWORD --execute "select user, host, password_last_changed from MysqL.user where password_last_changed <= '2016-9-00 11:00:00' order by password_last_changed ASC;"
EOF

注意,上面没有执行任何变量扩展 – 由于使用了<<<<'EOF'(vs<<< EOF),它将代码准确地传递给远程系统,因此变量扩展(“ $foo“)将在远程端扩展,仅使用远程shell可用的变量. 这也消耗了包含要运行的脚本的heredoc的stdin – 如果你需要stdin可用于其他目的,那可能无法正常工作. 动态生成eval-safe命令 您也可以告诉shell本身为您做报价.假设你的本地shell是bash或ksh:

#!/usr/bin/env bash
#              ^^^^ - NOT /bin/sh

# put your command into an array, honoring quoting and expansions
cmd=(
  sudo -i MysqL -uroot -pPASSWORD
    --execute "select user, host, password_last_changed from MysqL.user where password_last_changed <= '2016-9-00 11:00:00' order by password_last_changed ASC;"
)

# generate a string which evaluates to that array when parsed by the shell
printf -v cmd_str '%q ' "${cmd[@]}"

# pass that string to the remote host
ssh user@host "$cmd_str"

需要注意的是,如果您的字符串扩展为包含不可打印字符的值,则可以在printf’%q’的输出中使用不可移植的$”引用形式.要以可移植的方式解决这个问题,您实际上最终会使用一个单独的解释器,例如Python:

#!/bin/sh
# This works with any POSIX-compliant shell, either locally or remotely
# ...it *does* require Python (either 2.x or 3.x) on the local end.

quote_args() { python -c '
import pipes, shlex, sys
quote = shlex.quote if hasattr(shlex, "quote") else pipes.quote
sys.stdout.write(" ".join(quote(x) for x in sys.argv[1:]) + "\n")
' "$@"; }

ssh user@host "$(quote_args sudo -i MysqL -uroot -pPASSWORD sudo -i MysqL -uroot -pPASSWORD)"

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐