简体   繁体   English

SSH直接进入MySQL服务器

[英]SSH directly into MySQL server

i got a remote webserver running with a mysql database. 我有一个运行有mysql数据库的远程网络服务器。 Right now im using SSH to do any serverside management, and i access the MySQL often. 现在,我使用SSH进行任何服务器端管理,而且我经常访问MySQL。 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. 我想知道是否有可能制作一个可以ssh进入服务器的脚本,并且如果在命令行上使用“ -sql”(可能会更改)运行,那么它将进入mysql。

What i made so far: 我到目前为止所做的:

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

This results in an SSH session and when it ends my computer will try and create a mysql connection on the local machine. 这将导致SSH会话,并且在它结束时,我的计算机将尝试在本地计算机上创建mysql连接。

#!/bin/bash
if [ "$1" == "-l" ]; then
    ssh user@192.168.0.101 'mysql -u root -p';
else
    ssh user@192.168.0.101
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. 我假设它是因为将ssh与命令配合使用会期望响应,然后关闭连接。

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 提前致谢

The mysql command only executes interactively if it's input is a terminal. 如果输入的是终端,则mysql命令仅以交互方式执行。 When you run ssh with a command argument, it doesn't normally allocate a pseudo-tty on the server. 当使用命令参数运行ssh时,通常不会在服务器上分配伪tty。 So mysql just processes its standard input without displaying a prompt. 因此, mysql只处理其标准输入而不会显示提示。

Use the -t option to force this: 使用-t选项强制执行此操作:

ssh -t user@192.168.0.101 'mysql -u root -p'

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中的隧道工具:

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. 这将在本地计算机(33306)上创建一个端口,该端口通过隧道连接到远程计算机上的mysql端口(3306)。

Then on your local machine you run a local copy of mysql: 然后在本地计算机上运行mysql的本地副本:

mysql --port=33306 -u root -p

which should connect through the tunneled port to your database. 它应该通过隧道端口连接到您的数据库。

Try like this. 尝试这样。 Feed mysql password with the command. 使用命令输入mysql密码。 So you don't have to enter the password. 因此,您不必输入密码。

ssh user@192.168.0.101 'mysql --user="root" --password="password" --database="database" --execute="My Query;"'

Also I suggest you to set keybased ssh authentication. 我也建议您设置基于密钥的ssh身份验证。 Hence you can also avoid typing ssh password every time. 因此,您也可以避免每次都键入ssh密码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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