salt-api 获取服务器信息,minion批量执行cmd命令
Posted 小陆同学
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了salt-api 获取服务器信息,minion批量执行cmd命令相关的知识,希望对你有一定的参考价值。
import requests import json try: import cookielib except: import http.cookiejar as cookielib # 使用urllib2请求https出错,做的设置 import ssl context = ssl._create_unverified_context() class SaltAPI(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.token def get_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] def remote_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} return self.get_data(self.url, params) def salt_command(self, tgt, method, arg=None): """远程执行命令,相当于salt ‘client1‘ cmd.run ‘free -m‘""" if arg: 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) return result # 获取信息 @task def push_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)
salt ‘*‘ grains.items # 获取服务器参数
以上是关于salt-api 获取服务器信息,minion批量执行cmd命令的主要内容,如果未能解决你的问题,请参考以下文章