def remote_execution(request): """ remote command execution """ ret = '' tret = '' dangerCmd = ('rm','reboot','init','shutdown','poweroff') if request.method == 'POST': action = request.get_full_path().split('=')[1] if action == 'exec': tgt = request.POST.get('tgt') arg = request.POST.get('arg') if tgt: if arg: argCmd = arg.split()[0] argCheck = argCmd not in dangerCmd if argCheck: sapi = SaltAPI(url=settings.SALT_API['url'],username=settings.SALT_API['user'],password=settings.SALT_API['password']) unret = sapi.remote_execution(tgt,'cmd.run',arg) for kret in unret.keys(): lret = kret + ':\n' + unret[kret] + '\n' tret += lret + '\n' ret = tret elif not argCheck: ret = '亲,命令很危险, 你这样子老大会不开森!' else: ret = '没有输入命令,请重新输入!' else: ret = '没有指定目标主机,请重新输入!' return render_to_response('salt_remote_execution.html', {'ret': ret},context_instance=RequestContext(request))
def post(self, request, *args, **kwargs): _tgt = request.data.get('tgt', '') _sls_id = request.data.get('sls_id', '') # symlink /etc/salt/top.sls /etc/salt/sls/* if sym_link_sls(_sls_id): _saltapi = SaltAPI(url=SALT_API_URL, username=SALT_API_USERNAME, password=SALT_API_PASSWORD) _payload = _saltapi.remote_execution(tgt=_tgt, fun='state.apply') return Response(_payload, status=status.HTTP_200_OK) else: raise Response('', status=status.HTTP_400_BAD_REQUEST)
def post(self, request, *args, **kwargs): _type = request.data.get('type', '') if _type == 'glob': _server = request.data.get('servers', '') elif _type == 'list': _server = request.data.getlist('servers[]', '') _cmds = request.data.getlist('cmds[]', '') _raw_args = request.data.getlist('args[]', []) _args = [_arg.split(',') for _arg in _raw_args] _saltapi = SaltAPI(url=SALT_API_URL, username=SALT_API_USERNAME, password=SALT_API_PASSWORD) _payload = _saltapi.remote_execution(_server, _cmds, tgt_type=_type, arg=_args) return Response(_payload, status=status.HTTP_200_OK)
def remote_execution(request): """ remote command execution out(type:string) ret = 'format string' """ ret = '' tret = '' if request.method == 'POST': action = request.get_full_path().split('=')[1] if action == 'exec': tgt = request.POST.get('tgt') arg = request.POST.get('arg') tgtTest, tgtminis, tgtminisnox = tgtCheck() dangerCmd = ('rm', 'reboot', 'init', 'shutdown', 'poweroff') if tgt: if tgt in tgtTest: if arg: argCmd = arg.split()[0] argCheck = argCmd not in dangerCmd if argCheck: sapi = SaltAPI(url=settings.SALT_API['url'], username=settings.SALT_API['user'], password=settings.SALT_API['password']) unret = sapi.remote_execution(tgt, 'cmd.run', arg) for kret in unret.keys(): lret = kret + ':\n' + unret[kret] + '\n' tret += lret + '\n' ret = tret elif not argCheck: ret = '亲,命令很危险, 你这样子老大会不开森!' else: ret = '没有输入命令,请重新输入!' else: ret = '目标主机不合法,只能形如zhaogb-201、zhaogb-*、* !' else: ret = '没有指定目标主机,请重新输入!' return render_to_response('salt_remote_execution.html', {'ret': ret}, context_instance=RequestContext(request))
def post(self, request, *args, **kwargs): _glob = self.request.data.get('glob', '') _dst_dir = self.request.data.get('dst_dir', '') if _glob and _dst_dir: _saltapi = SaltAPI(url=SALT_API_URL, username=SALT_API_USERNAME, password=SALT_API_PASSWORD) _u = get_user(self.request) _dir = '{}.{}'.format(_u.username, int(timezone.now().timestamp())) # need to add a symbolic link from media to /etc/salt _srcdir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'media/file/', _dir) _saltdir = 'salt://media/file/' + _dir os.makedirs(_srcdir) _media = '/etc/salt/media' os.remove(_media) if os.path.islink(_media) else shutil.rmtree( _media) os.symlink( os.path.join(os.path.dirname(os.path.dirname(__file__)), 'media'), _media) for k, v in self.request.FILES.items(): _f = File(file=v, user=_u, status=1) _f.save() _origin_fpath = _f.file.path _f.file.name = _f.file.name.replace('file/', 'file/{}/'.format(_dir)) _f.save() shutil.move(_origin_fpath, _srcdir) _ret = _saltapi.remote_execution( tgt=_glob, fun='cp.get_file', arg=[ '{}/{}'.format(_saltdir, v.name), '{}/{}'.format(_dst_dir, v.name) ]) return Response('', status=status.HTTP_200_OK) return Response('Less glob and destination directory.', status=status.HTTP_400_BAD_REQUEST)
def remote_execution(request): """ remote command execution out(type:string) ret = 'format string' """ user = request.user.username ret = '' tret = '' hostsft = {} dcen_list = [] data_centers = {} get_errors = [] errors = [] danger_cmd = ('rm','reboot','init','shutdown','poweroff') minion_ip_list = [] result_dc = DataCenter.objects.all() for dc in result_dc: dcen_list.append(dc.dcen) data_centers[dc.dcen] = dc.dccn dcen_list.sort() if request.method == 'POST': check_tgt = request.POST.get('tgt', '') check_dc_list = request.POST.get('datacenter', '') module_detection = moduleDetection('cmd.run', user) if module_detection: get_errors.append(module_detection) if not (check_tgt or check_dc_list): get_errors.append(u'需要指定目标主机或目标机房!') if not request.POST.get('arg', ''): get_errors.append(u'请输入将要执行的命令!') else: arg_string = request.POST.get('arg') arg_strip = arg_string.strip() arg_list = arg_strip.split() arg_one = arg_list[0] for dcmd in danger_cmd: if arg_one == dcmd: get_errors.append(u'%s 命令危险,不允许使用!' % arg_one) if get_errors: for error in get_errors: errors.append(error.encode('utf-8')) else: tgt = request.POST.get('tgt') dc_list = request.POST.getlist('datacenter') arg = request.POST.get('arg') module_lock = moduleLock('cmd.run', user) if tgt: minion_id_from_tgt_set = targetToMinionID(tgt) else: minion_id_from_tgt_set = set([]) if dc_list: minion_id_from_dc_set = datacenterToMinionID(dc_list) else: minion_id_from_dc_set = set([]) all_minion_id_set = minion_id_from_tgt_set.union(minion_id_from_dc_set) if all_minion_id_set: sapi = SaltAPI( url=settings.SALT_API['url'], username=settings.SALT_API['user'], password=settings.SALT_API['password']) tgt_list = tgt.split(',') if ('*' in tgt_list) or ('*' in dc_list): unret = sapi.remote_execution(arg) else: tgt_list_to_str = ','.join(all_minion_id_set) unret = sapi.list_remote_execution(tgt_list_to_str, arg) hostsum = len(all_minion_id_set) sumset = all_minion_id_set ret_list = unret.keys() hostrsum = len(ret_list) returnset = set(ret_list) diffset = sumset.difference(returnset) hostunre = len(diffset) hostunrestr = ','.join(list(diffset)) hostsft['sum'] = hostsum hostsft['rsum'] = hostrsum hostsft['unre'] = hostunre hostsft['unrestr'] = hostunrestr if dc_list: operate_tgt = dc_list[0] elif tgt: tgtlist = tgt.split(',') operate_tgt = tgtlist[0] else: operate_tgt = 'unknown' op_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) op_user = arg op_tgt = '%s...' % operate_tgt p3 = OperateRecord.objects.create( nowtime=op_time, username=user, user_operate=op_user, simple_tgt=op_tgt) for kret in unret.keys(): minion_data = HostList.objects.get(minionid=kret) log.debug('remote_exec: %s' % str(kret)) minion_ip = minion_data.ip minion_ip_list.append(minion_ip) minion_ip_list.sort() for mip in minion_ip_list: minion_data = HostList.objects.get(ip=mip) kret = minion_data.minionid lret = mip + ':\n' + unret[kret] + '\n' tret += lret + '\n' ret = tret saveRecord = ReturnRecord.objects.create( #jid=jid[0], jid='', tgt_total=hostsum, tgt_ret=hostrsum, tgt_unret=hostunre, tgt_unret_list=hostunrestr ) module_unlock = moduleUnlock('cmd.run', user) else: tips = u'请输入正确的服务器IP或MinionID' errors.append(tips.encode('utf-8')) return render_to_response( 'salt_remote_execution.html', {'ret': ret, 'hostsft': hostsft, 'dcen_list': dcen_list, 'data_centers': data_centers, 'errors': errors }, context_instance=RequestContext(request) )