linux 命令行 双引号,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 <

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值