def module_run(request): import rpyc from cPickle import loads put_string = '' if not 'ModuleID' in request.GET: Module_Id = "" else: Module_Id = request.GET['ModuleID'] put_string += Module_Id + "@@" if not 'hosts' in request.GET: Hosts = "" else: Hosts = request.GET['hosts'] put_string += Hosts + "@@" if not 'sys_param_1' in request.GET: Sys_param_1 = "" else: Sys_param_1 = request.GET['sys_param_1'] put_string += Sys_param_1 + "@@" if not 'sys_param_2' in request.GET: Sys_param_2 = "" else: Sys_param_2 = request.GET['sys_param_2'] put_string += Sys_param_2 + "@@" try: conn = rpyc.connect(host='127.0.0.1', port=11511) conn.root.login('OMuser', '123456') except Exception, e: logger.error('connect rpyc server error:' + str(e)) return HttpResponse('connect rpyc server error:' + str(e))
def search_server_list(request): try: for i in CENTER_SERVER.keys(): recv_data = client_send_data("{'salt':1,'act':'test.ping','hosts':'*','argv':[]}",CENTER_SERVER[i][0],CENTER_SERVER[i][1]) dict_data = eval(recv_data) for k,v in dict_data.items(): uniq_test = server_list.objects.filter(server_name=k) if v == True and not uniq_test: ip = client_send_data("{'salt':1,'act':'grains.item','hosts':'%s','argv':['ipv4']}" % k,CENTER_SERVER[i][0],CENTER_SERVER[i][1]) ip = eval(ip) ip[k]['ipv4'].pop(0) os = client_send_data("{'salt':1,'act':'grains.item','hosts':'%s','argv':['os']}" % k,CENTER_SERVER[i][0],CENTER_SERVER[i][1]) os = eval(os) belong_to = i server_list.objects.create(server_name=k,ip=ip[k]['ipv4'],os=os[k]['os'],belong_to=belong_to,status=1) elif uniq_test: orm_server = server_list.objects.get(server_name=k) orm_server.status = 1 orm_server.save() for i in server_list.objects.all(): if not i.server_name in dict_data.keys(): i.status = 0 i.save() return HttpResponse(simplejson.dumps({'code':0,'msg':u'获取完成'}),content_type="application/json") except Exception,e: logger.error(e) return HttpResponse(simplejson.dumps({'code':1,'msg':u'获取失败'}),content_type="application/json")
def run_cmd(request): try: server_names = request.POST.get('server_names') belong_tos = request.POST.get('belong_tos') server_names = server_names.split(',') belong_tos = belong_tos.split(',') cmd = request.POST.get('cmd') time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') servers = {} cmd_results = '' for i in zip(server_names,belong_tos): if not servers.has_key(i[1]): servers[i[1]] = [] servers[i[1]].append(i[0]) for k,v in servers.items(): v = ','.join(v) cmd_result = client_send_data("{'salt':1,'act':'cmd.run','hosts':'%s','argv':%s}" % (v,cmd.split(',')),CENTER_SERVER[k][0],CENTER_SERVER[k][1]) cmd_result = convert_str_to_html(cmd_result) if cmd_results: cmd_results = cmd_result else: cmd_results = cmd_results + '<br><br><br><br>' + cmd_result for i in server_names: log.objects.create(source_ip=i,username=request.user.username,command=cmd,time=time_now) return HttpResponse(simplejson.dumps({'code':0,'msg':u'完成执行完成','cmd_results':cmd_results}),content_type="application/json") except Exception,e: logger.error(e) return HttpResponse(simplejson.dumps({'code':1,'msg':u'完成执行失败'}),content_type="application/json")
def module_run(request): import rpyc from cPickle import loads put_string="" if not 'ModuleID' in request.GET: Module_Id="" else: Module_Id=request.GET['ModuleID'] put_string+=Module_Id+"@@" if not 'hosts' in request.GET: Hosts="" else: Hosts=request.GET['hosts'] put_string+=Hosts+"@@" if not 'sys_param_1' in request.GET: Sys_param_1="" else: Sys_param_1=request.GET['sys_param_1'] put_string+=Sys_param_1+"@@" if not 'sys_param_2' in request.GET: Sys_param_2="" else: Sys_param_2=request.GET['sys_param_2'] put_string+=Sys_param_2+"@@" try: conn=rpyc.connect('192.168.1.20',11511) conn.root.login('OMuser','KJS23o4ij09gHF734iuhsdfhkGYSihoiwhj38u4h') except Exception,e: logger.error('connect rpyc server error:'+str(e)) return HttpResponse('connect rpyc server error:'+str(e))
def module_run(request): import rpyc from cPickle import loads put_string = '' if not 'ModuleID' in request.GET: Module_Id = "" else: Module_Id = request.GET['ModuleID'] put_string+=Module_Id+"@@" if not 'hosts' in request.GET: Hosts = "" else: Hosts = request.GET['hosts'] put_string+=Hosts+"@@" if not 'sys_param_1' in request.GET: Sys_param_1 = "" else: Sys_param_1 = request.GET['sys_param_1'] put_string+=Sys_param_1+"@@" if not 'sys_param_2' in request.GET: Sys_param_2 = "" else: Sys_param_2 = request.GET['sys_param_2'] put_string+=Sys_param_2+"@@" try: conn = rpyc.connect(host='127.0.0.1', port=11511) conn.root.login('OMuser','123456') except Exception,e: logger.error('connect rpyc server error:'+str(e)) return HttpResponse('connect rpyc server error:'+str(e))
def user_perm_save(request): _id = request.POST.get('id') username = request.POST.get('username') name = request.POST.get('name') web_perm = request.POST.get('web_perm') # server_password = request.POST.get('server_password') server_groups = request.POST.get('server_groups') three_months_later = datetime.datetime.now()+datetime.timedelta(91) aes = crypt.crypt_aes(SECRET_KEY[:32]) # server_password = aes.encrypt_aes(server_password) try: if _id =='': # if server_password: # perm.objects.create(username=username,name=name,web_perm=web_perm,server_password=server_password,server_groups=server_groups,\ # server_password_expire=three_months_later.strftime('%Y-%m-%d')) # else: # perm.objects.create(username=username,name=name,web_perm=web_perm,server_password=server_password,server_groups=server_groups) perm.objects.create(username=username,name=name,web_perm=web_perm,server_groups=server_groups) else: orm = perm.objects.get(id=_id) orm.username = username orm.name = name orm.web_perm = web_perm # if server_password: # orm.server_password = server_password orm.server_groups = server_groups orm.save() return HttpResponse(json.dumps({'code':0,'msg':u'保存成功'}),content_type="application/json") except Exception,e: logger.error(e) return HttpResponse(json.dumps({'code':1,'msg':str(e)}),content_type="application/json")
def salt_pillar_save(request): _id = request.POST.get("id") center_server = request.POST.get("center_server") name = request.POST.get("name") content = request.POST.get("content") try: if _id == "": saltstack_pillar.objects.create(center_server=center_server, name=name, content=content) else: orm = saltstack_pillar.objects.get(id=_id) orm.center_server = center_server orm.content = content orm.save() for i in center_server.split(","): master_dir = commands.getoutput( '''ssh %s "grep -A2 '^pillar_roots' /etc/salt/master |grep 'base:' -A1|grep '-'|cut -d'-' -f2"''' % CENTER_SERVER[i][0] ) os.system('''ssh %s "cat > %s/%s.sls << EOF\n%s\nEOF"''' % (CENTER_SERVER[i][0], master_dir, name, content)) content_top = """base:\n '*':\n""" for j in saltstack_pillar.objects.all(): if i in j.center_server.split(","): content_top += """ - %s\n""" % j.name content_top += "EOF" os.system('''ssh %s "cat > %s/top.sls << EOF\n%s"''' % (CENTER_SERVER[i][0], master_dir, content_top)) return HttpResponse(json.dumps({"code": 0, "msg": u"保存成功"}), content_type="application/json") except Exception, e: logger.error(e) return HttpResponse(json.dumps({"code": 1, "msg": str(e)}), content_type="application/json")
def salt_pillar_del(request): try: _id = request.POST.get("id") orm = saltstack_pillar.objects.get(id=_id) for i in orm.center_server.split(","): master_dir = commands.getoutput( '''ssh %s "grep -A2 '^pillar_roots' /etc/salt/master |grep 'base:' -A1|grep '-'|cut -d'-' -f2"''' % CENTER_SERVER[i][0] ) os.system('''ssh %s "rm -r %s/%s\.sls"''' % (CENTER_SERVER[i][0], master_dir, orm.name)) orm.delete() for i in CENTER_SERVER.keys(): master_dir = commands.getoutput( '''ssh %s "grep -A2 '^pillar_roots' /etc/salt/master |grep 'base:' -A1|grep '-'|cut -d'-' -f2"''' % CENTER_SERVER[i][0] ) content_top = """base:\n '*':\n""" for j in saltstack_pillar.objects.all(): if i in j.center_server.split(","): content_top += """ - %s\n""" % j.name content_top += "EOF" if len(re.findall(r"\n", content_top)) < 3: content_top = "" os.system('''ssh %s "cat > %s/top.sls << EOF\n%s"''' % (CENTER_SERVER[i][0], master_dir, content_top)) return HttpResponse(json.dumps({"code": 0, "msg": u"删除成功"}), content_type="application/json") except Exception, e: logger.error(e) return HttpResponse(json.dumps({"code": 1, "msg": u"删除失败"}), content_type="application/json")
def salt_pillar_save(request): _id = request.POST.get('id') center_server = request.POST.get('center_server') name = request.POST.get('name') content = request.POST.get('content') try: if _id =='': saltstack_pillar.objects.create(center_server=center_server,name=name,content=content) else: orm = saltstack_pillar.objects.get(id=_id) orm.center_server = center_server orm.content = content orm.save() for i in center_server.split(','): master_dir = commands.getoutput('''ssh %s "grep -A2 '^pillar_roots' /etc/salt/master |grep 'base:' -A1|grep '-'|cut -d'-' -f2"''' % CENTER_SERVER[i][0]) os.system('''ssh %s "cat > %s/%s.sls << EOF\n%s\nEOF"''' % (CENTER_SERVER[i][0],master_dir,name,content)) content_top = '''base:\n '*':\n''' for j in saltstack_pillar.objects.all(): if i in j.center_server.split(','): content_top += ''' - %s\n''' % j.name content_top += 'EOF' os.system('''ssh %s "cat > %s/top.sls << EOF\n%s"''' % (CENTER_SERVER[i][0],master_dir,content_top)) return HttpResponse(json.dumps({'code':0,'msg':u'保存成功'}),content_type="application/json") except Exception,e: logger.error(e) return HttpResponse(json.dumps({'code':1,'msg':str(e)}),content_type="application/json")
def assets_asset_save(request): _id = request.POST.get('id') assets_type = request.POST.get('assets_type') comment = request.POST.get('comment') assets_code = request.POST.get('assets_code') name = request.POST.get('name') if _id =='': orm = asset(name=name,assets_type=assets_type,assets_code=assets_code,comment=comment) comment_info = u'%s %s %s 入库' % (name,assets_type,assets_code) orm_log = log(comment=comment_info) else: orm = asset.objects.get(id=int(_id)) orm.name = name orm.assets_type = assets_type orm.assets_code = assets_code orm.comment = comment comment_info = u'%s %s %s 编辑' % (name,assets_type,assets_code) orm_log = log(comment=comment_info) try: orm_log.save() orm.save() return HttpResponse(json.dumps({'code':0,'msg':u'保存成功'}),content_type="application/json") except Exception,e: logger.error(e,comment) return HttpResponse(json.dumps({'code':1,'msg':str(e)}),content_type="application/json")
def module_run(request): import rpyc from cPickle import loads put_string = "" if not 'ModuleID' in request.GET: Module_Id = "" else: Module_Id = request.GET['ModuleID'] put_string += Module_Id + "@@" if not 'hosts' in request.GET: Hosts = "" else: Hosts = request.GET['hosts'] put_string += Hosts + "@@" if not 'sys_param_1' in request.GET: Sys_param_1 = "" else: Sys_param_1 = request.GET['sys_param_1'] put_string += Sys_param_1 + "@@" if not 'sys_param_2' in request.GET: Sys_param_2 = "" else: Sys_param_2 = request.GET['sys_param_2'] put_string += Sys_param_2 + "@@" try: conn = rpyc.connect('192.168.1.20', 11511) conn.root.login('OMuser', 'KJS23o4ij09gHF734iuhsdfhkGYSihoiwhj38u4h') except Exception, e: logger.error('connect rpyc server error:' + str(e)) return HttpResponse('connect rpyc server error:' + str(e))
def salt_state_save(request): _id = request.POST.get('id') center_server = request.POST.get('center_server') name = request.POST.get('name') content = request.POST.get('content') try: for i in center_server.split(','): master_dir = commands.getoutput('''ssh %s "grep -A2 '^file_roots' /etc/salt/master |grep 'base:' -A1|grep '-'|cut -d'-' -f2"''' % CENTER_SERVER[i][0]) # os.system('''ssh %s "mkdir -p %s/%s;cat > %s/%s/init.sls << EOF\n%s\nEOF"''' % (CENTER_SERVER[i][0],master_dir,name,master_dir,name,content)) cmd = '''mkdir -p %s/%s;cat > %s/%s/init.sls << EOF\n%s\nEOF''' % (master_dir,name,master_dir,name,content.replace('$','\$')) r_cmd(CENTER_SERVER[i][0],cmd) if _id =='': saltstack_state.objects.create(center_server=center_server,name=name,content=content) else: orm = saltstack_state.objects.get(id=_id) # old_name = orm.name orm.center_server = center_server orm.content = content orm.save() # if name != old_name: # os.system('''ssh %s "rm -r %s/%s"''' % (CENTER_SERVER[i][0],master_dir,old_name)) return HttpResponse(json.dumps({'code':0,'msg':u'保存成功'}),content_type="application/json") except Exception,e: logger.error(e) return HttpResponse(json.dumps({'code':1,'msg':str(e)}),content_type="application/json")
def order_form_save(request): _id = request.POST.get('id') name = request.POST.get('name') type = request.POST.get('type') # comment = request.POST.get('comment') time_now = datetime.datetime.now().time() begin = datetime.datetime.now().date() end = datetime.datetime.now() + datetime.timedelta(1) end = end.date() if not request.user.is_staff: if type == u'午餐' and time_now > datetime.time(11,00): return HttpResponse(simplejson.dumps({'code':1,'msg':u'已经超过午餐订餐时间'}),content_type="application/json") elif type == u'晚餐' and time_now > datetime.time(16,00): return HttpResponse(simplejson.dumps({'code':1,'msg':u'已经超过晚餐订餐时间'}),content_type="application/json") try: if _id =='': for i in name.split(','): check_orm = order.objects.filter(add_time__range=(begin,end)).filter(name=i).filter(type=type) if check_orm: return HttpResponse(simplejson.dumps({'code':1,'msg':u'您已订过餐'}),content_type="application/json") orm = order(name=i,type=type,comment='',order_name=request.user.first_name,star=0) orm.save() # else: # orm = user.objects.get(id=int(_id)) # orm.name = name # orm.department = department # orm.comment = comment # # # orm.save() return HttpResponse(simplejson.dumps({'code':0,'msg':u'订餐成功'}),content_type="application/json") except Exception,e: logger.error(e,comment) return HttpResponse(simplejson.dumps({'code':1,'msg':str(e)}),content_type="application/json")
def last_order_form_save(request): # _id = request.POST.get('id') # name = request.POST.get('name') # type = request.POST.get('type') # comment = request.POST.get('comment') name = request.user.first_name orm = order.objects.filter(order_name=name).order_by('add_time').reverse() last_order_time = orm[0].add_time print last_order_time begin = last_order_time.date() end = last_order_time + datetime.timedelta(1) end = end.date() time_now = datetime.datetime.now().time() begin_now = datetime.datetime.now().date() end_now = datetime.datetime.now() + datetime.timedelta(1) end_now = end_now.date() if not request.user.is_staff: if time_now > datetime.time(11, 00): return HttpResponse(simplejson.dumps({ 'code': 1, 'msg': u'已经超过一键订餐时间' }), content_type="application/json") try: orm2 = order.objects.filter(add_time__range=(begin, end)).filter( order_name=name) order_list = [] for i in orm2: order_list.append((i.name, i.type)) print order_list for i in order_list: check_orm = order.objects.filter( add_time__range=(begin_now, end_now)).filter(name=i[0]).filter(type=i[1]) if check_orm: continue orm = order(name=i[0], type=i[1], comment='', order_name=request.user.first_name, star=0) orm.save() return HttpResponse(simplejson.dumps({ 'code': 0, 'msg': u'一键订餐成功' }), content_type="application/json") except Exception, e: logger.error(e) return HttpResponse(simplejson.dumps({ 'code': 1, 'msg': str(e) }), content_type="application/json")
def cmd_template_del(request): try: _id = request.POST.get('id') orm = command_template.objects.get(id=_id) orm.delete() return HttpResponse(json.dumps({'code':0,'msg':u'删除成功'}),content_type="application/json") except Exception,e: logger.error(e) return HttpResponse(json.dumps({'code':1,'msg':u'删除失败'}),content_type="application/json")
def clean_code(self): logger.error('Code field value = %s' % self.cleaned_data["code"]) if self.check_link(self.cleaned_data["code"]): logger.info("if link ok") print "if link OK" self.cleaned_data["code"] = self.youtube_extract(self.cleaned_data["code"]) return self.cleaned_data["code"] else: raise forms.ValidationError("Error ! Url not valid !")
def salt_top_del(request): try: target_id = request.POST.get("target_id") for i in target_id.split(","): orm = saltstack_top.objects.get(id=i) orm.delete() return HttpResponse(json.dumps({"code": 0, "msg": u"删除成功"}), content_type="application/json") except Exception, e: logger.error(e) return HttpResponse(json.dumps({"code": 1, "msg": u"删除失败"}), content_type="application/json")
def salt_top_del(request): try: target_id = request.POST.get('target_id') for i in target_id.split(','): orm = saltstack_top.objects.get(id=i) orm.delete() return HttpResponse(json.dumps({'code':0,'msg':u'删除成功'}),content_type="application/json") except Exception,e: logger.error(e) return HttpResponse(json.dumps({'code':1,'msg':u'删除失败'}),content_type="application/json")
def upload_del(request): _id = request.POST.get('id') orm = upload_files.objects.get(id=_id) try: os.remove(BASE_DIR + '/uploads/' + orm.file_name) orm.delete() return HttpResponse(json.dumps({'code':0,'msg':u'删除成功'}),content_type="application/json") except Exception,e: logger.error(e) return HttpResponse(json.dumps({'code':1,'msg':str(e)}),content_type="application/json")
def server_del(request): try: server_names = request.POST.get('server_names') for i in server_names.split(','): orm = server_list.objects.get(server_name=i) orm.delete() return HttpResponse(json.dumps({'code':0,'msg':u'服务器删除成功'}),content_type="application/json") except Exception,e: logger.error(e) return HttpResponse(json.dumps({'code':1,'msg':u'服务器删除失败'}),content_type="application/json")
def discover_rpc_calls(self): ''' Поиск RPC actoins в установленных модулях ''' # Для всех установленных приложений for application_path in settings.INSTALLED_APPS: # Пытаемся выполнить импорт application = import_module(application_path) ''' Если в приложении есть модуль с именем rpc.py, значит возможно приложение предоставляет некоторые из своих классов для удаленного вызова ''' try: rpc_module = import_module('%s.rpc' % application_path) ''' Для всех классов из модуля, если они расширяют класс ExtDirectRPCAction, регистрируем в списке API их публичные (не приватные) вызовы ''' try: for class_name, class_class in getmembers( rpc_module, isclass): try: if issubclass(class_class, ExtDirectRPCAction): # Создаем экземпляр класса Action class_instance = class_class() # Регистрируем все его методы, не являющиеся приватными for method_name, method in getmembers( class_instance, ismethod): # Имена приватных методов начинаются с символа '_' if not method_name.startswith('_'): # Если метод не приватный, регистрируем его self.dispatcher().register_method( class_name, method_name, method) except Exception, e: logger.error(e) except Exception, e: logger.error(e) except: ''' Сюда мы попадаем, если не смогли импортировать модуль rpc.py Возможно, этого модуля просто не существует в установленном приложении, но если он существует и при этом не импортирован, значит что-то пошло не так. ''' if module_has_submodule(application, 'rpc'): raise
def assets_user_save(request): _id = request.POST.get('id') department = request.POST.get('department') comment = request.POST.get('comment') assets = request.POST.get('asset') name = request.POST.get('name') assets_data = '' try: if _id =='': for i in assets.split(','): orm_assets = asset.objects.get(id=i) orm_assets.status = '已发放' orm_assets.save() comment_info = u'%s %s %s 出库,发放给<%s>' % (orm_assets.name,orm_assets.assets_type,orm_assets.assets_code,name) orm_log = log(comment=comment_info) orm_log.save() if assets_data == '': assets_data = '< %s %s %s >' % (orm_assets.name,orm_assets.assets_type,orm_assets.assets_code) else: assets_data = '%s< %s %s %s >' % (assets_data,orm_assets.name,orm_assets.assets_type,orm_assets.assets_code) orm_user = user(name=name,department=department,assets=assets_data,comment=comment,assets_id=assets) orm_user.save() else: orm = user.objects.get(id=_id) for i in orm.assets_id.split(','): if not i in assets.split(','): orm_assets = asset.objects.get(id=i) orm_assets.status = '未发放' orm_assets.save() comment_info = u'%s %s %s 入库库,从<%s>处收回' % (orm_assets.name,orm_assets.assets_type,orm_assets.assets_code,name) orm_log = log(comment=comment_info) orm_log.save() for i in assets.split(','): if not i in orm.assets_id.split(','): orm_assets = asset.objects.get(id=i) orm_assets.status = '已发放' orm_assets.save() comment_info = u'%s %s %s 出库,发放给<%s>' % (orm_assets.name,orm_assets.assets_type,orm_assets.assets_code,name) orm_log = log(comment=comment_info) orm_log.save() if assets_data == '': assets_data = '< %s %s %s >' % (orm_assets.name,orm_assets.assets_type,orm_assets.assets_code) else: assets_data = '%s< %s %s %s >' % (assets_data,orm_assets.name,orm_assets.assets_type,orm_assets.assets_code) orm.name = name orm.department = department orm.assets = assets_data orm.comment = comment orm.assets_id = assets orm.save() return HttpResponse(json.dumps({'code':0,'msg':u'保存成功'}),content_type="application/json") except Exception,e: logger.error(e,comment) return HttpResponse(json.dumps({'code':1,'msg':str(e)}),content_type="application/json")
def discover_rpc_calls(self): ''' Поиск RPC actoins в установленных модулях ''' # Для всех установленных приложений for application_path in settings.INSTALLED_APPS: # Пытаемся выполнить импорт application = import_module(application_path) ''' Если в приложении есть модуль с именем rpc.py, значит возможно приложение предоставляет некоторые из своих классов для удаленного вызова ''' try: rpc_module = import_module('%s.rpc' % application_path) ''' Для всех классов из модуля, если они расширяют класс ExtDirectRPCAction, регистрируем в списке API их публичные (не приватные) вызовы ''' try: for class_name, class_class in getmembers(rpc_module, isclass): try: if issubclass(class_class, ExtDirectRPCAction): # Создаем экземпляр класса Action class_instance = class_class() # Регистрируем все его методы, не являющиеся приватными for method_name, method in getmembers(class_instance, ismethod): # Имена приватных методов начинаются с символа '_' if not method_name.startswith('_'): # Если метод не приватный, регистрируем его self.dispatcher().register_method(class_name, method_name, method) except Exception, e: logger.error(e) except Exception, e: logger.error(e) except: ''' Сюда мы попадаем, если не смогли импортировать модуль rpc.py Возможно, этого модуля просто не существует в установленном приложении, но если он существует и при этом не импортирован, значит что-то пошло не так. ''' if module_has_submodule(application, 'rpc'): raise
def check_permission(perm_name,username): try: flag = 0 orm = perm.objects.get(username=username) for i in orm.web_perm.split(','): if perm_name == i or u'所有权限' == i: flag += 1 return flag except Exception,e: logger.error(e) return 0
def audit_get_data(request): ip = request.POST.get('ip') username = request.POST.get('username') command = request.POST.get ('command') time = request.POST.get ('time') last_command = log.objects.all().order_by('id').reverse()[:1] for i in last_command: if i.command == command: return HttpResponse('duplicate') try: log.objects.create(source_ip=ip,username=username,command=command,time=time) return HttpResponse('success') except Exception,e: logger.error(e) return HttpResponse('error')
def salt_top_save(request): _id = request.POST.get("id") # center_server = request.POST.get('center_server') target = request.POST.get("target") state = request.POST.get("state") # master_dir = commands.getoutput('''ssh %s "grep -A2 '^file_roots' /etc/salt/master |grep 'base:' -A1|grep '-'|cut -d'-' -f2"''' % CENTER_SERVER[center_server][0]) try: center_server = "" for i in target.split(","): orm_server = server_list.objects.get(server_name=i) if center_server: if orm_server.belong_to != center_server: return HttpResponse( json.dumps({"code": 1, "msg": u"目标主机不在同一个中心服务器上"}), content_type="application/json" ) else: center_server = orm_server.belong_to for j in state.split(","): orm_state = saltstack_state.objects.get(name=j) if not center_server in orm_state.center_server.split(","): return HttpResponse( json.dumps({"code": 1, "msg": u"目标主机的中心服务器上没有这个模块"}), content_type="application/json" ) if _id == "": # for i in target.split(','): # if saltstack_top.objects.filter(target=i): # return HttpResponse(json.dumps({'code':1,'msg':u'目标主机已存在对应'}),content_type="application/json") # else: saltstack_top.objects.create(center_server=center_server, target=target, state=state) else: orm = saltstack_top.objects.get(id=_id) orm.center_server = center_server orm.target = target orm.state = state orm.save() # content = 'base:\n' # for i in saltstack_top.objects.all(): # content += " '%s':\n" % i.target # for j in i.state.split(','): # content += ' - %s\n' % j # content += 'EOF' # os.system('''ssh %s "cat > %s/top.sls << EOF\n%s"''' % (CENTER_SERVER[center_server][0],master_dir,content)) return HttpResponse(json.dumps({"code": 0, "msg": u"保存成功"}), content_type="application/json") except Exception, e: logger.error(e) return HttpResponse(json.dumps({"code": 1, "msg": str(e)}), content_type="application/json")
def cmd_template_save(request): _id = request.POST.get('id') description = request.POST.get('description') cmd = request.POST.get('cmd') try: if _id =='': command_template.objects.create(description=description,cmd=cmd) else: orm = command_template.objects.get(id=_id) orm.description = description orm.cmd = cmd orm.save() return HttpResponse(json.dumps({'code':0,'msg':u'保存成功'}),content_type="application/json") except Exception,e: logger.error(e) return HttpResponse(json.dumps({'code':1,'msg':str(e)}),content_type="application/json")
def run_cmd(request): try: server_names = request.POST.get('server_names') belong_tos = request.POST.get('belong_tos') server_names = server_names.split(',') belong_tos = belong_tos.split(',') cmd = request.POST.get('cmd') cmd_template = request.POST.get('cmd_template') for center_server in belong_tos: if not check_center_server_up(CENTER_SERVER[center_server][0],CENTER_SERVER[center_server][1]): return HttpResponse(json.dumps({'code':1,'msg':u'无法连接到%s' % center_server}),content_type="application/json") time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') servers = {} cmd_results = '' for i in zip(server_names,belong_tos): if not servers.has_key(i[1]): servers[i[1]] = [] servers[i[1]].append(i[0]) for k,v in servers.items(): v = ','.join(v) if cmd: cmd_result = client_send_data(json.dumps({'salt':1,'act':'cmd.run','hosts':v,'argv':cmd.split(',,')}),CENTER_SERVER[k][0],CENTER_SERVER[k][1]) cmd_result = convert_str_to_html(cmd_result) if not cmd_results: cmd_results = cmd_result else: cmd_results = cmd_results + '<br><br><br><br>' + cmd_result if cmd_template: orm = command_template.objects.get(description=cmd_template) command = '''echo '%s' > /tmp/tempfile && if awk 'FNR==1' /tmp/tempfile|grep python > /dev/null 2>&1;then python /tmp/tempfile;else bash /tmp/tempfile;fi;rm -rf /tmp/tempfile''' % re.sub(r"'",'''\'"'"\'''',orm.cmd) cmd_result = client_send_data(json.dumps({'salt':1,'act':'cmd.run','hosts':v,'argv':command.split(',,')}),CENTER_SERVER[k][0],CENTER_SERVER[k][1]) cmd_result = convert_str_to_html(cmd_result) if cmd_results: cmd_results = cmd_result else: cmd_results = cmd_results + '<br><br><br><br>' + cmd_result cmd = u'模板 < %s >' % cmd_template for i in server_names: log.objects.create(source_ip=i,username=request.user.username,command=cmd,time=time_now) return HttpResponse(json.dumps({'code':0,'msg':u'完成执行完成','cmd_results':cmd_results}),content_type="application/json") except Exception,e: logger.error(e) return HttpResponse(json.dumps({'code':1,'msg':u'完成执行失败'}),content_type="application/json")
def salt_state_del(request): try: _id = request.POST.get('id') orm = saltstack_state.objects.get(id=_id) state_list = [] for i in saltstack_top.objects.all(): for j in i.state.split(','): state_list.append(j) if orm.name in state_list: return HttpResponse(json.dumps({'code':1,'msg':u'模块已被应用无法删除'}),content_type="application/json") for i in orm.center_server.split(','): master_dir = commands.getoutput('''ssh %s "grep -A2 '^file_roots' /etc/salt/master |grep 'base:' -A1|grep '-'|cut -d'-' -f2"''' % CENTER_SERVER[i][0]) os.system('''ssh %s "rm -r %s/%s"''' % (CENTER_SERVER[i][0],master_dir,orm.name)) orm.delete() return HttpResponse(json.dumps({'code':0,'msg':u'删除成功'}),content_type="application/json") except Exception,e: logger.error(e) return HttpResponse(json.dumps({'code':1,'msg':u'删除失败'}),content_type="application/json")
def server_group_save(request): _id = request.POST.get('id') comment = request.POST.get('comment') server_group_name = request.POST.get('server_group_name') members_server = request.POST.get('members_server') try: if _id =='': server_group_list.objects.create(server_group_name=server_group_name,members_server=members_server,comment=comment) else: orm = server_group_list.objects.get(id=_id) orm.server_group_name = server_group_name orm.members_server = members_server orm.comment = comment orm.save() return HttpResponse(json.dumps({'code':0,'msg':u'保存成功'}),content_type="application/json") except Exception,e: logger.error(e) return HttpResponse(json.dumps({'code':1,'msg':str(e)}),content_type="application/json")
def audit_get_data(request): orm = server_list.objects.all() allow_ip_list = [] for i in orm: allow_ip_list.append(i.external_ip) if get_ip(request) in allow_ip_list: ip = request.POST.get('ip') username = request.POST.get('username') command = request.POST.get ('command') time = request.POST.get ('time') last_command = log.objects.filter(source_ip=ip).order_by('id').reverse()[:1] for i in last_command: if i.command == command: return HttpResponse('duplicate') if ip and username and command and time: try: log.objects.create(source_ip=ip,username=username,command=command,time=time) return HttpResponse('success') except Exception,e: logger.error(e) return HttpResponse('error') else: return HttpResponse('error')
def handle_uploaded_file(request,f): file_name = '' try: path = BASE_DIR + '/uploads/' file_name = path + f.name if not os.path.exists(path): os.makedirs(path) if os.path.isfile(file_name): time = datetime.datetime.now().strftime('%Y%m%d%H%M%S') os.rename(file_name,file_name + '_' + time) orm = upload_files.objects.get(file_name=f.name) orm.file_name = f.name + '_' + time orm.save() file = open(file_name, 'wb+') for chunk in f.chunks(): file.write(chunk) file.close() file_size = os.path.getsize(file_name) upload_files.objects.create(file_name=f.name,file_size=file_size,upload_user=request.user.username) result_code = 0 except Exception, e: logger.error(e) result_code = 1
def salt_state_save(request): _id = request.POST.get("id") center_server = request.POST.get("center_server") name = request.POST.get("name") content = request.POST.get("content") try: for i in center_server.split(","): master_dir = commands.getoutput( '''ssh %s "grep -A2 '^file_roots' /etc/salt/master |grep 'base:' -A1|grep '-'|cut -d'-' -f2"''' % CENTER_SERVER[i][0] ) # os.system('''ssh %s "mkdir -p %s/%s;cat > %s/%s/init.sls << EOF\n%s\nEOF"''' % (CENTER_SERVER[i][0],master_dir,name,master_dir,name,content)) cmd = """mkdir -p %s/%s;cat > %s/%s/init.sls << EOF\n%s\nEOF""" % ( master_dir, name, master_dir, name, content.replace("$", "\$"), ) r_cmd(CENTER_SERVER[i][0], cmd) if _id == "": saltstack_state.objects.create(center_server=center_server, name=name, content=content) else: orm = saltstack_state.objects.get(id=_id) # old_name = orm.name orm.center_server = center_server orm.content = content orm.save() # if name != old_name: # os.system('''ssh %s "rm -r %s/%s"''' % (CENTER_SERVER[i][0],master_dir,old_name)) return HttpResponse(json.dumps({"code": 0, "msg": u"保存成功"}), content_type="application/json") except Exception, e: logger.error(e) return HttpResponse(json.dumps({"code": 1, "msg": str(e)}), content_type="application/json")
def order_form_save(request): return render(request, 'public/no_passing.html') _id = request.POST.get('id') name = request.POST.get('name') type = request.POST.get('type') # comment = request.POST.get('comment') time_now = datetime.datetime.now().time() begin = datetime.datetime.now().date() end = datetime.datetime.now() + datetime.timedelta(1) end = end.date() if not request.user.is_staff: if type == u'午餐' and time_now > datetime.time(11, 00): return HttpResponse(simplejson.dumps({ 'code': 1, 'msg': u'已经超过午餐订餐时间' }), content_type="application/json") elif type == u'晚餐' and time_now > datetime.time(16, 00): return HttpResponse(simplejson.dumps({ 'code': 1, 'msg': u'已经超过晚餐订餐时间' }), content_type="application/json") try: if _id == '': for i in name.split(','): check_orm = order.objects.filter( add_time__range=(begin, end)).filter(name=i).filter(type=type) if check_orm: return HttpResponse(simplejson.dumps({ 'code': 1, 'msg': u'您已订过餐' }), content_type="application/json") orm = order(name=i, type=type, comment='', order_name=request.user.first_name, star=0) orm.save() # else: # orm = user.objects.get(id=int(_id)) # orm.name = name # orm.department = department # orm.comment = comment # # # orm.save() return HttpResponse(simplejson.dumps({ 'code': 0, 'msg': u'订餐成功' }), content_type="application/json") except Exception, e: logger.error(e) return HttpResponse(simplejson.dumps({ 'code': 1, 'msg': str(e) }), content_type="application/json")
def index(request): logger.error('Test Django Logging') return HttpResponse("Hello world Django.")