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

时间:2022-09-26 08:04:25

I want to create a database on a remote server through ssh with a bash script. Something like this

我想通过带有bash脚本的ssh在远程服务器上创建数据库。像这样的东西

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

1 个解决方案

#1


2  

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

#1


2  

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