Skip to content

Commit

Permalink
'添加zip包操作,ssh跳板连接mysql'
Browse files Browse the repository at this point in the history
  • Loading branch information
cuizhongyi committed Aug 13, 2018
1 parent 1688a87 commit 4a3c75e
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
42 changes: 42 additions & 0 deletions ssh_connect_mysql/ssh_connect_mysql.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
通过跳板机,连接远程mysql数据库
author: gxcuizy
time: 2018-08-10
"""

import pymysql
from sshtunnel import SSHTunnelForwarder

# 程序主入口
if __name__ == "__main__":
# 跳板机SSH连接
with SSHTunnelForwarder(
('192.168.0.1', 22),
ssh_username="test",
ssh_pkey="test.pem",
remote_bind_address=('*************mysql.rds.aliyuncs.com', 3306)
) as tunnel:
# 数据库连接配置,host默认127.0.0.1不用修改
conn = pymysql.connect(
host='127.0.0.1',
port=tunnel.local_bind_port,
user='root',
password='root',
db='test',
charset='utf8',
cursorclass=pymysql.cursors.DictCursor
)
# 获取游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 查询数据库,查询一条数据,其他CURD操作类似
sql = "SELECT name FROM table_name WHERE id = '%s'"
prams = ('1',)
cursor.execute(sql % prams)
info = cursor.fetchone()
print(info)
# 关闭连接
cursor.close()
conn.close()
51 changes: 51 additions & 0 deletions zip/zip.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
压缩和解压缩zip文件
author: gxcuizy
time:2018-08-13
"""

import zipfile
import os


def create_zip(path):
"""创建一个压缩文件"""
# 创建一个zip文件对象
zip_file = zipfile.ZipFile(os.path.basename(path) + ".zip", "w")
# 将文件写入zip文件中,即将文件压缩
print('开始压缩文件……')
for root, dirs, files in os.walk(path, topdown=False):
for name in dirs:
print("正在压缩文件夹:" + os.path.join(root, name))
zip_file.write(os.path.join(root, name))
for name in files:
print("正在压缩文件:" + os.path.join(root, name))
zip_file.write(os.path.join(root, name))
# 关闭zip文件对象
zip_file.close()


def uncompress_zip(path):
"""解压缩一个文件"""
print('正在解压文件中……')
zfile = zipfile.ZipFile(path, "r")
zfile.extractall()


# 程序主入口
if __name__ == "__main__":
# 打包(解压缩)的文件路径(文件名)
path_info = 'test.zip'
if os.path.isdir(path_info):
# 打包
create_zip(path_info)
print('压缩完成!')
elif os.path.isfile(path_info):
# 解压
uncompress_zip(path_info)
print('解压完成!')
else:
print('文件类型错误,请重试!')

0 comments on commit 4a3c75e

Please sign in to comment.