Python API调用saltstack
SaltStack本身提供salt(usr/bin/salt)来交互管理,但是去服务器上敲命令肯定不是一个长远之计,这时候python就体现了nb的功能。
Python API就是给Python提供的API使用,需要在SaltStack master上运行
1.实例代码
[root@master ~]$python
Python 2.7.5 (default, Jul 13 2018, 13:06:57)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import salt.client
>>> local = salt.client.LocalClient() #<salt.client.LocalClient object at 0x7f886dbdd850>
>>> local.cmd('*','cmd.run',['hostname'])#向所有minion发送命令
{'slave': 'slave'}
因此python API就是提供了向saltstack发送命令的入口。
2.通过API获取saltstack的配置文件
(1)获取master配置文件
>>> import salt.config #导入salt配置模块
>>> m_opts=salt.config.client_config('/etc/salt/master') #读取salt配置文件,得到一个字典数据
(2)获取minion配置文件
Python 2.7.5 (default, Jul 13 2018, 13:06:57)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import salt.client
>>> salt.config.minion_config('/etc/salt/minion') #读取minion配置文件,得到字典数据,通过字典方法可以查看信息
#############################################################################
Python API介绍
/usr/bin/salt默认使用的接口是LocalClient,该接口只能在salt master上使用
[root@master ~]$python
Python 2.7.5 (default, Jul 13 2018, 13:06:57)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import salt.client
>>> local = salt.client.LocalClient() #<salt.client.LocalClient object at 0x7f886dbdd850>
>>> local.cmd('*','cmd.run',['hostname'])#向所有minion发送命令
{'slave': 'slave'}
逐条返回结果,local.cmd_iter()
>>> ret=local.cmd_iter('*','test.ping')
>>> ret
<generator object cmd_iter at 0x7f886d455c80>
>>> for i in ret:
... print i
...
{'slave': {'retcode': 0, 'ret': True}}
菲波那切数列
>>> local.cmd('*','test.fib',[10])
{'slave': [[0, 1, 1, 2, 3, 5, 8], 2.1457672119140625e-06]}
检查minion服务器信息
>>> local.cmd('*','cmd.run',['hostname'])
{'slave': 'slave'}
>>> local.cmd('*','cmd.run',['ifconfig'])
>>> local.cmd('*','cmd.run',['crontab -l'])
>>> local.cmd('*','cmd.run',['df -h'])
启停minion的服务,如nginx
>>> local.cmd('*','service.stop',['nginx'])
{'slave': True}
>>> local.cmd('*','service.status',['nginx'])
{'slave': False}
>>> local.cmd('*','service.start',['nginx'])
{'slave': True}