背景
公司生产环境需要使用堡垒机登陆,而有一些临时数据需要用python和表格处理,就想着在本地连接,经过网上查找,找到以下办法
需要安装的包
pip install pyhive
pip install sshtunnel
pip imstall pymysql
使用堡垒机,都用到了sshtunnel这个库,使用方法如下:
import pymysql
from pyhive import hive
from sshtunnel import SSHTunnelForwarder
with SSHTunnelForwarder(ssh_address_or_host=('ssh_host', port), # 堡垒机的地址和端口
ssh_pkey=r'.\private_key', # 密钥的地址,如果是通过密码登陆把参数换成ssh_password
ssh_username='user', # 堡垒机账号
remote_bind_address=('host', port)) as server: # 要连接的数据库的地址和端口
# conn = pymysql.connect(host='127.0.0.1', port=server.local_bind_port, user='user', password='password')
# cursor = conn.cursor()
conn = hive.connect(host='127.0.0.1', port=server.local_bind_port, username='user')
# cursor = conn.cursor()
# cursor.execute('''select count(*) from table''')
# print(cursor.fetchall())
# cursor.close()
df = pd.read_sql('select count(*) from table', con=conn)
print(df)
conn.close()
说明:
connect()方法的参数中的host必须为127.0.0.1;
其实重点就是SSHTunnelForwarder 这个方法进行的代理配置,其他的只需要根据不同的数据库调用不用的模块即可。这里还有个问题,在调用pyhive的时候,如果直接执行sql,会报错:拒绝连接,但是使用pandas的read_sql则不会,目前还不知道是什么原因,如果有知道的大佬也可以跟我说一下。