背景
最近在开发中遇到了一个场景,公司需要连接kerberos认证的Hive,正常的情况下直接用pyhive就可以了,网上可以找到许多相关的解决方案,但是我们在使用中发现了一个问题,pyhive使用的是非开源的,在查询数据时容易出现bug,且需要很长时间才能够修复,为了规避这个问题,我们采用python jdbc连接的方式来规避这个问题;
解决思路
python有lib叫做jaydebeapi,是专门用来调用jdbc连接的,我们使用jaydebeapi调用jdbc连接hive,中间做好kerberos认证即可;参考代码如下:
python
"""测试验证jaydebeapi连接hive,采用kerberos认证"""
import os
import jpype
import jaydebeapi
def main():
driver = "org.apache.hive.jdbc.HiveDriver"
HS2_HOST = "xxxx"
HS2_PORT = 10000
REALM = "xxxx"
url = f"jdbc:hive2://{HS2_HOST}:{HS2_PORT}/default;principal=hive/xxxx@{REALM};sasl.qop=auth-conf;"
jdbc_path = "/opt/xxxx/"
if not jpype.isJVMStarted():
jpype.startJVM(
jpype.getDefaultJVMPath(),
f"-Djava.class.path={jdbc_path}/hive-jdbc.jar",
"-Djava.security.krb5.conf=./krb5.conf",
"-Djavax.security.auth.useSubjectCredsOnly=false",
# 如需排查 Kerberos,打开下一行:
# "-Dsun.security.krb5.debug=true",
)
# Kerberos认证连接;不需要 username/password)
conn = jaydebeapi.connect(driver, url)
cursor = conn.cursor()
sqlstr = "select * from xxx"
cursor.execute(sqlstr)
result = cursor.fetchall()
for r in result:
print(r)
cursor.close()
conn.close()
if __name__ == '__main__':
main()
注:1.当前运行代码的环境已经安装了kerberos的client,且已经完成了认证; 2.jdbc:hive2://{HS2_HOST}:{HS2_PORT}/default;principal=hive/xxxx@{REALM};sasl.qop=auth-conf;
中的参数和所在的集群相关,需要自己配置; sasl.qop 参数通常出现在使用 Kerberos 进行安全认证的系统中,尤其是在涉及 SASL (Simple Authentication and Security Layer) 的场景下,比如 Kafka、Hadoop、LDAP 等分布式系统或网络协议;其取值有如下三个:
- auth:仅认证(Authentication only)。只验证身份,不提供数据加密或完整性保护。
- auth-int:认证 + 完整性保护(Authentication + Integrity)。确保数据在传输过程中未被篡改,但不加密。
- auth-conf:认证 + 完整性 + 机密性(Authentication + Integrity + Confidentiality)。提供完整加密,确保数据不被窃听。 开发者需要根据自己集群的配置来设置该参数;
`