如何在脚本化的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")将在远程端扩展,仅使用可用变量到远程外壳。

这也消耗了包含要运行的脚本的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)"

以上是 如何在脚本化的ssh命令中使用单引号和双引号 的全部内容, 来源链接: utcz.com/qa/424661.html

回到顶部