通过ssh在bash脚本创建MySQL数据库(Create mySQL database throu

2019-09-24 04:11发布

我想通过ssh来创建一个远程服务器上的数据库有一个bash脚本。 像这样的事情

#!/bin/sh
ssh user@example.com 'mysql -h example.com -uroot -pMYPASSWD -e "CREATE DATABASE $1;"'

所以,我在终端可以运行它像

$ myBashScript nameOfNewDatabase

Answer 1:

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

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


文章来源: Create mySQL database through ssh in a bash script