Python實現Kerberos用戶的增刪改查操作
1、首先模擬python類似shell命令行操作的接口:
python安裝subprocess(本地)、paramiko(SSH遠程)
#-*- coding: UTF-8 -*-
#!/usr/bin/python
import os, sys
import subprocess
import paramiko
import settings
class RunCmd(object):
def __init__(self):
self.cmd = 'ls'
@staticmethod
def local_run(cmd):
print('start executing...')
print('cmd is -------> %s' % str(cmd))
s = subprocess.Popen(str(cmd), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = s.communicate()
print("outinfo is -------> %s" % out)
print("errinfo is -------> %s" % err)
print('finish executing...')
print('result:------> %s' % s.returncode)
return s.returncode
@staticmethod
def remote_run(host, username, password, port, cmd):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=host, port=int(port), username=username, password=password, timeout=5)
stdin, stdout, stderr = client.exec_command(cmd)
result = stdout.read()
client.close()
return result
@staticmethod
def krb_run(cmd):
print('krb_run start...')
print('cmd is -------> %s' % str(cmd))
result = RunCmd.remote_run(settings.KRB_HOST, settings.USERNAME, settings.PASSWORD, settings.PORT, cmd)
print('result:------> %s' % result)
print('krb_run finish...')
return result
2、Kerberos常用的命令操作封裝成接口,其他簡單。但需要交互的是刪除 principal
def delete_user(self, username):
cmd = r"""
expect -c "
set timeout 1;
spawn kadmin.local -q \"delete_principal {principal}\" ;
expect yes/no {{ send \"yes\r\" }} ;
expect *\r
expect \r
expect eof
"
""".format(principal=username)
RunCmd.krb_run(cmd)
補充知識:python操作有Kerberos認證的hive庫
之前訪問hive都比較簡單,直接用pyhive連接即可。
但是最近遇到了一個問題,hive有了Kerberosren認證。
最終經過各種嘗試和靈感迸發(fā),終于解決了這個問題,遂記錄之。
代碼
from pyhive.hive import connect
con = connect(host='XXXX',port=10000,auth='KERBEROS',kerberos_service_name="hive")
cursor = con.cursor()
cursor.execute('select * from tmp.pricing_calculate_result_spark where time_id="201907171355" limit 10,1')
datas = cursor.fetchall()
print(datas)
cursor.close()
con.close()
端口和ip都換成自己的,auth和kerberos_service_name不要改
運行效果

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章
在vscode使用jupyter notebook出現bug及解決
這篇文章主要介紹了在vscode使用jupyter notebook出現bug及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06
解決pycharm debug時界面下方不出現step等按鈕及變量值的問題
這篇文章主要介紹了解決pycharm debug時界面下方不出現step等按鈕及變量值的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06

