在Bash脚本中通过SSH创建MySQL数据库

3
我希望通过ssh和bash脚本在远程服务器上创建数据库。类似于这样:
#!/bin/sh
ssh user@example.com 'mysql -h example.com -uroot -pMYPASSWD -e "CREATE DATABASE $1;"'

这样我就可以在终端中像这样运行它:

$ myBashScript nameOfNewDatabase

尝试这个:ssh user@example.com "mysqladmin create $1" - ed.
http://www.manpagez.com/man/1/mysqladmin/ 提供了选项的详细信息,例如 --user=root --password=MYPASSWD 等。 - ed.
得到错误bash: mysqladmin: 未找到命令,尝试了我在描述中写的那个,但是mysql已经安装了。我将检查一下是否安装了mysqladmin。 - Spoeken
Mysqladmin已安装,但当我尝试通过ssh user@example.com远程运行命令"mysqladmin create $1"时,它会给我上面的错误。 - Spoeken
请注意,“mysqladmin”不是本地的,而是安装在服务器上的。尝试类似这样的命令 ssh user@example.com "/path/to/mysqladmin create $1",不要依赖于远程PATH设置。 - wh81752
1个回答

3
以下脚本可以远程执行任意命令。
#!/bin/bash
# call mysql on a remote server to execute the given command 

# show usage and exit
usage() {
  echo "$0 server sql-command"  1>&2
    exit 1
}

# check number of arguments
if [ $# -lt 2 ]
then
  usage
fi

# get server name and sql command
server="$1"
sql="$2"

# copy command to a temporary file
tmpsql="/tmp/sql$$"
echo "$sql" > $tmpsql

# copy command file to server
scp $tmpsql $server:$tmpsql
# run command remotely with removing command file afterwards
ssh $server "mysql -uroot -pPASSWORD < $tmpsql;rm $tmpsql"
# remove local copy of command file
rm $tmpsql

你需要确保在ssh会话中设置了PATH或在脚本中指定mysql的完全限定名称。在ssh终端会话中使用“which mysql”来查找它,例如:
which mysql /usr/local/mysql/bin/mysql
- Wolfgang Fahl
那么在服务器的bash配置文件中设置了PATH也没有帮助,我还需要在这个脚本中声明它?应该如何实现呢? - Spoeken
使用MacPorts时,我必须将PATH声明放在.ssh/environment中,例如:PATH=/usr/bin:/bin:/usr/sbin:/sbin:/opt/local/bin - Wolfgang Fahl
好的,我已经做到了可以运行mysql命令,不过必须写上整个mysql路径。但现在它告诉我“-e”需要一个参数。你有任何线索吗? - Spoeken
我的脚本没有使用-e将命令导入mysql。我故意试图避免需要-e的引号转义问题。在ssh连接中,引号和其他需要转义的字符可能会变得棘手。 - Wolfgang Fahl
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接