使用定界符
您可以在 shell 的标准输入上传递您的确切代码:
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
),它将代码传递到远程系统exactly,所以变量展开("$foo"
) 将在远程端进行扩展,仅使用远程 shell 可用的变量。
这也会消耗包含要运行的脚本的heredoc的标准输入——如果您需要标准输入可用于其他目的,则可能无法按预期工作。
动态生成评估安全命令:阵列版
您还可以告诉 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)"
动态生成 eval-safe 命令:函数版
您还可以将命令封装在函数中,并告诉 shell 序列化该函数。
remote_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;"
}
ssh user@host bash -s <<<"$(declare -f remote_cmd); remote_cmd"
Using bash -s
如果您确定远程 shell 默认是 bash,则不需要在此处字符串或不带引号的此处文档中传递代码 - 如果是这种情况,您可以在命令行上传递代码(代替bash -s
) 反而。
如果远程命令需要传递一些变量,请使用declare -p
以与上面使用相同的方式远程设置它们declare -f
.