引言
自己搭建了一个堡垒机,原理是堡垒机和目标服务器是开放的,而其它IP对目标服务器不可访问,当然也可以通过下图来了解。
代码
import sshtunnel
import pymysql
ssh_server = sshtunnel.SSHTunnelForwarder(
ssh_address_or_host=("3*.***.**.*9", 22), # 堡垒机的地址和端口号
ssh_username="****", # SSH 用户名(如果使用 pem 公钥可不设置)
ssh_password="******", # SSH 密码(如果使用 pem 公钥可不设置)
ssh_pkey="./key.pem", # pem 公钥路径(如用户名和密码方式登录,可不设置)
remote_bind_address=("4*.***.***.**8", 3306)) # 内部机器的地址和端口号
ssh_server.start()
connect = pymysql.connect(
host='127.0.0.1',
port=ssh_server.local_bind_port,
user='******',
password='******'
)
cursor = connect.cursor()
cursor.execute("show databases")
fetchall = cursor.fetchall()
print(fetchall)