Docs/数据库/mysql/命令行ssh通道连接mysql.md
2022-10-18 16:59:37 +08:00

45 lines
No EOL
2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#### 背景说明如下
为了安全mysql数据库安装在内网环境外网无法直连只能通过与数据库在同一个内网的、可以与外网通信的服务器连接即使用ssh隧道连接。
一般的第三方可视化客户端连接工具都可以配置ssh隧道。若使用命令行连接就需要使用命令建立隧道。
##### 建立隧道命令如下:
```
# 需要连接数据库的外网环境,执行下列命令
ssh -p {ssh_port} -i {rsa_file} -fNL {local_port}:{mysql_ip}:{mysql_port} {ssh_user}@{ssh_ip}
```
###### 命令详解:
* -p {ssh_port}: 指定跳板机器的ssh服务的端口也就是B服务器
* -i {rsa_file}:指定连接跳板机的ssh公钥由跳板机的ssh服务端生成如果不指定公钥或者公钥验证失败则会弹出密码进行登录。如果需要密码登录可以不填-i
* -f:告诉SSH客户端在后台运行也就是执行命令之后在进程监听需要关闭直接kill
* -N:只进行端口转发,不执行命令
* -L:指定连接服务的格式 [bind_address:]port:host:hostport
* {local_port}:本地监听的端口
* {mysql_ip}转发到的mysql的ip或域名远程mysql主机地址
* {mysql_port}转发到的mysql的端口
* {ssh_port}:跳板机的
* {ssh_user}跳板机的ssh用户名(如果为rsa登录则ras对应的用户名和ssh_user一致)
* {ssh_ip}跳板机的ip或域名
##### 连接数据库命令:
```
mysql -h127.0.0.1 -P {local_port} -u{mysql_user} -p
```
#### 举例说明
A需要连接数据库的外网服务器centos 8
B只有内网地址或只能被特定主机连接的数据库服务器。数据库连接为172.16.0.35:3306
C可以被A直连与B在同一个内网中/或可以连接B。公网地址为3.3.3.3连接公钥为rsa_pub.pem
###### 1、建立隧道
*A执行*
```
ssh -p 22 -i rsa_pub.pem -fNL 3320:172.16.0.35:3306 root@3.3.3.3
```
###### 2、查看本地监听端口
```
ss -anltp | grep 3320
```
###### 3、连接数据库
```
mysql -h 127.0.0.1 -P 3320 -u admin -p
```