saltstack主机管理项目:计主机管理项目命令分发器(三)

一、开发目标命令格式如下:

 

二、目录结构

三、代码注解

01、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)
 

02、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
}  

03、 建了一个目录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")
 

04、plugins 建立一个目录创建两个类

1、 cmd.py 

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

2、state.py

from Arya.plugins import cmd,state

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

四、命令行运行截图

 

posted @ 2018-08-04 18:44  活的潇洒80  阅读(510)  评论(0编辑  收藏  举报