importrequestsimportjsontry:importcookielibexcept:importhttp.cookiejar as cookielib#使用urllib2请求https出错,做的设置
importssl
context=ssl._create_unverified_context()classSaltAPI(object):"""定义salt api接口的类
初始化获得token"""
def __init__(self,):
self.url= "https://192.168.1.165:8001/"self.username= "XXX"self.password= "XXX"self.headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36","Content-type": "application/json"
#"Content-type": "application/x-yaml"
}
self.params= {‘client‘: ‘local‘, ‘fun‘: ‘‘, ‘tgt‘: ‘‘}
self.login_url= self.url + "login"self.login_params= {‘username‘: self.username, ‘password‘: self.password, ‘eauth‘: ‘pam‘}
self.token= self.get_data(self.login_url, self.login_params)[‘token‘]
self.headers[‘X-Auth-Token‘] =self.tokendefget_data(self, url, params):
send_data=json.dumps(params)
request= requests.post(url, data=send_data, headers=self.headers, verify=False)
response=request.json()
result=dict(response)return result[‘return‘][0]defremote_execution_module(self, tgt, fun, arg):"""远程执行模块,有参数
:param tgt: minion list
:param fun: 模块
:param arg: 参数
:return: dict, {‘minion1‘: ‘ret‘, ‘minion2‘: ‘ret‘}"""params= {‘client‘: ‘local‘, ‘tgt‘: tgt, ‘fun‘: fun, ‘arg‘: arg}returnself.get_data(self.url, params)def salt_command(self, tgt, method, arg=None):"""远程执行命令,相当于salt ‘client1‘ cmd.run ‘free -m‘"""
ifarg:
params= {‘client‘: ‘local‘, ‘fun‘: method, ‘tgt‘: tgt, ‘arg‘: arg}else:
params= {‘client‘: ‘local‘, ‘fun‘: method, ‘tgt‘: tgt}#print(‘命令参数: ‘, params)
result =self.get_data(self.url, params)returnresult#获取信息
@taskdefpush_host_by_salt_tasks():
salt=SaltAPI()
minions_list=[‘cpu_model‘,‘fqdn_ip4‘,‘os‘,‘disks‘,‘gpus‘,‘id‘,‘ipv4‘,‘kernel‘,‘localhost‘,‘machine_id‘,‘master‘,‘num_cpus‘,‘saltpath‘,‘selinux‘,‘server_id‘,‘virtual‘,‘machine_id‘,‘path‘,‘swap_total‘,‘systemd‘,‘username‘,‘kernelrelease‘,
]
ret= salt.remote_execution_module(‘*‘, ‘grains.item‘, minions_list)return Server_Asset_Record.Excu.insert(ret)