1

I'm studying MySQL, and every time I have to

  1. Enter ssh XXX@XXX command, and enter my password to the school server.
  2. Enter mysql -u XXX -p command, and enter MySQL password.

I want to create a Bash script for performing the steps above automatically.

I can accomplish the first step with this code:

#!/usr/bin/expect -f    
set address xxx.com   
set password xxx  
set timeout 10   
spawn ssh xxx@$address   
expect {    "*yes/no" { send "yes\r"; exp_continue}    "*password:" { send "$password\r" }  }  
send clear\r 
interact

But I don't know how to automatically input the next command (mysql -u xxx -p) and the password.

How can I do this?

0

2 Answers 2

5

You don't need such a complex script to just enter the MySQL console on remote machine. Use the features of the ssh tool:

ssh -tt user@host -- mysql -uuser -ppassword

The -t option forces pseudo-terminal allocation. Multiple -t force tty allocation, even if ssh has no local tty (see man ssh). Note the use of -p option. There must be no spaces between -p and password (see the manual for mysql).

Or even connect via mysql directly, if the MySQL host is accessible from your local machine:

mysql -hhost -uuser -p

Don't forget to adjust the shebang:

#!/bin/bash -
Sign up to request clarification or add additional context in comments.

4 Comments

What if I want to create a bash file for running these steps, I mean I just open the file, than all the commands will be correctly input in terminal.
@J.Pei, you can put the command into a file, of course. Don't forget to adjust the she-bang line accordingly.
So, the effectiveness of "-tt" is combine the 2 commands(ssh ... and mysql ...) to one command line?@Ruslan Osmanov
@J.Pei, no, -tt forces pseudo-terminal allocation. And you need a pseudo-terminal for interactive session. Otherwise, the session may stall waiting for input, or even fail.
-1

Use my.cnf to store your password securly like ssh keys.

https://easyengine.io/tutorials/mysql/mycnf-preference/

Same way ssh is also possible through ssh -i parameter and passing the private key path of the remote host.

Best of luck!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.