我正在编写一个小的 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;"
Run Code Online (Sandbox Code Playgroud)
不幸的是,这个命令同时包含单引号和双引号,所以我做不到
ssh user@host "command";
Run Code Online (Sandbox Code Playgroud)
解决此问题的推荐方法是什么?
您可以在 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
Run Code Online (Sandbox Code Playgroud)
请注意,上面没有执行任何变量扩展——由于使用了<<'EOF'(vs <<EOF),它将代码准确地传递给远程系统,因此变量扩展 ( "$foo") 将在远程端扩展,仅使用可用变量到远程外壳。
这也会为包含要运行的脚本的heredoc 消耗stdin——如果您需要stdin 可用于其他目的,这可能无法按预期工作。
您还可以告诉 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"
Run Code Online (Sandbox Code Playgroud)
需要注意的是,如果您的字符串扩展为包含不可打印字符的值,则$''在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)"
Run Code Online (Sandbox Code Playgroud)
您还可以将您的命令封装在一个函数中,并告诉您的 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"
Run Code Online (Sandbox Code Playgroud)
bash -s如果您确定远程 shell 默认为 bash,则不需要在此处字符串或不带引号的 heredoc 中使用和传递代码——如果是这种情况,您可以在命令行上传递代码(代替的bash -s)来代替。
如果远程命令需要传递一些变量,使用declare -p与上面使用的相同的方式远程设置它们declare -f。