salt-api 使用

   这点时间研究运维自动化,研究到salt-api部分遇到了很多坑,这里记录一下,前面的陆续补上。

1、进程正题,步骤开始:   

cd /etc/yum.repos.d/ && wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
rpm -ivh epel-release-6-8.noarch.rpm
yum -y install kernel-firmware kernel-headers perf e2fsprogs
rpm -ivh libyaml-0.1.3-1.4.el6.x86_64.rpm 
rpm -ivh PyYAML-3.10-3.1.el6.x86_64.rpm 
yum -y install salt-master salt-api 

2、

#安装pip:
wget https://pypi.python.org/packages/source/p/pip/pip-1.5.6.tar.gz#md5=01026f87978932060cc86c1dc527903e --no-check-certificate
tar xvfz pip-1.5.6.tar.gz
cd pip-1.5.6
python setup.py build && python setup.py install && pip freeze
 
 
#使用pip安装cherrypy:
pip install cherrypy==3.2.3

3、安装openssl证书,因为salt-api是基于证书的,目录不要给错:

[root@www tmp]# cd /etc/pki/tls/certs

[root@www certs]# make testcert 

umask 77 ; \

        /usr/bin/openssl genrsa -aes128 2048 > /etc/pki/tls/private/localhost.key

Generating RSA private key, 2048 bit long modulus

..............................................................................................................................................+++

........................................................+++

e is 65537 (0x10001)

Enter pass phrase:               #输入6位以上的秘钥  

Verifying - Enter pass phrase:    #再次输入

umask 77 ; \

        /usr/bin/openssl req -utf8 -new -key /etc/pki/tls/private/localhost.key -x509 -days 365 -out /etc/pki/tls/certs/localhost.crt -set_serial 0

Enter pass phrase for /etc/pki/tls/private/localhost.key:    #再次输入

You are about to be asked to enter information that will be incorporated

into your certificate request.

What you are about to enter is what is called a Distinguished Name or a DN.

There are quite a few fields but you can leave some blank

For some fields there will be a default value,

If you enter ‘.‘, the field will be left blank.

-----

Country Name (2 letter code) [XX]:CN

State or Province Name (full name) []:nanning

Locality Name (eg, city) [Default City]:ninning

Organization Name (eg, company) [Default Company Ltd]:

Organizational Unit Name (eg, section) []:

Common Name (eg, your name or your server‘s hostname) []:

Email Address []:18878774260@163.com


[root@www certs]# cd ../private/

[root@www private]# openssl rsa -in localhost.key -out localhost_nopass.key

Enter pass phrase for localhost.key:

writing RSA key


建立登录的账号和密码:

[root@www private]# useradd -M -s /sbin/nologin xiaoluo

[root@www private]# passwd xiaoluo


#salt master配置文件:/etc/salt/master 
#取消注释
default_include: master.d/*.conf
mkdir -p /etc/salt/master.d


#saltstack服务端配置:
[root@localhost ~]# cat /etc/salt/master.d/api.conf 
rest_cherrypy:
  port: 8888
  ssl_crt: /etc/pki/tls/certs/localhost.crt
  ssl_key: /etc/pki/tls/private/localhost_nopass.key
[root@localhost ~]# cat /etc/salt/master.d/eauth.conf 
external_auth:
  pam:
    xiaoluo:
      - .*
      ‘@wheel‘
      ‘@runner‘
  
#重启salt-master和salt-api服务: 
[root@mail ~]# /etc/init.d/salt-master restart
Stopping salt-master daemon:                               [FAILED]
Starting salt-master daemon:                               [  OK  ]


登录获取token:

[root@mail salt]# curl -k https://192.168.10.205:8888/login -H "Accept: application/x-yaml"  -d username=‘xiaoluo‘ -d password=‘123456‘ -d eauth=‘pam‘

return:

- eauth: pam

  expire: 1423599495.7932329

  perms:

  - .*

  - ‘@wheel‘

  - ‘@runner‘

  start: 1423556295.793232

  token: 38fc58406d4248abded1abbfa11ce83b68754975

  user: xiaoluo

获取token之后,可以使用token通信:


[root@mail salt]# curl -k https://192.168.10.205:8888/ -H "Accept: application/x-yaml" -H "X-Auth-Token: 38fc58406d4248abded1abbfa11ce83b68754975" -d client=‘local‘ -d tgt=‘*‘ -d fun=‘test.ping‘

return:

- monitor: true

跟salt ‘*‘ test.ping的效果是一样的。这样就实现了salt-api接口的通信。


当然在开发获取数据的时候这样的办法显然是不够灵活的。下面贴出一个salt-api的类:

#!/usr/bin/env python

#coding=utf-8


import urllib2, urllib, json, re


class saltAPI:

    def __init__(self):

        self.__url = ‘https://192.168.10.205:8888‘       #salt-api监控的地址和端口如:‘https://192.168.186.134:8888‘

        self.__user =  ‘xiaoluo‘             #salt-api用户名

        self.__password = ‘123456‘          #salt-api用户密码

        self.__token_id = self.salt_login()


    def salt_login(self):

        params = {‘eauth‘: ‘pam‘, ‘username‘: self.__user, ‘password‘: self.__password}

        encode = urllib.urlencode(params)

        obj = urllib.unquote(encode)

        headers = {‘X-Auth-Token‘:‘‘}

        url = self.__url + ‘/login‘

        req = urllib2.Request(url, obj, headers)

        opener = urllib2.urlopen(req)

        content = json.loads(opener.read())

        try:

            token = content[‘return‘][0][‘token‘]

            return token

        except KeyError:

            raise KeyError


    def postRequest(self, obj, prefix=‘/‘):

        url = self.__url + prefix

        headers = {‘X-Auth-Token‘   : self.__token_id}

        req = urllib2.Request(url, obj, headers)

        opener = urllib2.urlopen(req)

        content = json.loads(opener.read())

        return content[‘return‘]


    def saltCmd(self, params):

        obj = urllib.urlencode(params)

        obj, number = re.subn("arg\d", ‘arg‘, obj)

        res = self.postRequest(obj)

        print  res[0][‘monitor‘][‘biosversion‘]

        print  res[0][‘monitor‘][‘cpu_model‘]



def main():

    #以下是用来测试saltAPI类的部分

    sapi = saltAPI()

    params = {‘client‘:‘local‘, ‘fun‘:‘grains.items‘, ‘tgt‘:‘*‘}

    test = sapi.saltCmd(params)

##运行之后就会打印出grain的值。需要什么值可以直接打印。

测试效果:

[root@mail python]# python salt-api.py

2.2.2

Intel(R) Xeon(R) CPU E5-2603 v2 @ 1.80GHz


本文出自 “小罗” 博客,请务必保留此出处http://xiaoluoge.blog.51cto.com/9141967/1613353

salt-api 使用

上一篇:浅析数据库与缓存的双写一致性问题


下一篇:C# 创建自己的日志记录类 源码