简体   繁体   中英

Run Remote Mysql Command with Shell Script

I am trying to run an ssh command in my shell script which will automatically create a database, user, password etc on a remote server:

password=`date +%s|sha256sum|base64|head -c 32`
read -p "Enter staging folder name... e.g. xxxxxxxx:   " stagingdirectory
echo $stagingdirectory
read -p "Give the name for the database (this will be used in mysql)" dbname
echo $dbname
read -p "Give the name of the user for the database (this will be used in mysql)" dbuser
echo $dbuser

sqlstatement="mysql -uXXXXXXX -pXXXXXXXX -hXXXXXXXX -e "
sqlstatement+='"CREATE DATABASE IF NOT EXISTS $dbname;CREATE USER $dbuser@'%' IDENTIFIED BY '$password';GRANT ALL PRIVILEGES ON $dbname.* TO $dbuser@'%';FLUSH PRIVILEGES;"'

echo $sqlstatement
ssh -A $domainname@35.163.55.55 -e "$sqlstatement"

When I try and run this command, I get this error:

This is what gets returned (I have replaced actual values with XXXX):

Bad escape character 'mysql -udbadmin -pXXXXX -hXXXXX -e"CREATE DATABASE IF NOT EXISTS $dbname;CREATE USER $dbuser@% IDENTIFIED BY XXXXXX;GRANT ALL PRIVILEGES ON $dbname.* TO $dbuser@%;FLUSH PRIVILEGES;"'.

I think this is due to my sql statement and strings escaping.

Try changing the line,

ssh -A $domainname@35.163.55.57 -e "$sqlstatement"

to

ssh -A $domainname@35.163.55.57 "$sqlstatement"

From the manual of ssh, see below

-e escape_char

Sets the escape character for sessions with a pty (default: '~'). The escape character is only recognized at the beginning of a line. The escape character followed by a dot ('.') closes the connection; followed by control-Z suspends the connection; and followed by itself sends the escape char- acter once. Setting the character to “none” disables any escapes and makes the session fully transparent.

Here in your example, ssh is not getting a valid escape character, and you don't need one either

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM