cmd实时接收服务器信息,salt-api 获取服务器信息,minion批量执行cmd命令(示例代码)...

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值