Centos6.5配置salt-api

1、yum源安装
rpm -ivh http://dl.fedoraproject.org/pub/epel/6Server/x86_64/epel-release-6-8.noarch.rpm
yum install salt salt-master salt-minion -y

2、salt-minion修改配置文件
sed -i 's/#master: salt/master: 172.16.8.25/' /etc/salt/minion
grep -n '^master' /etc/salt/minion

3、启动服务
/etc/init.d/salt-master start
/etc/init.d/salt-minion start

列出要注册的主机
salt-key -L
全部允许
salt-key -A
测试
salt '*' test.ping

安装salt-api
yum -y install salt-api

安装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

#配置openssl证书:
cd /etc/pki/tls/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:
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) []:beijing
Locality Name (eg, city) [Default City]:beijing
Organization Name (eg, company) [Default Company Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:
Email Address []:[email protected]
cd ../private/
[root@localhost private]# openssl rsa -in localhost.key -out localhost_nopass.key
Enter pass phrase for localhost.key:
writing RSA key
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
useradd -M -s /sbin/nologin test
passwd test

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

saltstack服务端配置:
cat /etc/salt/master.d/api.conf 
rest_cherrypy:
  port: 8000
  ssl_crt: /etc/pki/tls/certs/localhost.crt
  ssl_key: /etc/pki/tls/private/localhost_nopass.key

cat /etc/salt/master.d/eauth.conf 
external_auth:
    pam:

    test:

        - .*

        - '@wheel'

        - '@runner'


重启salt-master和salt-api服务:
 
/etc/init.d/salt-master restart
Stopping salt-master daemon:   [FAILED]
Starting salt-master daemon:   [  OK  ]
/etc/init.d/salt-api restart

Stopping salt-api daemon:           [FAILED]
Starting salt-api daemon:                    [  OK  ]

netstat -lntp|grep 8000
tcp 0  0 0.0.0.0:8000 0.0.0.0   LISTEN  14695/python  

curl使用api:

curl -k https://172.16.8.25:8000/login -H "Accept: application/x-yaml"  -d username='test' -d password='123456' -d eauth='pam'
return:
- eauth: pam
  expire: 1419373087.9501131
  perms:
  - .*
  - '@wheel'
  - '@runner'
  start: 1419329887.9501131
  token: e214657dba43b46c482501349123jkpo
  user: jc
saltstack安装客户端测试:

/etc/init.d/salt-minion restart

API测试test.ping:
curl -k https://172.16.8.25:8000/ -H "Accept: application/x-yaml" -H "X-Auth-Token: e214657dba43b46c482501349123jkpo" -d client='local' -d tgt='*' -d fun='test.ping'
return:
- localhost: true

Api测试查看系统内存:
curl -k https://172.16.8.25:8000/ -H "Accept: application/x-yaml" -H "X-Auth-Token: 5ff2c69eaaa5a68997b371932b8bfaea0f5351eb" -d client='local' -d tgt='*' -d fun='cmd.run' -d arg="free -m"
return:
- 172.16.8.25: '             total       used       free     shared    buffers     cached
    Mem:           980        388        592          0         12         59
    -/+ buffers/cache:        316        664
    Swap:            0          0          0'

cat saltapi.py 
#!/usr/bin/env python
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.16.8.25:8000',username='test',password='123456')
print sapi.list_all_key()
# sapi.token_id()
#sapi.delete_key('test-01')
print sapi.accept_key('localhost')
#sapi.deploy('test-01','nginx')
#print sapi.remote_noarg_execution('test-01','grains.items')
if __name__ == '__main__':
main()

执行脚本:
[root@localhost ~]# python saltapi.py 
([u'172.16.8.25'], [])
True



你可能感兴趣的:(自动化运维)