用Python实现salt-api调用

调整

之前写过PHP调用salt-api脚本,搬砖需求调整又写了Python版的,实现的思路和PHP一样,这里记录下,调用1个参数或不带参的salt执行模块,后面需要使用更多的参数,发散思维再优化代码。

代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/python 
# -*- coding: utf-8 -*-
import pycurl
import StringIO
#登录salt-api,获取token
def api_login():
global token
url='https://IP地址:8000/login'
ch=pycurl.Curl()
ch.setopt(ch.URL, url)
info = StringIO.StringIO()
ch.setopt(ch.WRITEFUNCTION, info.write)
ch.setopt(ch.POST, True)
#如果是https就要开启这两行
ch.setopt(ch.SSL_VERIFYPEER, 0)
ch.setopt(ch.SSL_VERIFYHOST, 2)
ch.setopt(ch.HTTPHEADER, ['Accept: application/x-yaml'])
ch.setopt(ch.POSTFIELDS, 'username=你的用户名&password=对应用户的密码&eauth=pam')
#要包头信息
#ch.setopt(ch.HEADER, True)
#不要包头信息
ch.setopt(ch.HEADER,False)
ch.perform()
html = info.getvalue()
#提取token
token = html.split("\n")[-3].replace("\n", '')
token = token.split(' ')[3]
info.close()
ch.close()

def api_exec(target, fun, arg='', arg_num=0):
global token
url='https://IP地址:8000/'
ch=pycurl.Curl()
ch.setopt(ch.URL, url)
info = StringIO.StringIO()
ch.setopt(ch.WRITEFUNCTION, info.write)
ch.setopt(ch.POST, True)
ch.setopt(ch.SSL_VERIFYPEER, 0)
ch.setopt(ch.SSL_VERIFYHOST, 2)
ch.setopt(ch.HTTPHEADER, ['Accept: application/x-yaml', "X-Auth-Token: %s" %(token)])
if arg_num == 0:
ch.setopt(ch.POSTFIELDS, "client=local&tgt=%s&fun=%s" %(target, fun))
elif arg_num == 1:
ch.setopt(ch.POSTFIELDS, "client=local&tgt=%s&fun=%s&arg=%s" %(target, fun, arg))
ch.setopt(ch.HEADER,False)
ch.perform()
html = info.getvalue()
info.close()
ch.close()
return html

#测试时用的,做为模块使用时注释下面两行
api_login()
print api_exec('主机key', 'test.ping', '', 0)
运行结果

python-salt-api
提取token时,不要忘记除掉结尾的换行符”\n”,不然会报错。

----------------本文结束 感谢阅读----------------