python3 saltstack api 接入

功能介绍

  • 使用python urllib模块,请求saltstack api
  • 针对saltstack api常用模块编写为函数,方便使用
  • saltstack api配置简单化

注意事项

  • 请保证自己的saltstack api是可以使用的,请在自己的salt服务器中使用以下命令
curl -k https://172.28.5.190:8000/login \
-H "Accept: application/x-yaml" \
-d username='saltapi' \
-d password='saltapi' \
-d eauth='pam'
  • 执行正常结果,主要是需要token
return:
- eauth: pam
  expire: 1542725811.402969
  perms:
  - .*
  - '@wheel'
  - '@runner'
  start: 1542682611.402966
  token: 541d1b86d29daaff1c1cbb8f01a454de0bf4cba3
  user: saltapi
  • 脚本文件目录
- salt_api
  - __init__.py
  - saltStack.py
  - saltDao.py
  - test.py

saltStack.py

#!/usr/bin/env python
# -*-coding:utf-8-*-
import urllib
import urllib.parse
import urllib.request
import ssl
import json

#: 解决saltstack api ssh连接报错
context = ssl._create_unverified_context()
ssl._create_default_https_context = ssl._create_unverified_context


class SaltAPI(object):
    __token_id = ''

    #: saltstackapi地址,请按照需求修改
    #: url后面不要带  /  
    def __init__(self):
        self.__url = 'https://172.28.5.190:8000'
        self.__user = 'saltapi'
        self.__password = 'saltapi'

    #: 获取请求成功参数token值
    def token_id(self):
        params = {'eauth': 'pam', 'username': self.__user, 'password': self.__password}
        encode_params = urllib.parse.urlencode(params).encode(encoding='utf-8')
        content = self.post_request(encode_params, prefix='/login')
        self.__token_id = content['return'][0]['token']

    #: 使用post请求,配置请求参数
    def post_request(self, params, prefix='/'):
        url = self.__url + prefix
        headers = {'X-Auth-Token': self.__token_id}
        req = urllib.request.Request(url, params, headers=headers)
        data = urllib.request.urlopen(req).read().decode("utf-8")
        content = json.loads(data)
        return content

    #: 获取各主机信息
    def salt_command(self, tgt, fun, arg=''):
        self.token_id()
        params = {'client': 'local'}
        try:
            if tgt and fun:
                if type(tgt) == list:
                    params['expr_form'] = 'list'
                    params['tgt'] = ','.join(tgt)
                else:
                    params['tgt'] = tgt
                params['fun'] = fun

            else:
                return "salt语法有误,请检查!"

            if arg:
                params['arg'] = arg

            encode_params = urllib.parse.urlencode(params).encode(encoding='utf-8')
            content = self.post_request(encode_params)
            return content
        except Exception as e:
            return e

saltDao.py

#!/usr/bin/env python
# -*-coding:utf-8-*-
# 需要写什么方法,可以根据我的语法继续编写,很方便
from sdk_api import saltStack


#: 获取Linux主机远程端口
def getHostSsh(saltIdList):
    salt_api = saltStack.SaltAPI()
    tgt = saltIdList
    fun = 'cmd.run'
    arg = "netstat -lnpt | grep sshd | grep -v 'tcp6' | awk '{print $4}' | awk -F':' '{print $2}'"
    data = salt_api.salt_command(tgt, fun, arg)
    return data['return'][0]


#: salt-minion主机连接测试
def getSaltTest(saltIdList):
    salt_api = saltStack.SaltAPI()
    tgt = saltIdList
    fun = 'test.ping'
    data = salt_api.salt_command(tgt, fun)
    return data['return'][0]


#: salt ganins信息获取
def getSaltGrains(saltIdList):
    salt_api = saltStack.SaltAPI()
    tgt = saltIdList
    fun = 'grains.items'
    data = salt_api.salt_command(tgt, fun)
    return data['return'][0]


#: salt获取磁盘信息
def getSaltDisk(saltIdList):
    salt_api = saltStack.SaltAPI()
    tgt = saltIdList
    fun = 'disk.usage'
    data = salt_api.salt_command(tgt, fun)
    return data['return'][0]


#: salt获取内存信息
def getSaltMem(saltIdList):
    salt_api = saltStack.SaltAPI()
    tgt = saltIdList
    fun = 'status.meminfo'
    data = salt_api.salt_command(tgt, fun)
    return data['return'][0]

test.py

#!/usr/bin/env python
# -*-coding:utf-8-*-
from sdk_api import saltDao

#: saltIdList 有两种选择
#: 1.列表   saltIdList=[]
#: 2.*      saltIdList="*"
saltIdList = ["tender", "salt-master"]
memory = saltDao.getSaltMem(saltIdList)
for saltId, saltJson in memory.items():
    print("saltId: %s" % saltId)
    for key, values in saltJson.items():
        print("\t%s: %s" % (key, values))

测试结果

