def createRundeck(self): c = client.LocalClient() #item = '/bin/bash /var/rundeck/newjobimport.sh %s %s' %(self.group,self.env) item = 'source /etc/profile;sh /var/xxx/runjobimport.sh %s %s' %(self.group,self.env) result=client.LocalClient().cmd('run01.xxx.xxx','cmd.run',[item],timeout=15,verbose=True).items() for k,v in result: if v == 'ok': return True else: return False
def testPing(self): y = 1 print "Test connect server: '" + self.server + "',mid: '" + self.type + "'." c = client.LocalClient() while 1: # t = excuteLocateShell("salt -t 300 -C 'L@" + self.type + "' test.ping --out yaml") try: # if yaml.load(t[1])[self.type]: if c.cmd(self.type, 'test.ping')[self.type]: print 'Connect to "' + self.server + '" server is ok,and mid:' + self.type # break return 0 except Exception, e: print 'Connect to ' + self.server + ",and mid: '" + self.type + "' timout.", y # excuteShell(cmd="salt-ssh -i '"+self.type+"' -r 'source /etc/profile;/etc/init.d/salt-minion restart'",type=self.type) # maybe minion client process is down # self.restartMinion() # maybe key in un,not in acc pass if y > 5 and y <= 8: self.foundMinionKey(count=y) elif y > 8: print "Connect server " + self.server + ",mid: " + self.type + " unreachable,please check iptables." print "you may be execute command: salt-key -d " + self.type + " -y" print "and re-install try again latter." # sys.exit(9) return 1 y += 1
def test_create_local_client(self): local_client = client.LocalClient(mopts=self.get_temp_config("master")) self.assertIsInstance( local_client, client.LocalClient, "LocalClient did not create a LocalClient instance", )
def _connect(self): if not HAVE_SALTSTACK: raise errors.AnsibleError("saltstack is not installed") self.client = sc.LocalClient() self._connected = True return self
def get_hostname(host): try: local = client.LocalClient() cmd = local.cmd(host, 'grains.item', ['nodename']) hostname_info = {"hostname": cmd[host]['nodename']} return hostname_info except Exception, e: print e
def setUp(self): master_config_path = self.get_config_file_path('master') master_config = config.master_config(master_config_path) if not os.path.exists(master_config['cachedir']): os.makedirs(master_config['cachedir']) if not os.path.exists(integration.TMP_CONF_DIR): os.makedirs(integration.TMP_CONF_DIR) self.local_client = client.LocalClient(mopts=master_config)
def setUp(self): if not os.path.exists('/tmp/salttest'): # This path is hardcoded in the configuration file os.makedirs('/tmp/salttest/cache') if not os.path.exists(integration.TMP_CONF_DIR): os.makedirs(integration.TMP_CONF_DIR) self.local_client = client.LocalClient( self.get_config_file_path('master'))
def salt(self,host): ret = [] local = sc.LocalClient() grains = local.cmd(host, "grains.items")[host] nics = filter(lambda x: x != 'lo', grains['hwaddr_interfaces'].keys()) for nic in nics: name = nic hwaddr = grains['hwaddr_interfaces'][nic] ipv4 = grains['ip4_interfaces'][nic][0] ret.append({'name':name,'hwaddr':hwaddr,'ipv4':ipv4}) return ret
def runState(self): c = client.LocalClient() jid = '' jid = c.cmd_async(self.group, # target 'state.sls', # function [self.arg], # arg for function jid=jid, expr_form='nodegroup', kwarg={'pillar':{'status':'TEST'},} ) return jid
def __init__(self): self.ms_type = '' self.input_file = '' self.verbose = False self.local_salt = client.LocalClient() self.input_list = [] self.available_minions = [] self.available_minions_ids = [] self.failed_minions_ids = [] with open('qs_base.txt') as _qs_base: self.qs_base_list = _qs_base.read().splitlines()
def test(): print("Testing HTTP Against Each Minion") cli = client.LocalClient(__opts__['conf_file']) minions = cli.cmd('*', 'test.ping', timeout=1) success = True for minion in sorted(minions): result = http.query('http://{}'.format(minion), status=True) if result['status'] != 200: success = False print("{}: {}".format(minion, result['body'])) return success
def __init__(self): self.client = Client.LocalClient() self.file_path = '/home/work/open-falcon/agent/control' self.file_cfg = '/home/work/open-falcon/agent/cfg.json' self.enable_s = '"enabled": true' self.disable_s = '"enabled": false' self.path_file = "/home/work/open-falcon/agent" self.ant_cfg = "/home/work/open-falcon/anteye/cfg.json" self.ant_file = "/home/work/open-falcon/anteye/control" self.db = DB("root", "password", "localhost", "falcon_portal") self.tab_host = "falcon_hosts" self.tab_service = "falcon_service"
def __init__(self, state_params): # 开始执行,更新status=1,start_time=now self.number = state_params['number'] Jobs.objects.filter(number=self.number).update( status=1, start_time=datetime.datetime.now()) playbook_obj = Playbooks.objects.get(id=state_params['playbook_id']) base_path = '/srv/salt/%s.sls' % playbook_obj.description with open(base_path, 'w') as f: f.write(playbook_obj.context) self.minions = state_params['minion_id_list'] self.sls = playbook_obj.description self.client = client.LocalClient()
def salt(self,host): local = sc.LocalClient() grains = local.cmd(host, "grains.items") server_info = {} for i in grains.keys(): server_info['hostname'] = grains[i]["nodename"] server_info['sn'] = grains[i]["serialnumber"] server_info['vendor'] = grains[i]["manufacturer"] server_info['os_platform'] = grains[i]["osfullname"] server_info['os_version'] = grains[i]["osmajorrelease"] server_info['cpu_cores'] = grains[i]["num_cpus"] server_info['cpu_model'] = grains[i]["cpu_model"] return server_info
def __init__(self): self.user = '******' self.password = '******' self.base_url = "http://10.1.0.12:5050" self.auth_url = "http://10.1.0.12:1234/auth/login" self.base_path = "/home/work/open-falcon/agent/plugin" self.salt_base = "salt://file/open-falcon/plugin/compute" data = {"name": self.user, "password": self.password} self.s = requests.session() self.s.post(self.auth_url, data=data) self.client = Client.LocalClient() self.db = DB("root", "password", "localhost", "falcon_portal") self.tab_service = "falcon_service"
def AddNodeState(self): c = client.LocalClient() jid = '' node_item = self.node.split(',') for item in node_item: jid = c.cmd_async(item, # target 'state.sls', # function [self.arg], # arg for function jid=jid, timeout='15', kwarg={'pillar':{'status':'TEST'},} ) return jid
def testPing(self): c = client.LocalClient() result=c.cmd(self.node, # target 'test.ping', # function timeout='15' ) node_item = self.node.split(',') for i in node_item: for k,v in result.items(): for n in node_item: if k == i and v: return True else: return False
def grains_defined(self): # 导入自定义grains文件 grains_path = '/srv/salt/_grains/' grains_file = '/srv/salt/_grains/grains_defined.py' if os.path.exists(grains_file): grains_bak = datetime.datetime.now().strftime( '%Y%m%d_%H%M%S_%f') + '_grains' os.rename(grains_file, grains_path + grains_bak) shutil.copyfile(self.init_conf + 'grains_defined.py', '/srv/salt/_grains/grains_defined.py') result = client.LocalClient().cmd_async('*', 'saltutil.sync_all', []) #result = client.LocalClient().cmd(minion_id, 'grains.item', ['md_op_linux_beijing_opcenter-slave','md_op_linux_shanghai_opcenter-slave','md_op_linux_qingdao_opcenter-slave','md_op_linux_shenzhen_opcenter-slave']) return result
def checkPillar(self): result = {} item = self.node.split(',') for i in item: if self.group and i: try: result=client.LocalClient().cmd(self.group,'pillar.items',expr_form='nodegroup',timeout=15,verbose=True).items() for k,v in result: if i == k and len(v) != 0: return True else: return False except: return False
def test_job_result_return_success(self): """ Should return the `expected_return`, since there is a job with the right jid. """ minions = () jid = "0815" raw_return = {"id": "fake-id", "jid": jid, "data": "", "return": "fake-return"} expected_return = {"fake-id": {"ret": "fake-return"}} local_client = client.LocalClient(mopts=self.get_temp_config("master")) local_client.event.get_event = MagicMock(return_value=raw_return) local_client.returners = MagicMock() ret = local_client.get_event_iter_returns(jid, minions) val = next(ret) self.assertEqual(val, expected_return)
def checkZabbix(self): c = client.LocalClient() result = c.cmd(self.group, # target 'cmd.run', # function ['ps -elf|grep -w zabbix|grep -v grep|wc -l'], # arg for function expr_form='nodegroup', kwarg={'pillar':{'status':'TEST'},} ) node_item = self.node.split(',') for k,v in result.items(): for n in node_item: if k == n and v >= '1': return True else: return False
def checkLogstash(self): c = client.LocalClient() result = c.cmd(self.group, # target 'cmd.run', # function ['ps -elf|grep -w logstash|grep -v grep|wc -l'], # arg for function expr_form='nodegroup', ) node_item = self.node.split(',') for k,v in result.items(): for n in node_item: if k == n and v >= '1': print 'True' return True else: print 'False' return False
def checkNode(self): result = {} q_group = self.group print q_group if q_group: try: result=client.LocalClient().cmd(q_group,'cmd.run',[''],expr_form='nodegroup',timeout=15,verbose=True) print result.keys() exit_item = result.keys() node_item = self.node.split(',') for n in node_item: if n in exit_item: return True except: result['result'] = False return False
def get_cpuinfo(host): try: local = client.LocalClient() operating_system = system(host) if operating_system == 'linux': cmd = local.cmd( host, 'grains.item', ['cpu_module', 'cpu_physical', 'cpu_cores', 'cpu_processor']) cpu_info = {"cpu": cmd[host]} return cpu_info elif operating_system == 'windows': print 'windows' else: print 'other os' except Exception, e: print e
def _write_certs_to_minion(fqdn, dest_path, cert_data): """Writes signed cert back to requesting minion at specified path. Given a destination path on the minion, write both the signed cert and a full chain (cert + CA cert) to it using the standard filenames. """ client = salt_client.LocalClient(SALT_MASTER_CONFIG) cert_path = os.path.join(dest_path, CERT_FILENAME) fullchain_path = os.path.join(dest_path, FULLCHAIN_FILENAME) cert = cert_data['certificate'] issuing_ca = cert_data['issuing_ca'] fullchain = '\n'.join([cert, issuing_ca]) write_cert = client.cmd(fqdn, 'file.write', [cert_path, cert]) write_fullchain = client.cmd(fqdn, 'file.write', [fullchain_path, fullchain]) # TODO(dmw) Figure out odd client.cmd rc's and error if needed. return True
def server_manage(request): user = User.objects.get(id=request.session['_auth_user_id']) login_user = user.last_name + user.first_name if user.username != "admin": return HttpResponseRedirect('/') if request.method == "POST": cli = client.LocalClient() re_id = cli.cmd(tgt='*', fun='grains.item', arg=['os']) for k, v in re_id.items(): exsit = Servers.objects.filter(ipaddress=k) if exsit: continue else: server = Servers(ipaddress=k, ostype=v['os'], user=user) server.save() return HttpResponse() return render_to_response('server_manage.html', {'login_user': login_user})
def __init__(self, cluster_name=None): if cluster_name is None: cluster_name = socket.getfqdn().split('.', 1)[-1] LOG.info("No domain/cluster_name passed, use generated: {}".format( cluster_name)) salt = client.LocalClient() inv = salt.cmd('salt:master', 'cmd.run', ['reclass --inventory'], tgt_type='pillar').values() file_io = StringIO(''.join(inv).decode("utf-8")) inventory = yaml.load(file_io) LOG.info("Try to load nodes for domain {}".format(cluster_name)) self.nodes = { k: v for k, v in inventory["nodes"].items() if cluster_name in k } LOG.info("Load nodes: {}".format(self.nodes.keys()))
def test_job_result_return_success(self): """ Should return the `expected_return`, since there is a job with the right jid. """ minions = () jid = '0815' raw_return = { 'id': 'fake-id', 'jid': jid, 'data': '', 'return': 'fake-return' } expected_return = {'fake-id': {'ret': 'fake-return'}} local_client = client.LocalClient(mopts=self.get_temp_config('master')) local_client.event.get_event = MagicMock(return_value=raw_return) local_client.returners = MagicMock() ret = local_client.get_event_iter_returns(jid, minions) val = next(ret) self.assertEqual(val, expected_return)
def Get_Merged(): merged_list = [] local = sc.LocalClient() tgt_name = salt_master try: pillar = local.cmd(tgt_name, 'pillar.items') if len(pillar) <= 0: print('{0}获取pillar失败{1}'.format(st.color['FG_RED'], st.color['END'])) sys.exit(1) ret = pillar.values()[0]['slist'] for i in ret: if len(ret[i]['merge_server']) != 0: merged_list.append(i) return merged_list except Exception as e: print("{0}{1}{2}".format(st.color['FG_RED'], e, st.color['END'])) return False
def test_job_result_return_success(master_config): """ Should return the `expected_return`, since there is a job with the right jid. """ minions = () jid = "0815" raw_return = { "id": "fake-id", "jid": jid, "data": "", "return": "fake-return" } expected_return = {"fake-id": {"ret": "fake-return"}} with client.LocalClient(mopts=master_config) as local_client: local_client.event.get_event = MagicMock(return_value=raw_return) local_client.returners = MagicMock() ret = local_client.get_event_iter_returns(jid, minions) val = next(ret) assert val == expected_return