-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathsshtunnel_sql.py
71 lines (54 loc) · 1.69 KB
/
sshtunnel_sql.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/python
#_*_coding:utf-8_*_
# code.by leoiceo
import MySQLdb
from sshtunnel import SSHTunnelForwarder
import MySQLdb.cursors
def dbconnect_ssh(ssh_host,ssh_port,keyfile,ssh_user,db_host,db_name,sql,db_port,db_user,db_passwd):
with SSHTunnelForwarder(
(ssh_host, ssh_port),
#ssh_password="sshpasswd",
ssh_pkey=keyfile,
ssh_username=ssh_user,
remote_bind_address=(db_host, db_port)
) as server:
db = MySQLdb.connect(
host='127.0.0.1',
port=server.local_bind_port,
user=db_user,
passwd=db_passwd,
db=db_name,
charset="utf8",
cursorclass=MySQLdb.cursors.DictCursor)
cursor = db.cursor()
try:
cursor.execute(sql)
data = cursor.fetchall()
db.commit()
except:
db.rollback()
collect = []
for result in data:
collect.append(result)
db.close()
cursor.close()
return collect
def dbconnect(db_host,db_name,cmd,port,db_user,db_passwd):
try:
db = MySQLdb.connect(host="%s"%db_host,port=port,user=db_user,passwd=db_passwd,db="%s"%db_name,charset="utf8",cursorclass = MySQLdb.cursors.DictCursor)
cursor = db.cursor()
except Exception,e:
print "db connect failed: %s" % e
sql = "%s"%cmd
try:
cursor.execute(sql)
data = cursor.fetchall()
db.commit()
except:
db.rollback()
collect = []
for result in data:
collect.append(result)
db.close()
cursor.close()
return collect