通过ssh在bash脚本创建MySQL数据库 [英] Create mySQL database through ssh in a bash script
本文介绍了通过ssh在bash脚本创建MySQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过ssh来创建一个远程服务器上的数据库与bash脚本。事情是这样的。
#!/ bin / sh的
SSH user@example.com'的mysql -h example.com -uroot -pMYPASSWD -eCREATE DATABASE $ 1;'
所以,我在终端可以像
运行 $ myBashScript nameOfNewDatabase
解决方案
下面的脚本可以远程执行任意命令。
#!/斌/庆典
在远程服务器上调用#mysql的执行给定的命令#显示使用和退出
用法(){
回声$ 0个服务器的SQL命令1>和2
1号出口
}参数#支票号码
如果[$#-lt 2]
然后
用法
科幻#获取服务器的名称和SQL命令
服务器=$ 1
SQL =$ 2#copy命令到一个临时文件
tmpsql =/ tmp目录/ SQL $$
回声$ SQL> $ tmpsql#命令文件复制到服务器
SCP $ tmpsql $服务器:$ tmpsql
#运行与远程删除命令文件命令之后
SSH服务器$的mysql -uroot -ppassword< $ tmpsql; RM $ tmpsql
#删除命令文件的本地副本
RM $ tmpsql
I want to create a database on a remote server through ssh with a bash script. Something like this
#!/bin/sh
ssh user@example.com 'mysql -h example.com -uroot -pMYPASSWD -e "CREATE DATABASE $1;"'
So that I in terminal can run it like
$ myBashScript nameOfNewDatabase
解决方案
The following script can remotely execute arbitrary commands
#!/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在bash脚本创建MySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文