我有以下说明并且它有效。
ssh -i /e/Data/openssh.ppk [email protected] ssh cos-server "pwd "
但是当我执行下面的指令时:
ssh -i /e/Data/openssh.ppk [email protected] ssh cos-server "mysql -u bduser --host=tdb --password=pass -e \"SELECT 1 AS Quantity;\""
它要求我输入密码。我输入了密码,但命令似乎失败了,输出显示了mysql选项。我不知道是否需要另一个引号。
这是输出:
Warning: Permanently added 'cos-server_avm,100.69.35.5' (ECDSA) to the list of
known hosts.
mysql Ver 15.1 Distrib 10.2.13-MariaDB, for Linux (x86_64) using readline 5.1
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Usage: mysql [OPTIONS] [database]
Default options are read from the following files in the given order:
/etc/my.cnf ~/.my.cnf
The following groups are read: mysql client client-server client-mariadb
The following options may be given as the first argument:
--print-defaults Print the program argument list and exit.
--no-defaults Don't read default options from any option file.
--defaults-file=# Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.
-?, --help Display this help and exit.
-I, --help Synonym for -?
--abort-source-on-error
Abort 'source filename' operations in case of errors
--auto-rehash Enable automatic rehashing. One doesn't need to use
'rehash' to get table and field completion, but startup
and reconnecting may take a longer time. Disable with
--disable-auto-rehash.
(Defaults to on; use --skip-auto-rehash to disable.)
-A, --no-auto-rehash
...
...
操作说明:
ssh -i /e/Data/openssh.ppk [email protected] ssh cos-server 'mysql --user=bduser --host=tdb --password=pass -e "SELECT VERSION();SELECT NOW()"'
输出:
Warning: Permanently added 'cos-server,100.69.35.5' (ECDSA) to the list of known
hosts.
bash: -c: line 0: syntax error near unexpected token `('
bash: -c: line 0: `mysql -u bduser --host=tdb --password=pass -e SELECT
VERSION();SELECT NOW();'
这个案例中缺少了什么?
答案1
MySQL 说:
Usage: mysql [OPTIONS] [database]
因为您没有指定数据库。您的命令应如下所示:
ssh -i /e/Data/openssh.ppk [email protected] \
ssh cos-server \
'mysql -u bduser --host=tdb --password=pass -e \"SELECT 1 AS Quantity\;\" the_database'
编辑:答案最初有一个命令,其中转义是关闭的,这样,字符;
就被解释为命令的结尾。我已经更新了答案,但显然,随着 SQL 命令变得越来越复杂,这会变得越来越令人困惑。例如,一个简单的命令select count(*)
需要转义括号,并且会变成select count\(*\)
。如果查询包含字符串,那么您必须编写类似这样的 mysql 命令:
'mysql -u bduser --host=tdb --password=pass -e \"SELECT \\\"'this_string'\\\" AS Quantity\;\" the_database'
至少可以说这并不简单。
如果您计划以这种方式定期使用此数据库,那么您可能需要考虑其他选项,例如建立 SSH 隧道并连接到本地计算机上的隧道端口。
答案2
'mybd' 不是有效标志,因此它向您显示有效选项。删除它,它应该可以工作:
ssh -i /e/Data/openssh.ppk [email protected] ssh cos-server "mysql -u bduser --host=tdb --password=pass -e 'SELECT 1 AS Quantity;'"
答案3
我换了一种方式来做。
脚步:
在服务器上:
1) 我在 /etc 中创建了一个目录 impsql 2) 我创建了一个批处理文件。假设:impsql.sh(包括 chmod +x)。此文件包含:
ssh cos-server mysql -u bduser --host=tdb --password=pass mydb < /etc/impsql/impsql.sql
3) 我在 /etc 中创建了一个文件 impsql.sql。该文件包含:
SELECT 1 AS Quantity;
在 PC 客户端上:
4)我执行:
ssh -i /e/Data/openssh.ppk [email protected] /etc/impsql/impsql.sh
所以不涉及引号。