微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在bash脚本中通过ssh创建mySQL数据库

我想使用bash脚本通过ssh在远程服务器上创建数据库.像这样

#!/bin/sh
ssh [email protected] 'MysqL -h example.com -uroot -pMYPASSWD -e "CREATE DATABASE $1;"'

这样我在终端可以像

$myBashScript nameOfNewDatabase

解决方法:

以下脚本可以远程执行任意命令

#!/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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