用python操作saltstack,如果是在本地,则可以用python的salt模块,但如果要操作远程saltstack,则不行,今天就来看看怎么操作。
用python操作远程的saltstack,需要远程saltstack安装并开启salt-api,然后用python登录salt-api获取token,再执行命令,具体代码如下:
#! coding:utf-8 import urllib import urllib2 from op_site.settings import salt_http_url, salt_user, salt_pwd def get_salt_token(url, user, pwd): params = {'eauth': 'pam', 'username': user, 'password': pwd} params_encode = urllib.urlencode(params) # 把上面的参数格式化为字符串,因为下面Request函数需要str类型的参数 url = str(url.rstrip('/')) + '/login' # 构造url headers = {'Accept': 'application/x-yaml'} # 设置头部信息 req = urllib2.Request(url, params_encode, headers) # params_encode为传入字典参数,params_encode为None 则方法为get,有params_encode为post方法 opener = urllib2.urlopen(req) resp = (opener.read()).strip() s_token = (resp.split('\n')[-2]).split(':')[1] return s_token def exec_salt_cmd(dip, cmd): params = {'client': 'local', 'tgt': dip, 'fun': cmd} params = urllib.urlencode(params) token = get_salt_token('http://192.168.9.1:8080', 'salt', 'salt_pwd') # 这里的账号密码是上篇文章中salt-master配置文件里面配置的 headers = {'X-Auth-Token': token} req = urllib2.Request(salt_http_url, params, headers) opener = urllib2.urlopen(req) resp = opener.read() return resp
if __name__ == "__main__":
exec_salt_cmd('192.168.9.3', 'df -h')
这就是简单的用python登录远程saltstack并执行命令。