saltId: tender
    WritebackTmp: {'value': '0', 'unit': 'kB'}
    SwapTotal: {'value': '2031612', 'unit': 'kB'}
    Active(anon): {'value': '61448', 'unit': 'kB'}
    SwapFree: {'value': '2031612', 'unit': 'kB'}
    KernelStack: {'value': '2592', 'unit': 'kB'}
    MemFree: {'value': '652804', 'unit': 'kB'}
    HugePages_Rsvd: {'value': '0'}
    Active(file): {'value': '120004', 'unit': 'kB'}
    NFS_Unstable: {'value': '0', 'unit': 'kB'}
    VmallocChunk: {'value': '34359566684', 'unit': 'kB'}
    Writeback: {'value': '0', 'unit': 'kB'}
    Inactive(file): {'value': '80904', 'unit': 'kB'}
    MemTotal: {'value': '1004112', 'unit': 'kB'}
    VmallocUsed: {'value': '162832', 'unit': 'kB'}
    DirectMap1G: {'value': '0', 'unit': 'kB'}
    HugePages_Free: {'value': '0'}
    AnonHugePages: {'value': '2048', 'unit': 'kB'}
    Inactive: {'value': '81276', 'unit': 'kB'}
    Active: {'value': '181452', 'unit': 'kB'}
    Inactive(anon): {'value': '372', 'unit': 'kB'}
    CommitLimit: {'value': '2533668', 'unit': 'kB'}
    Hugepagesize: {'value': '2048', 'unit': 'kB'}
    Cached: {'value': '74144', 'unit': 'kB'}
    SwapCached: {'value': '0', 'unit': 'kB'}
    VmallocTotal: {'value': '34359738367', 'unit': 'kB'}
    Shmem: {'value': '384', 'unit': 'kB'}
    Dirty: {'value': '4', 'unit': 'kB'}
    Mapped: {'value': '11164', 'unit': 'kB'}
    SUnreclaim: {'value': '26260', 'unit': 'kB'}
    Unevictable: {'value': '0', 'unit': 'kB'}
    SReclaimable: {'value': '19776', 'unit': 'kB'}
    Slab: {'value': '46036', 'unit': 'kB'}
    DirectMap2M: {'value': '1040384', 'unit': 'kB'}
    HugePages_Surp: {'value': '0'}
    Bounce: {'value': '0', 'unit': 'kB'}
    HugePages_Total: {'value': '0'}
    AnonPages: {'value': '59408', 'unit': 'kB'}
    PageTables: {'value': '3936', 'unit': 'kB'}
    HardwareCorrupted: {'value': '0', 'unit': 'kB'}
    DirectMap4k: {'value': '8192', 'unit': 'kB'}
    Mlocked: {'value': '0', 'unit': 'kB'}
    Buffers: {'value': '127144', 'unit': 'kB'}
    Committed_AS: {'value': '253820', 'unit': 'kB'}
saltId: salt-master
    WritebackTmp: {'value': '0', 'unit': 'kB'}
    SwapTotal: {'value': '2097148', 'unit': 'kB'}
    Active(anon): {'value': '244896', 'unit': 'kB'}
    SwapFree: {'value': '1541672', 'unit': 'kB'}
    KernelStack: {'value': '7488', 'unit': 'kB'}
    MemFree: {'value': '105100', 'unit': 'kB'}
    HugePages_Rsvd: {'value': '0'}
    Active(file): {'value': '71508', 'unit': 'kB'}
    NFS_Unstable: {'value': '0', 'unit': 'kB'}
    VmallocChunk: {'value': '34359310332', 'unit': 'kB'}
    CmaFree: {'value': '0', 'unit': 'kB'}
    Writeback: {'value': '0', 'unit': 'kB'}
    Inactive(file): {'value': '48576', 'unit': 'kB'}
    MemTotal: {'value': '997956', 'unit': 'kB'}
    VmallocUsed: {'value': '177400', 'unit': 'kB'}
    DirectMap1G: {'value': '0', 'unit': 'kB'}
    HugePages_Free: {'value': '0'}
    AnonHugePages: {'value': '57344', 'unit': 'kB'}
    Inactive: {'value': '360432', 'unit': 'kB'}
    Active: {'value': '316404', 'unit': 'kB'}
    Inactive(anon): {'value': '311856', 'unit': 'kB'}
    CommitLimit: {'value': '2596124', 'unit': 'kB'}
    Hugepagesize: {'value': '2048', 'unit': 'kB'}
    Cached: {'value': '130104', 'unit': 'kB'}
    SwapCached: {'value': '44408', 'unit': 'kB'}
    VmallocTotal: {'value': '34359738367', 'unit': 'kB'}
    CmaTotal: {'value': '0', 'unit': 'kB'}
    Shmem: {'value': '10060', 'unit': 'kB'}
    Dirty: {'value': '12', 'unit': 'kB'}
    Mapped: {'value': '26652', 'unit': 'kB'}
    SUnreclaim: {'value': '75284', 'unit': 'kB'}
    Unevictable: {'value': '0', 'unit': 'kB'}
    SReclaimable: {'value': '49340', 'unit': 'kB'}
    MemAvailable: {'value': '122132', 'unit': 'kB'}
    Slab: {'value': '124624', 'unit': 'kB'}
    DirectMap2M: {'value': '972800', 'unit': 'kB'}
    HugePages_Surp: {'value': '0'}
    Bounce: {'value': '0', 'unit': 'kB'}
    HugePages_Total: {'value': '0'}
    AnonPages: {'value': '517560', 'unit': 'kB'}
    PageTables: {'value': '17264', 'unit': 'kB'}
    HardwareCorrupted: {'value': '0', 'unit': 'kB'}
    DirectMap4k: {'value': '75648', 'unit': 'kB'}
    Mlocked: {'value': '0', 'unit': 'kB'}
    Buffers: {'value': '12', 'unit': 'kB'}
    Committed_AS: {'value': '3229088', 'unit': 'kB'}

你可能感兴趣的:(python3 saltstack api 接入)