python ssh链接Mysql数据库

from sshtunnel import SSHTunnelForwarder
import time, datetime, pymysql, json, requests


def ssh_mysql(sql, method):
# SSH 信息
ssh_ip = ''
ssh_port = 2214 # type:int
ssh_username = 'root'
ssh_password = ''
# DB信息
db_user = 'root'
db_password = ''
db_host = '127.0.0.1'
database = 'bigadmin'

with SSHTunnelForwarder(
(ssh_ip, ssh_port),
ssh_username=ssh_username,
ssh_password=ssh_password,
remote_bind_address=('127.0.0.1', 3306)) as server:

       #必须为本机回环地址,其实就是一个端口映射,首先通过 sshtunnel.SSHTunnelForwarder 进行端口映射,将远程服务器的3306端口映射到本地的3306端口,再连接本地的端口,
       #那么后续对本地3306端口的操作其实都可以视为对线上服务器3306端口的操作,理论上来说,PuTTY也是进行了相同的操作,以此达到内网穿透的目的。


db = pymysql.connect(host=db_host,
port=server.local_bind_port,
user=db_user,
passwd=db_password,
database=database,
charset='utf8')
cursor = db.cursor()

if method == 'get':
cursor.execute(sql)
data = cursor.fetchall()
db.close()
return data

if method == 'add':
cursor.execute(sql)
insert_id = cursor.lastrowid
db.commit()
db.close()
return '添加的id是:{}'.format(insert_id)

if method == 'edit':
cursor.execute(sql)
edit_id = cursor.lastrowid
db.commit()
db.close()
return '更新的id是:{}'.format(edit_id)

if method == 'del':
cursor.execute(sql)
del_id = cursor.lastrowid
db.commit()
db.close()
return '删除的id是{]'.format(del_id)
# tips:
#1.写端口号的时候切记不要加引号!  一般是type:int
#2.绑定的本地端口号不一定非要是3306,只要你本地没有使用的端口占用,没有端口冲突都行!
#3.如果密码中有‘\’,切记一定要用‘\\’进行转义!!!


posted @ 2023-01-09 13:46  .未央  阅读(228)  评论(0编辑  收藏  举报