我正在编写一个小的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 <
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
注意,上面没有执行任何变量扩展 – 由于使用了<<<
这也消耗了包含要运行的脚本的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)"
标签:bash,linux,ssh
来源: https://codeday.me/bug/20190928/1825468.html