Christoffer
Christoffer

Reputation: 9

SSH directly into MySQL server

i got a remote webserver running with a mysql database. Right now im using SSH to do any serverside management, and i access the MySQL often. I wondered if its possible for me to make a script that would ssh into the server and if run with "-sql" (subject to change) on the command line it would instead go into mysql.

What i made so far:

#!/bin/bash
if [ "$1" == "-l" ]; then
    ssh [email protected] //local address for privacy;
    mysql -u root -p;
else
    ssh [email protected]
fi

This results in an SSH session and when it ends my computer will try and create a mysql connection on the local machine.

#!/bin/bash
if [ "$1" == "-l" ]; then
    ssh [email protected] 'mysql -u root -p';
else
    ssh [email protected]
fi

This results in a password request and then nothing. I'm assuming its because using ssh with a command expects a response and then shuts down the connection.

Is there any way to do this, i realise that it's not of any significant importance, but it is fun to play around with

Thanks in advance

Upvotes: 0

Views: 524

Answers (3)

Hankster
Hankster

Reputation: 422

One option you might want to consider for solving this kind of access problem is through the use of the tunneling facility in ssh:

ssh -l user -L 33306:192.168.0.101:3306 192.168.0.101

or maybe

ssh -l user -L 33306:127.0.0.1:3306 192.168.0.101

This creates a port on your local machine (33306) which tunnels to the mysql port (3306) on the remote machine.

Then on your local machine you run a local copy of mysql:

mysql --port=33306 -u root -p

which should connect through the tunneled port to your database.

Upvotes: 3

Harikrishnan
Harikrishnan

Reputation: 9979

Try like this. Feed mysql password with the command. So you don't have to enter the password.

ssh [email protected] 'mysql --user="root" --password="password" --database="database" --execute="My Query;"'

Also I suggest you to set keybased ssh authentication. Hence you can also avoid typing ssh password every time.

Upvotes: 0

Barmar
Barmar

Reputation: 780663

The mysql command only executes interactively if it's input is a terminal. When you run ssh with a command argument, it doesn't normally allocate a pseudo-tty on the server. So mysql just processes its standard input without displaying a prompt.

Use the -t option to force this:

ssh -t [email protected] 'mysql -u root -p'

Upvotes: 5

Related Questions