SaltApi

class SaltAPI(object):

    def __init__(self, url=None, user=None, password=None):
        self.__url = settings.SALT_API_URL
        self.__user = settings.SALT_API_USER
        self.__password = settings.SALT_API_PASSWORD
        self.__headers = {'Accept': 'application/json', 'Content-type': 'application/json', 'Connection': 'close'}
        self.__data = {'client': 'local'}
        self.__token = None

    def get_token(self):
        """
        用戶登陸和獲取token
        :return:
        """
        params = {'eauth': 'pam', 'username': self.__user, 'password': self.__password}
        content = self.postRequest(params, self.__headers, prefix='login')
        try:
            self.__token = content['return'][0]['token']
            self.__headers['X-Auth-Token'] = self.__token
        except Exception as e:
            logger.error(e)
            return content

    def get_grains(self, target=None):
        """
        獲取系統(tǒng)基礎(chǔ)信息
        :return:
        """
        data = copy.deepcopy(self.__data)
        if target:
            data['tgt'] = target
        else:
            data['tgt'] = '*'
        data['fun'] = 'grains.items'
        content = self.postRequest(data, self.__headers)
        try:
            return content['return'][0]
        except Exception as e:
            logger.error(e)
            return content

    def get_auth_keys(self):
        """
        獲取所有已認(rèn)證的主機(jī)
        :return:
        """
        data = copy.deepcopy(self.__data)
        data['client'] = 'wheel'
        data['fun'] = 'key.list_all'
        content = self.postRequest(data, self.__headers)
        try:
            return content['return'][0]['data']['return']['minions']
        except Exception as e:
            logger.error(e)
            return content

    def get_minion_status(self):
        """
        獲取所有主機(jī)的連接狀態(tài)
        :return:
        """
        data = copy.deepcopy(self.__data)
        data['client'] = 'runner'
        data['fun'] = 'manage.status'
        content = self.postRequest(data, self.__headers)
        try:
            return content['return'][0]
        except Exception as e:
            logger.error(e)
            return content

    def delete_key(self, minion=None):
        '''
        刪除指定主機(jī)的認(rèn)證信息
        '''
        if not minion:
            return {'success': False, 'msg': 'minion-id is none'}

        data = copy.deepcopy(self.__data)
        data['client'] = 'wheel'
        data['fun'] = 'key.delete'
        data['match'] = minion
        content = self.postRequest(data, self.__headers)

        try:
            return {'success': content['return'][0]['data']['success']}
        except Exception as e:
            logger.error(e)
            return content

    def minion_alive(self, minion=None):
        '''
        Minion主機(jī)存活檢測
        '''
        data = copy.deepcopy(self.__data)
        if minion:
            data['tgt'] = minion
            result = {minion: False}
        else:
            data['tgt'] = '*'
            result = {'success': False}
        data['fun'] = 'test.ping'
        content = self.postRequest(data, self.__headers)
        try:
            return content['return'][0]
        except Exception as e:
            logger.error(e)
            return result

    def passwd(self, target=None, user=None, password=None, pass_length=16):
        """
        修改密碼
        :param target: 目標(biāo)客戶端
        :param user: 目標(biāo)客戶端的系統(tǒng)用戶名
        :param password: 新的密碼,必須大于等于12位
        :return:
        """
        if not target:
            return {'success': False, 'msg': 'target is none.'}, password
        if not user:
            return {'success': False, 'msg': 'user is none.'}, password
        if password:
            if len(password) < pass_length:
                return {'success': False, 'msg': 'password must be greater than or equal to {} bits.'.format(pass_length)}, password

            if password.isalpha() or password.isdigit() or password.islower() or password.isupper():
                return {'success': False, 'msg': 'password must be have lowercase, uppercase and digit.'}, password
        else:
            password = make_pass(pass_length)

        _password = crypt(password, 'cmdb')
        try:
            self.cmd(target=target, arg='usermod -p "{}" {}'.format(_password, user))
        except Exception as e:
            logger.debug(e)

        res = {'success': True,
               'msg': 'Changing password for user {}.all authentication tokens updated successfully.'.format(user),
        }

        return res, password

    def get_users(self, target=None):
        """
        獲取系統(tǒng)用戶
        :param target: 目標(biāo)客戶端
        :return:
        """
        if not target: return {'success': False, 'msg': 'target is none.'}
        content = self.cmd(target=target, arg="grep /bin/bash /etc/passwd|awk -F ':' '{print $1}'")
        return content

    def run_cmdb_agent(self, target=None):
        """
        運(yùn)行cmdb agent
        :param target: 目標(biāo)客戶端
        :return:
        """
        if not target:
            return {'success': False, 'msg': 'target is none.'}
        content = self.cmd(target=target, arg="/etc/init.d/vmagent")
        return content

    def cmd(self, target=None, fun='cmd.run', arg=None, async=False):
        """
        遠(yuǎn)程執(zhí)行任務(wù)
        :param target: 目標(biāo)客戶端,為空return False
        :param fun: 模塊
        :param arg: 參數(shù),可為空
        :param async: 異步執(zhí)行,默認(rèn)非異步
        :return:
        """
        data = copy.deepcopy(self.__data)
        if not target:
            return {'success': False, 'msg': 'target is none'}
        if arg:
            data['arg'] = arg
        if async:
            data['client'] = 'local_async'
        data['tgt'] = target
        data['fun'] = fun

        content = self.postRequest(data, self.__headers)
        try:
            return content['return'][0]
        except Exception as e:
            logger.error(e)
            return content

    def jobs(self, fun=None, jid=None):
        """
        任務(wù)
        :param fun: active,detail
        :param jid: Job ID
        :return:
        """
        data = {'client': 'runner'}
        if fun == 'active':
            data['fun'] = 'jobs.active'
        elif fun == 'detail':
            if not jid: return {'success': False, 'msg': 'job id is none'}
            data['fun'] = 'jobs.lookup_jid'
            data['jid'] = jid
        else:
            return {'success': False, 'msg': 'fun is active or detail'}
        content = self.postRequest(data, self.__headers)
        try:
            return content['return'][0]
        except Exception as e:
            logger.error(e)
            return content

    def postRequest(self, data, headers, prefix=None):
        if prefix:
            url = '{}/{}'.format(self.__url, prefix)
        else:
            url = self.__url
        try:
            s = requests.Session()
            s.mount('https://', HTTPAdapter(max_retries=10))
            ret = s.post(url, data=json.dumps(data), headers=headers, verify=False, timeout=(30, 60))
            if ret.status_code == 401:
                logger.error('Salt Unauthorized')
                return {'return': [{'success': False, 'msg': 'Salt Unauthorized'}]}
            elif ret.status_code == 200:
                return ret.json()
            else:
                return {'return': [{'success': False, 'msg': ret.content}]}
        except Exception as e:
            logger.error(e)
            return {'return': [{'success': False, 'msg': e}]}

    def get_pre_auth_keys(self):
        """
        獲取未授權(quán)的salt主機(jī)
        :return:
        """
        data = copy.deepcopy(self.__data)
        data['client'] = 'wheel'
        data['fun'] = 'key.list_all'
        content = self.postRequest(data, self.__headers)
        try:
            return content['return'][0]['data']['return']['minions_pre']
        except Exception as e:
            logger.error(e)
            return content

    def accept_key(self, minion):
        """
        授權(quán)salt主機(jī)
        :param minion:
        :return:
        """
        data = copy.deepcopy(self.__data)
        data['client'] = 'wheel'
        data['fun'] = 'key.accept'
        data['match'] = minion
        content = self.postRequest(data, self.__headers)

        try:
            return {'success': content['return'][0]['data']['success']}
        except Exception as e:
            logger.error(e)
            return content

    def salt_alive(self, tgt):
        '''
        Minion主機(jī)存活檢測
        '''
        data = copy.deepcopy(self.__data)
        if tgt:
            data['tgt'] = tgt
        else:
            data['tgt'] = '*'
        data['fun'] = 'test.ping'
        content = self.postRequest(data, self.__headers)
        try:
            return content['return'][0]
        except Exception as e:
            logger.error(e)
            return None

    def getRequest(self, headers, prefix=None):
        if prefix:
            url = '{}/{}'.format(self.__url, prefix)
        else:
            url = self.__url
        try:
            s = requests.Session()
            s.mount('https://', HTTPAdapter(max_retries=10))
            ret = s.get(url, headers=headers, verify=False, timeout=(30, 60))
            if ret.status_code == 401:
                logger.error('Salt Unauthorized')
                return {'return': [{'success': False, 'msg': 'Salt Unauthorized'}]}
            elif ret.status_code == 200:
                return ret.json()
        except Exception as e:
            logger.error(e)
            return {'return': [{'success': False, 'msg': e}]}

    def salt_runner_requests(self, jid):
        '''
        通過jid獲取執(zhí)行結(jié)果
        '''

        content = self.getRequest(prefix='/jobs/{}'.format(jid), headers=self.__headers)
        return content

    def salt_runner(self, jid):
        """
        獲取job的執(zhí)行結(jié)果
        :param jid:
        :return:
        """
        data = copy.deepcopy(self.__data)
        data['client'] = 'runner'
        data['fun'] = 'jobs.lookup_jid'
        data['jid'] = jid
        content = self.postRequest(data, self.__headers)
        return content

    def salt_running_jobs(self):
        """
        獲取在運(yùn)行的job
        :return:
        """
        data = copy.deepcopy(self.__data)
        data['clent'] = 'runner'
        data['fun'] = 'jobs.active'
        content = self.postRequest(data, self.__headers)

        try:
            return content['return'][0]
        except Exception as e:
            logger.error(e)
            return content

    def remote_execution(self, tgt, fun, arg, expr_form):
        """
        異步執(zhí)行遠(yuǎn)程指令
        :param tgt:
        :param fun:
        :param arg:
        :param expr_form:
        :return:
        """
        data = copy.deepcopy(self.__data)
        data['client'] = 'local_async'
        data['tgt'] = tgt
        data['fun'] = fun
        data['arg'] = arg
        data['expr_form'] = expr_form

        content = self.postRequest(data, self.__headers)

        try:
            return content['return'][0]['jid']
        except Exception as e:
            logger.error(e)
            return content

    def remote_module(self, tgt, fun, arg, kwarg, expr_form, client='local_async'):
        """
        異步部署模塊
        :param tgt:
        :param fun:
        :param arg:
        :param kwarg:
        :param expr_form:
        :param client local_async 異步 or local 同步
        :return:
        """
        data = copy.deepcopy(self.__data)
        data['client'] = client
        data['tgt'] = tgt
        data['fun'] = fun
        data['arg'] = arg
        data['kwarg'] = {"pillar": kwarg}
        data['expr_form'] = expr_form

        content = self.postRequest(data, self.__headers)
        if client == "local_async":
            try:
                return content['return'][0]['jid']
            except Exception as e:
                logger.error(e)
                return content
        else:
            return content

    def remote_localexec(self, tgt, fun, arg, expr_form):
        data = copy.deepcopy(self.__data)
        data['client'] = 'local'
        data['tgt'] = tgt
        data['fun'] = fun
        data['arg'] = arg
        data['expr_form'] = expr_form

        content = self.postRequest(data, self.__headers)

        try:
            return content['return'][0]['jid']
        except Exception as e:
            logger.error(e)
            return content

    def salt_state(self, tgt, arg, expr_form):
        """
        sls文件
        :param tgt:
        :param arg:
        :param expr_form:
        :return:
        """

        data = copy.deepcopy(self.__data)
        data['client'] = 'local'
        data['tgt'] = tgt
        data['fun'] = 'state.sls'
        data['arg'] = arg
        data['expr_form'] = expr_form
        content = self.postRequest(data, self.__headers)

        try:
            return content['return'][0]
        except Exception as e:
            logger.error(e)
            return content

    def project_manage(self, tgt, fun, arg1, arg2, arg3, arg4, arg5, expr_form):
        """
        項(xiàng)目管理
        :param tgt:
        :param fun:
        :param arg1:
        :param arg2:
        :param arg3:
        :param arg4:
        :param arg5:
        :param expr_form:
        :return:
        """
        data = copy.deepcopy(self.__data)

        data['client'] = 'local'
        data['tgt'] = tgt
        data['fun'] = fun
        data['arg'] = arg1
        data['arg2'] = arg2
        data['arg3'] = arg3
        data['arg4'] = arg4
        data['arg5'] = arg5
        data['expr_form'] = expr_form
        content = self.postRequest(data, self.__headers)

        try:
            return content['return'][0]
        except Exception as e:
            logger.error(e)
            return content

    def file_copy(self, tgt, fun, arg1, arg2, expr_form):
        """
        文件copy
        :param tgt: ./
        :param fun: file.manager
        :param arg1:
        :param arg2:
        :param expr_form:
        :return:
        """
        data = copy.deepcopy(self.__data)

        data['client'] = 'local'
        data['tgt'] = tgt
        data['fun'] = fun
        data['arg'] = arg1
        data['arg2'] = arg2
        data['expr_form'] = expr_form
        content = self.postRequest(data, self.__headers)

        try:
            return content['return'][0]
        except Exception as e:
            logger.error(e)
            return content

    def file_bak(self, tgt, fun, arg, expr_form):
        """
        文件備份到master上
        :param tgt:
        :param fun:
        :param arg:
        :param expr_form:
        :return:
        """
        data = copy.deepcopy(self.__data)

        data['client'] = 'local'
        data['tgt'] = tgt
        data['fun'] = fun
        data['expr_form'] = expr_form
        content = self.postRequest(data, self.__headers)

        try:
            return content['return'][0]
        except Exception as e:
            logger.error(e)
            return content

    def file_manage(self, tgt, fun, arg1, arg2, arg3, expr_form):
        """
        文件回滾
        :param tgt:
        :param fun:
        :param arg1:
        :param arg2:
        :param arg3:
        :param expr_form:
        :return:
        """
        data = copy.deepcopy(self.__data)

        data['client'] = 'local'
        data['tgt'] = tgt
        data['fun'] = fun
        data['arg'] = arg1
        data['arg2'] = arg2
        data['arg3'] = arg3
        data['expr_form'] = expr_form
        content = self.postRequest(data, self.__headers)

        try:
            return content['return'][0]
        except Exception as e:
            logger.error(e)
            return content

    def remote_server_info(self, tgt, fun):
        """
        獲取遠(yuǎn)程主機(jī)信息
        :param tgt:
        :param fun:
        :return:
        """
        data = copy.deepcopy(self.__data)

        data['client'] = 'local'
        data['tgt'] = tgt
        data['fun'] = fun
        content = self.postRequest(data, self.__headers)

        try:
            return content['return'][0][tgt]
        except Exception as e:
            logger.error(e)
            return content

    def get_list_job(self):
        """
        獲取正在運(yùn)行的job
        :return:
        """
        data = copy.deepcopy(self.__data)
        data['client'] = 'runner'
        data['fun'] = 'jobs.list_jobs'
        content = self.postRequest(data, self.__headers)
        ret = content['return'][0]
        return [{k: v} for k, v in zip(ret.keys(), ret.values())]

    def get_running_job(self):
        """
        獲取正在運(yùn)行的job
        :return:
        """
        data = copy.deepcopy(self.__data)
        data['client'] = 'runner'
        data['fun'] = 'jobs.active'
        content = self.postRequest(data, self.__headers)

        ret = content['return'][0]
        return [{k: v} for k, v in zip(ret.keys(), ret.values())]

    def term_running_job(self, jid):
        """
        終止正在運(yùn)行的job
        :return:
        """
        data = copy.deepcopy(self.__data)
        data['tgt'] = '*'
        data['client'] = 'local'
        data['fun'] = 'saltutil.term_job'
        data['arg'] = jid

        content = self.postRequest(data, self.__headers)

        return content['return'][0]

    def get_job_info(self, jid):
        """
        獲取正在運(yùn)行的job
        :return:
        """
        data = copy.deepcopy(self.__data)
        data['client'] = 'runner'
        data['fun'] = 'jobs.lookup_jid'
        data['arg'] = jid

        content = self.postRequest(data, self.__headers)

        return content

    def check_job_result(self, jid):
        """
        檢查job是否已經(jīng)運(yùn)行完成
        :return:
        """
        data = copy.deepcopy(self.__data)
        data['client'] = 'runner'
        data['fun'] = 'jobs.exit_success'
        data['arg'] = jid

        content = self.postRequest(data, self.__headers)

        return content

