一、封装带SSH跳板机的MYSQL

二、配置settting

 1 import pymysql
 2 from sshtunnel import SSHTunnelForwarder
 3 
 4 class MyDb(object):
 5     #mysql类方法
 6     def __del__(self):
 7         self.cur.close()
 8         self.coon.close()
 9         self.server.close()
10 
11     def __init__(self,host,ssh_username,ssh_password,ip,db,sql_username,password):
12         try:
13             server = SSHTunnelForwarder(
14                 ssh_address_or_host=(host, 22),
15                 ssh_username=ssh_username,
16                 ssh_password=ssh_password,
17                 remote_bind_address=(ip, 3306)
18             )
19             self.server = server
20             self.server.daemon_forward_servers = True #不加server关闭不了
21             self.server.start()
22             self.connect = pymysql.connect(
23                 host='127.0.0.1',user=sql_username,passwd=password,port=self.server.local_bind_port,charset='utf8',db=db,
24                 autocommit=True,
25             )
26 
27         except Exception as e:
28             print('mysql连接失败,错误信息%s'%e)
29 
30         else:
31             self.cursor = self.connect.cursor(cursor=pymysql.cursors.DictCursor)
32 
33 
34     def ex_sql(self,sql,many=True):
35         try:
36             self.cursor.execute(sql)
37         except Exception as e:
38             print('sql语句有问题,%s'%sql)
39         else:
40             if many:
41                 result = self.cursor.fetchall()
42             else:
43                 result = self.cursor.fetchone()
44             return result
45 
46 
47 #哪里用哪里实例化吧
48 # my_sql = MyDb(**setting.MYSQL_INFO)
49 #直接在这里实例化的话,用的时候,直接导入就ok了
ssh_mysql

相关文章:

  • 2022-12-23
  • 2021-10-05
  • 2021-09-19
  • 2021-06-30
  • 2022-12-23
  • 2021-05-21
  • 2021-08-02
猜你喜欢
  • 2021-09-10
  • 2022-12-23
  • 2021-10-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案