企业级 ##自动化运维工具Saltstack扩展(salt-api)##

1.【server3】建立服务:

[root@server3 ~]# yum install -y salt-api
[root@server3 ~]# /etc/init.d/salt-minion start
Starting salt-minion:root:server3 daemon: OK

2.【server1】建立服务:

[root@server1 master.d]# yum install -y salt-api
[root@server1 private]# pwd
/etc/pki/tls/private
[root@server1 private]# openssl genrsa 1024 > localhost.key
Generating RSA private key, 1024 bit long modulus
.++++++
...................++++++
e is 65537 (0x10001)
[root@server1 private]# ls
localhost.key
[root@server1 private]# cd ..
[root@server1 tls]# cd certs/
[root@server1 certs]# make testcert
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
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) []:shaanxi
Locality Name (eg, city) [Default City]:xi'an
Organization Name (eg, company) [Default Company Ltd]:westos
Organizational Unit Name (eg, section) []:linux
Common Name (eg, your name or your server's hostname) []:server1
Email Address []:root@localhost

3.【server1】编辑配置文件:

[root@server1 certs]# cd /etc/salt/
[root@server1 salt]# ls
cloud           cloud.maps.d       master    minion.d   proxy
cloud.conf.d    cloud.profiles.d   master.d  minion_id  proxy.d
cloud.deploy.d  cloud.providers.d  minion    pki        roster
[root@server1 salt]# cd master.d/
[root@server1 master.d]# ls
[root@server1 master.d]# cd ..
[root@server1 salt]# vim master
[root@server1 salt]# cd master.d/
[root@server1 master.d]# vim api.conf

企业级 ##自动化运维工具Saltstack扩展(salt-api)##_第1张图片

[root@server1 master.d]# vim auth.conf

企业级 ##自动化运维工具Saltstack扩展(salt-api)##_第2张图片
4.添加用户,设置密码:

[root@server1 master.d]# useradd saltapi
[root@server1 master.d]# passwd saltapi
Changing password for user saltapi.
New password: 
BAD PASSWORD: it is based on a dictionary word
BAD PASSWORD: is too simple
Retype new password: 
passwd: all authentication tokens updated successfully.

5.启动服务:

[root@server1 master.d]# /etc/init.d/salt-master stop
Stopping salt-master daemon:                               [  OK  ]
[root@server1 master.d]# /etc/init.d/salt-master status
salt-master is stopped
[root@server1 master.d]# /etc/init.d/salt-master start
Starting salt-master daemon:                               [  OK  ]
[root@server1 master.d]# /etc/init.d/salt-api start
Starting salt-api daemon:                                  [  OK  ]
[root@server1 master.d]# netstat -antlp|grep :8000
tcp        0      0 0.0.0.0:8000                0.0.0.0:*                   LISTEN      3244/salt-api -d    

6.获取服务token码:

[root@server1 master.d]# curl -sSk https://localhost:8000/login \
> -H 'Accept: application/x-yaml' \
> -d username=saltapi \
> -d password=westos \
> -d eauth=pam
return:
- eauth: pam
  expire: 1534628669.2393489
  perms:
  - .*
  - '@wheel'
  - '@runner'
  - '@jobs'
  start: 1534585469.2393479
  token: 7e979b37fd9f73a3026ca2a94ab45a71cefcba17
  user: saltapi

7.进行测试:

[root@server1 master.d]# curl -sSk https://localhost:8000 \
> -H 'Accept: application/x-yaml' \
> -H 'X-Auth-Token: 7e979b37fd9f73a3026ca2a94ab45a71cefcba17' \
>  -d client=local \
>  -d tgt='*' \
> -d fun=test.ping
return:
- server1: true
  server2: true
  server3: true

8.建立api自动脚本:

[root@server1 ~]# vim salt-api.py
# -*- coding: utf-8 -*-

import urllib2,urllib
import time

try:
    import json
except ImportError:
    import simplejson as json

class SaltAPI(object):
    __token_id = ''
    def __init__(self,url,username,password):
        self.__url = url.rstrip('/')
        self.__user = username
        self.__password = password

    def token_id(self):
        ''' user login and get token id '''
        params = {'eauth': 'pam', 'username': self.__user, 'password': self.__password}
        encode = urllib.urlencode(params)
        obj = urllib.unquote(encode)
        content = self.postRequest(obj,prefix='/login')
    try:
            self.__token_id = content['return'][0]['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

    def list_all_key(self):
        params = {'client': 'wheel', 'fun': 'key.list_all'}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        minions = content['return'][0]['data']['return']['minions']
        minions_pre = content['return'][0]['data']['return']['minions_pre']
        return minions,minions_pre

    def delete_key(self,node_name):
        params = {'client': 'wheel', 'fun': 'key.delete', 'match': node_name}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        ret = content['return'][0]['data']['success']
        return ret

    def accept_key(self,node_name):
        params = {'client': 'wheel', 'fun': 'key.accept', 'match': node_name}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        ret = content['return'][0]['data']['success']
        return ret

    def remote_noarg_execution(self,tgt,fun):
        ''' Execute commands without parameters '''
        params = {'client': 'local', 'tgt': tgt, 'fun': fun}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        ret = content['return'][0][tgt]
        return ret

    def remote_execution(self,tgt,fun,arg):
        ''' Command execution with parameters '''        
        params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        ret = content['return'][0][tgt]
        return ret

    def target_remote_execution(self,tgt,fun,arg):
        ''' Use targeting for remote execution '''
        params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg, 'expr_form': 'nodegroup'}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        jid = content['return'][0]['jid']
        return jid

    def deploy(self,tgt,arg):
        ''' Module deployment '''
        params = {'client': 'local', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        return content

    def async_deploy(self,tgt,arg):
        ''' Asynchronously send a command to connected minions '''
        params = {'client': 'local_async', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        jid = content['return'][0]['jid']
        return jid

    def target_deploy(self,tgt,arg):
        ''' Based on the node group forms deployment '''
        params = {'client': 'local_async', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg, 'expr_form': 'nodegroup'}
        obj = urllib.urlencode(params)
        self.token_id()
        content = self.postRequest(obj)
        jid = content['return'][0]['jid']
        return jid

def main():
    sapi = SaltAPI(url='https://172.25.39.1:8000',username='saltapi',password='westos')

    #sapi.token_id()
    #print sapi.list_all_key()
    #sapi.delete_key('test-01')
    #sapi.accept_key('test-01')
    sapi.deploy('server3','nginx.service')
    #print sapi.remote_noarg_execution('test-01','grains.items')

if __name__ == '__main__':
    main()

推送:[root@server1 ~]# python salt-api.py
在【server3】中关闭nginx服务:

[root@server3 ~]# /etc/init.d/nginx stop
Stopping nginx:                                            [  OK  ]

再次推送:[root@server1 ~]# python salt-api.py
在【server3】中ps ax查看进程,发现nginx服务重新打开
这里写图片描述

你可能感兴趣的:(linux)