使用方式

client = SaltAPI()
client.get_token()
然后用client調(diào)用方法

異步執(zhí)行模塊部署

入?yún)?module.module_path # 模塊路徑
  "tgt_list": [
        "SHTL00706921"
    ],
    "arg": "init.6_env_init"
expr_form = 'list'
調(diào)用并返回jid
jid = sapi.remote_module(tgt_select, 'state.sls', 'module.{}.{}'.format(module.module_path, module.module),
                                     {'SALTSRC': 'module/{}'.format(module.module_path)}, expr_form)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末涡真,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子组砚,更是在濱河造成了極大的恐慌拆挥,老刑警劉巖畔咧,帶你破解...
    沈念sama閱讀 219,589評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件娶靡,死亡現(xiàn)場離奇詭異牧牢,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)姿锭,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,615評論 3 396
  • 文/潘曉璐 我一進(jìn)店門塔鳍,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人艾凯,你說我怎么就攤上這事献幔《” “怎么了趾诗?”我有些...
    開封第一講書人閱讀 165,933評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長蹬蚁。 經(jīng)常有香客問我恃泪,道長,這世上最難降的妖魔是什么犀斋? 我笑而不...
    開封第一講書人閱讀 58,976評論 1 295
  • 正文 為了忘掉前任贝乎,我火速辦了婚禮,結(jié)果婚禮上叽粹,老公的妹妹穿的比我還像新娘览效。我一直安慰自己,他們只是感情好虫几,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,999評論 6 393
  • 文/花漫 我一把揭開白布锤灿。 她就那樣靜靜地躺著,像睡著了一般辆脸。 火紅的嫁衣襯著肌膚如雪但校。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,775評論 1 307
  • 那天啡氢,我揣著相機(jī)與錄音状囱,去河邊找鬼术裸。 笑死,一個胖子當(dāng)著我的面吹牛亭枷,可吹牛的內(nèi)容都是我干的袭艺。 我是一名探鬼主播,決...
    沈念sama閱讀 40,474評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼奶栖,長吁一口氣:“原來是場噩夢啊……” “哼匹表!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起宣鄙,我...
    開封第一講書人閱讀 39,359評論 0 276
  • 序言:老撾萬榮一對情侶失蹤袍镀,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后冻晤,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體苇羡,經(jīng)...
    沈念sama閱讀 45,854評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,007評論 3 338
  • 正文 我和宋清朗相戀三年鼻弧,在試婚紗的時候發(fā)現(xiàn)自己被綠了设江。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,146評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡攘轩,死狀恐怖叉存,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情度帮,我是刑警寧澤歼捏,帶...
    沈念sama閱讀 35,826評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站笨篷,受9級特大地震影響瞳秽,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜率翅,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,484評論 3 331
  • 文/蒙蒙 一练俐、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧冕臭,春花似錦腺晾、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,029評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至念颈,卻和暖如春泉粉,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,153評論 1 272
  • 我被黑心中介騙來泰國打工嗡靡, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留跺撼,地道東北人。 一個月前我還...
    沈念sama閱讀 48,420評論 3 373
  • 正文 我出身青樓讨彼,卻偏偏與公主長得像歉井,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子哈误,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,107評論 2 356

推薦閱讀更多精彩內(nèi)容

  • 最近再看阮一峰的一篇博客提到了一本書《Software Architecture Patterns》(PDF),寫...
    卓_然閱讀 7,778評論 0 22
  • 先保存起來免得地址失效https://nqdeng.github.io/7-days-nodejs/#6[http...
    Iterate閱讀 1,078評論 0 10
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理哩至,服務(wù)發(fā)現(xiàn),斷路器蜜自,智...
    卡卡羅2017閱讀 134,672評論 18 139
  • 本文是基于“微服務(wù)架構(gòu)設(shè)計(jì)模式”這本書的總結(jié)和提煉菩貌,將其中的關(guān)鍵知識點(diǎn)結(jié)合個人的開發(fā)實(shí)踐進(jìn)行結(jié)合提煉,并對部分話題...
    彥幀閱讀 4,230評論 1 2
  • 今天感恩節(jié)哎重荠,感謝一直在我身邊的親朋好友箭阶。感恩相遇!感恩不離不棄戈鲁。 中午開了第一次的黨會仇参,身份的轉(zhuǎn)變要...
    迷月閃星情閱讀 10,567評論 0 11