Python2调用Salt API

有些话、适合烂在心里 提交于 2020-08-10 06:46:13

 

#!/usr/bin/env python
#coding=utf-8
#For Python2
import urllib,urllib2,json,sys,importlib,argparse
reload(sys)
sys.setdefaultencoding('utf-8')


class saltAPI():

    def __init__(self):
        self.url = 'http://10.10.2.11:8000'
        self.data = {'username' : 'saltapi',
                     'password' : 'saltapi',
                     'eauth' : 'pam'}
        self.headers = {'User-Agent':'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
        self.token = self.get_token()
        self.headers['X-Auth-Token'] = self.token

        # self.headers['Accept'] = 'application/x-yaml'
        # self.headers['Content-Type'] = 'application/json'
    #获取token
    def get_token(self):
        postdata = urllib.urlencode(self.data).encode('utf8')
        content = self.post_request('/login',postdata)
        try:
            token = content['return'][0]['token']
            return token
        except Exception as ErrorMsg:
            print(ErrorMsg)

    #发送post
    def post_request(self,prefix='/',postdata=None):
        try:
            request = urllib2.Request(self.url+ prefix,postdata,headers=self.headers)
            reponse = urllib2.urlopen(request).read()
            content  = json.loads(reponse.decode('utf8'))
            return content
        except Exception as ErrorMsg:
            print(ErrorMsg)
            exit()

    
    def SaltCmd_Exec(self,tgt,fun='cmd.run',expr_form='glob',arg=None,**kwargs):
        #通过json格式提交参数,需要指定Content-Type,用户自行选择是否指定Shell=PowerShell,可以运行grains.item、cmd.run、cmd.script等命令
        #多台主机同时执行cmd.script,使用expr_form=list
        self.headers['Content-Type'] = 'application/json'
        # params = [{'client': 'local', 'tgt': tgt, 'fun': fun,'expr_form':expr_form,'arg':arg ,'kwarg':kwargs }]
        params = {'client': 'local', 'tgt': tgt, 'fun': fun,'expr_form':expr_form,'arg':arg }
        #检查kwargs是否为空,不为空则将其加入到params中
        kwargs2 = {}
        if kwargs :
            for k,v in kwargs.items():
                if kwargs[k] != None:
                    kwargs2[k] = kwargs[k]
        if kwargs2 :
        #     params = dict(list(params.items())+list(kwargs2.items()))
            params['kwarg'] = kwargs2
        # print(params)
        #json.loads() transform str to dict;json.dumps() transform dict to str.
        # obj = bytes(json.dumps([params])) #Python2,可用
        obj = json.dumps([params]).encode('utf8') #Python2,可用
        ret = self.post_request(prefix='/',postdata=obj)
        return ret
        
    def listkeys(self):
        params = {'client':'wheel','fun':'key.list_all'}
        obj = urllib.urlencode(params).encode('UTF8')
        ret = self.post_request(prefix='/',postdata=obj)
        print(ret)

    def AuthTest(self):
        print(self.headers)


#为运行grins.items命令的返回结果进行处理
def res_proc_grainsitem(data):
    for k,v in data.items():
        d2 = data[k]
        d2['biosversion']
        d2['biosversion'].find('Hyper-V')
        if d2['biosversion'].find('Hyper-V') >= 0:
            sn = 'HV00000'
        else:
            sn  = d2['serialnumber']
        print(d2['id'],d2['host'],d2['windowsdomain'],d2['manufacturer'],d2['productname'],sn,d2['virtual'],d2['cpu_model'],d2['num_cpus'],d2['mem_total'],d2['os'],d2['osfullname'],d2['kernelrelease'])


###################################### Main Start #######################################
parser = argparse.ArgumentParser(description='Input args')
parser.add_argument('--host',dest='host',type=str,help='Input Server IP')
parser.add_argument('--cmd_salt',dest='cmd_salt',type=str,help='Input Salt Command')
parser.add_argument('--cmd_srv',dest='cmd_srv',type=str,help='Input Server Command')
parser.add_argument('--spt_args',dest='spt_args',type=str,help='Input Server Script Args')
parser.add_argument('--shell',dest='shell',type=str,help='Specify an alternate shell')
args=parser.parse_args()
# parser.print_help()

sapi= saltAPI()
# sapi.AuthTest()

# 单台主机执行命令使用glob,多台主机执行命令使用list参数
if args.host.find(',') >= 0:
    exprform = 'list'
else:
    exprform = 'glob'
cmdExec = sapi.SaltCmd_Exec(args.host,args.cmd_salt,exprform,args.cmd_srv,args=args.spt_args,shell=args.shell)


if args.cmd_salt == 'grains.items' :
    res_proc_grainsitem(cmdExec['return'][0])
elif args.cmd_salt == 'cmd.run' :
    dd3 = cmdExec['return'][0]
    for k,v in dd3.items():
        print(k,dd3[k])
elif args.cmd_salt == 'cmd.script' :
    dd3 = cmdExec['return'][0]
    for k,v in dd3.items():
        print(k,dd3[k]['stdout'])
else :
    print(cmdExec)

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!