saltstack主機管理項目:計主機管理項目命令分發器(三)

1、開發目標命令格式以下:

 

2、目錄結構

3、代碼註解

0一、salt.py 只是一個入口,沒幹什麼事情

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:luoahong


import os, sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Stark.settings")
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    # print(BASE_DIR)
    sys.path.append(BASE_DIR)
    from Arya.action_list import actions
    from Arya.backends.utils import ArgvManagement

    obj = ArgvManagement(sys.argv)
 

0二、action_list.py 路由分發器

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:luoahong

from Arya.plugins import cmd,state
actions = {
    'cmd': cmd.CMD,
    'state':state.State
}  

0三、 建了一個目錄backends目錄下 建立一個utils.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:luoahong

from Arya import action_list
import django
django.setup()

from Stark import settings
from Arya import models
class ArgvManagement(object):
    '''
    接收用戶指令並分配到相應模塊
    '''
    def __init__(self,argvs):
        self.argvs = argvs
        self.argv_parse()

    def help_msg(self):
        print("Available modules:")
        for registered_module in action_list.actions:
            print("  %s" % registered_module)
        exit()
    def argv_parse(self):
        print(self.argvs)
        if len(self.argvs) <2:
            self.help_msg()
        module_name = self.argvs[1]
        if '.' in module_name:
            mod_name,mod_method = module_name.split('.')
            module_instance  = action_list.actions.get(mod_name)
            if module_instance:#matched
               module_instance(self.argvs,models,settings)

        else:
            exit("invalid module name argument")
 

0四、plugins 創建一個目錄建立兩個類

一、 cmd.py 

from Arya.backends.base_module import BaseSaltModule
class CMD(BaseSaltModule):
    print('in cmd module ')

二、state.py

from Arya.plugins import cmd,state

from Arya.backends.base_module import BaseSaltModule
class State(BaseSaltModule):
    print('in state module ')

4、命令行運行截圖

相關文章
相關標籤/搜索