def receive(self, text=None, bytes=None, **kwargs): """ Called when a message is received with either text or bytes filled out. """ #self.close() self.clientip = '127.0.0.1' self.username = self.message.user.username try: self.role = self.message.user.userprofile.role except: self.role = 'none' data = json.loads(self.message['text']) step = 0 ### step one ### info = {} info['step'] = 'one' info['project'] = data['project'] info['minion_id'] = data['minion_id'] self.message.reply_channel.send({'text': json.dumps(info)}) ### final step ### info = {} info['step'] = 'final' commandexe = Command(data['minion_id'], 'state.sls', expr_form='list') info['results'] = commandexe.StateSls('nginx.conf_dev') #info['results'] = commandexe.StateSls('nginx.reload') #info['results'] = dict(info['results'], **commandexe.StateSls('nginx.reload')) self.message.reply_channel.send({'text': json.dumps(info)}) self.close()
def CommandDeploy(request): if request.is_websocket(): global username, role, clientip username = request.user.username try: role = request.user.userprofile.role except: role = 'none' clientip = request.META['REMOTE_ADDR'] #logger.info(dir(request.websocket)) #message = request.websocket.wait() #配置文件目录 conf_dir = "/srv/salt/nginx/files" for postdata in request.websocket: if not postdata: break #logger.info(type(postdata)) data = json.loads(postdata) ### step one ### info_one = {} info_one['step'] = 'one' info_one['project'] = data['project'] info_one['minion_id'] = data['minion_id'] request.websocket.send(json.dumps(info_one)) logger.info('%s is requesting. %s 执行参数:%s' % (clientip, request.get_full_path(), data)) ### final step ### info_final = {} info_final['step'] = 'final' commandexe = Command(data['minion_id'], 'state.sls', expr_form='list') #同步配置文件 info_final['results'] = commandexe.StateSls('nginx.conf') #reload服务 info_final['results'] = commandexe.StateSls('nginx.reload') #info_final['results'] = dict(info_final['results'], **commandexe.StateSls('nginx.reload')) request.websocket.send(json.dumps(info_final)) ### close websocket ### request.websocket.close()
def CommandExecute(request): if request.is_websocket(): global username, role, clientip username = request.user.username try: role = request.user.userprofile.role except: role = 'none' clientip = request.META['REMOTE_ADDR'] for postdata in request.websocket: if not postdata: break data = json.loads(postdata) logger.info('%s is requesting. %s 执行参数:%s' % (clientip, request.get_full_path(), data)) #request.websocket.send(json.dumps(data)) ### step one ## info_one = {} info_one['step'] = 'one' request.websocket.send(json.dumps(info_one)) #time.sleep(2) ### final step ### info_final = {} info_final['step'] = 'final' arglist = ["runas=%s" % data['exe_user']] arglist.append(data['arguments']) commandexe = Command( data['target'], data['function'], arglist, data['expr_form'], ) if data['function'] == 'test.ping': info_final['results'] = commandexe.TestPing() elif data['function'] == 'cmd.run': info_final['results'] = commandexe.CmdRun() elif data['function'] == 'state.sls': info_final['results'] = commandexe.StateSls(data['arguments']) #logger.info(json.dumps(info_final)) request.websocket.send(json.dumps(info_final)) ### close websocket ### request.websocket.close()
def receive(self, text=None, bytes=None, **kwargs): """ Called when a message is received with either text or bytes filled out. """ #self.close() data = json.loads(self.message['text']) self.clientip = '127.0.0.1' self.username = self.message.user.username try: self.role = self.message.user.userprofile.role except: self.role = 'none' ### step one ## info = {} info['step'] = 'one' self.message.reply_channel.send({'text': json.dumps(info)}) #time.sleep(2) ### final step ### info = {} info['step'] = 'final' arglist = ["runas=%s" % data['exe_user']] arglist.append(data['arguments']) commandexe = Command( data['target'], data['function'], arglist, data['expr_form'], ) if data['function'] == 'test.ping': info['results'] = commandexe.TestPing() elif data['function'] == 'cmd.run': info['results'] = commandexe.CmdRun() elif data['function'] == 'state.sls': info['results'] = commandexe.StateSls(data['arguments']) self.message.reply_channel.send({'text': json.dumps(info)}) self.close()
def CheckMinion(request): global username, role, clientip username = request.user.username try: role = request.user.userprofile.role except: role = 'none' clientip = request.META['REMOTE_ADDR'] if request.is_websocket(): for postdata in request.websocket: data = json.loads(postdata) logger.info('%s is requesting. %s 执行参数:%s' % (clientip, request.get_full_path(), data)) result = {} for minion_id in data: commandexe = Command(minion_id, 'test.ping') result['minion_id'] = minion_id result['test_ping'] = commandexe.TestPing()[minion_id] request.websocket.send(json.dumps(result)) ### close websocket ### request.websocket.close() else: if request.method == 'POST': #print (request.body) #return HttpResponse("%s" %request.body) data = json.loads(request.body) result = {} for tgt in data['tgt']: logger.info('%s is requesting %s. data: %s' % (clientip, request.get_full_path(), data)) #logger.info('%s' %(data['tgt'])) commandexe = Command(tgt, 'test.ping') result[tgt] = commandexe.TestPing()[tgt] logger.info(result) return HttpResponse(json.dumps(result)) elif request.method == 'GET': logger.info('%s is requesting %s.' % (clientip, request.get_full_path())) return HttpResponse('You get nothing!') else: logger.info('%s is requesting %s.' % (clientip, request.get_full_path())) return HttpResponse('nothing!')
def UpdateServers(request): if request.is_websocket(): clientip = getIp(request) username = request.user.username try: role = request.user.userprofile.role except: role = 'none' if not username: request.websocket.send('userNone') logger.info('user: 用户名未知 | [WS]%s is requesting. %s' % (clientip, request.get_full_path())) ### close websocket ### request.websocket.close() logger.info('user:%s | [WS]%s is requesting. %s' % (username, clientip, request.get_full_path())) for postdata in request.websocket: if not postdata: ### close websocket ### request.websocket.close() break data = json.loads(postdata) step = 0 for record in data['records']: step += 1 return_info = {} return_info['record'] = record return_info['step'] = step return_info['info'] = "" return_info['permission'] = True return_info['result'] = True #判断是否有权限 if not HasServerPermission(request, record, "change"): return_info['permission'] = False return_info['result'] = False request.websocket.send(json.dumps(return_info)) ### close websocket ### request.websocket.close() break #修改密码 cmd = 'echo "%s" |passwd root --stdin' % data[ 'password'].replace('`', '\`') # `这个符号在Linux命令行有特殊含义,需要转义 result = Command(record['minion_id'], 'cmd.run', cmd, 'glob').CmdRun()[record['minion_id']] if 'all authentication tokens updated successfully' not in result: return_info['result'] = False return_info['info'] = result request.websocket.send(json.dumps(return_info)) continue #密码加密并存放 crypto, status = encryptPasswd(data['password'], record) if not status: return_info['result'] = False return_info['info'] = "密码修改成功,但是密码加密失败:" + result message['text'] = "@arno\r\n" + return_info['info'] sendTelegram(message).send() request.websocket.send(json.dumps(return_info)) continue try: update = minion_t.objects.get( minion_id=record['minion_id']) update.password = crypto update.save() except Exception as e: sendTelegram(message).send() return_info['result'] = False return_info['info'] = "密码修改成功,但是密码存入失败:" + str(e) message['text'] = "@arno\r\n" + return_info['info'] sendTelegram(message).send() request.websocket.send(json.dumps(return_info)) continue request.websocket.send(json.dumps(return_info)) ### close websocket ### request.websocket.close() else: return HttpResponseForbidden('nothing!')
def receive(self, text=None, bytes=None, **kwargs): """ Called when a message is received with either text or bytes filled out. """ #self.close() self.clientip = '127.0.0.1' self.username = self.message.user.username try: self.role = self.message.user.userprofile.role except: self.role = 'none' data = json.loads(self.message['text']) step = 0 for record in data['records']: step += 1 return_info = {} return_info['record'] = record return_info['step'] = step return_info['info'] = "" return_info['permission'] = True return_info['result'] = True #判断是否有权限 if not HasServerPermission(self.message, record, "change"): return_info['permission'] = False return_info['result'] = False self.message.reply_channel.send( {'text': json.dumps(return_info)}) ### close websocket ### self.close() break #修改密码 cmd = 'echo "%s" |passwd root --stdin' % data['password'].replace( '`', '\`') # `这个符号在Linux命令行有特殊含义,需要转义 result = Command(record['minion_id'], 'cmd.run', cmd, 'glob').CmdRun()[record['minion_id']] if 'all authentication tokens updated successfully' not in result: return_info['result'] = False return_info['info'] = result self.message.reply_channel.send( {'text': json.dumps(return_info)}) continue #密码加密并存放 crypto, status = encryptPasswd(data['password'], record) if not status: return_info['result'] = False return_info['info'] = "密码修改成功,但是密码加密失败:" + result message['text'] = "@arno\r\n" + return_info['info'] sendTelegram(message).send() self.message.reply_channel.send( {'text': json.dumps(return_info)}) continue try: update = minion_t.objects.get(minion_id=record['minion_id']) update.password = crypto update.save() except Exception as e: sendTelegram(message).send() return_info['result'] = False return_info['info'] = "密码修改成功,但是密码存入失败:" + str(e) message['text'] = "@arno\r\n" + return_info['info'] sendTelegram(message).send() self.message.reply_channel.send( {'text': json.dumps(return_info)}) continue self.message.reply_channel.send({'text': json.dumps(return_info)}) self.close()
def get_result(result, tomcat_info, code_list, content_body): try: if tomcat_info.server_type == 'app': result['info'] = error_status datas = {} datas['target'] = tomcat_info.minion_id datas['function'] = 'cmd.run' datas[ 'arguments'] = 'ps -ef |grep -i "java" |grep -i " -jar" |grep -v grep' datas['expr_form'] = 'glob' commandexe = Command(datas['target'], datas['function'], datas['arguments'], datas['expr_form']) exe_result = commandexe.CmdRun()[datas['target']] if exe_result == '': result['code'] = error_status elif exe_result == 'not return': result['code'] = exe_result result['info'] = '请检查服务器是否存活' else: result['code'] = '200' result['info'] = '正常' #logger.info(result) else: ret = requests.head(result['url'], headers={'Host': result['domain']}, timeout=16) if tomcat_info.project == 'ALL_TSD_WS' and ret.status_code == 500: result['code'] = '200' else: result['code'] = '%s' % ret.status_code try: title = re.search('<title>.*?</title>', ret.content) result['info'] = title.group().replace('<title>', '').replace( '</title>', '') except AttributeError: if result['code'] in code_list: result['info'] = '正常' else: result['info'] = '失败' except: result['code'] = error_status result['info'] = '失败' if result['code'] == error_status: commandexe = Command(tomcat_info.minion_id, 'test.ping') test_result = commandexe.TestPing()[tomcat_info.minion_id] if test_result == 'not return': result['code'] == test_result result['info'] = '请检查服务器是否存活' #print " %s" %result['code'] try: ret = requests.post(server, data=json.dumps(result), timeout=3) except requests.exceptions.ConnectionError: insert = tomcat_status( access_time=result['access_time'], project=result['project'], domain=result['domain'], url=result['url'], code=result['code'], info=result['info'], ) insert.save() if result['code'] not in code_list: print ColorP( result['code'], fore='red') + " " + result['project'] + ": " + result['url'] try: result['server_type'] = tomcat_project.objects.filter( project=result['project']).first().server_type except: send_mail(['*****@*****.**'], 'tomcat报警', '%s project doesn\'t exists' % result['project']) result['server_type'] = 'unknown' content_body = content_body + "<tr style=\"font-size:15px\"><td >%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" % ( result['access_time'], result['project'], result['server_type'], result['domain'], result['url'], result['code'], result['info']) else: print result['code'] + "\t" + result['project'] + ": " + result['url'] #logger.info(MIMEText(str(result), 'utf-8')) return content_body
def UrlCheckServer(request): if request.is_websocket(): global username, role, clientip username = request.user.username try: role = request.user.userprofile.role except: role = 'none' clientip = request.META['REMOTE_ADDR'] #logger.info(dir(request.websocket)) #message = request.websocket.wait() code_list = ['200', '302', '303', '405'] for postdata in request.websocket: #logger.info(type(postdata)) data = json.loads(postdata) ### step one ### info_one = {} info_one['step'] = 'one' request.websocket.send(json.dumps(info_one)) logger.info('%s is requesting. %s 执行参数:%s' % (clientip, request.get_full_path(), data)) #results = [] ### final step ### info_final = {} info_final['step'] = 'final' info_final['access_time'] = datetime.datetime.now().strftime( '%Y/%m/%d %H:%M:%S') try: if data['server_type'] == 'app': info_final['info'] = error_status datas = {} datas['target'] = data['minion_id'] datas['function'] = 'cmd.run' datas[ 'arguments'] = 'ps -ef |grep -i "java" |grep -i " -jar" |grep -v grep' datas['expr_form'] = 'glob' commandexe = Command(datas['target'], datas['function'], datas['arguments'], datas['expr_form']) exe_result = commandexe.CmdRun()[datas['target']] logger.info("exe_result: %s" % exe_result) if exe_result == '': info_final['code'] = error_status elif exe_result == 'not return': info_final['code'] = exe_result info_final['info'] = '请检查服务器是否存活' else: info_final['code'] = '200' info_final['info'] = '正常' #logger.info(info_final) else: ret = requests.head(data['url'], headers={'Host': data['domain']}, timeout=10) info_final['code'] = '%s' % ret.status_code try: title = re.search('<title>.*?</title>', ret.content) info_final['info'] = title.group().replace( '<title>', '').replace('</title>', '') except AttributeError: if info_final['code'] in code_list: info_final['info'] = '正常' else: info_final['info'] = '失败' except: info_final['code'] = error_status info_final['info'] = '失败' if info_final['code'] == error_status: commandexe = Command(data['minion_id'], 'test.ping') test_result = commandexe.TestPing()[data['minion_id']] if test_result == 'not return': info_final['info'] = '请检查服务器是否存活' request.websocket.send(json.dumps(info_final)) ### close websocket ### request.websocket.close()
def DeployExe(request): global username, role, clientip username = request.user.username try: role = request.user.userprofile.role except: role = 'none' clientip = request.META['REMOTE_ADDR'] if request.is_websocket(): for postdata in request.websocket: logger.info('%s is requesting. %s 执行参数:%s' % (clientip, request.get_full_path(), postdata)) #logger.info(type(postdata)) data = json.loads(postdata) ### step one ### info_one = {} info_one['step'] = 'one' request.websocket.send(json.dumps(info_one)) time.sleep(1) ### final step ### info_final = {} info_final['step'] = 'final' info_final['minion_all'] = len(data['minion_id']) info_final['minion_count'] = 0 #set timeout for specific module if data['module'] == 'init': timeout = 600 elif data['module'] == 'tomcat': timeout = 1200 elif data['module'] == 'php': timeout = 1800 else: timeout = 300 #execute deploy module for minion_id in data['minion_id']: info_final['minion_id'] = minion_id info_final['module'] = data['module'] info_final['project'] = data['project'] info_final['result'] = "" request.websocket.send(json.dumps(info_final)) logger.info('部署参数:%s' % info_final) info_final['minion_count'] += 1 if data['module'] == 'tomcat': commandexe = Command('WTT_100_109', 'cmd.run', '/srv/shell/install_tomcat.sh %s %s' % (minion_id, data['project']), 'glob', timeout=timeout) info_final['result'] = commandexe.CmdRun()['WTT_100_109'] logger.info("%s 部署完成。" % data['project']) else: commandexe = Command(minion_id, 'state.sls', data['module'], 'glob', timeout=timeout) info_final['result'] = commandexe.StateSls()[minion_id] logger.info("%s 部署完成。" % data['module']) request.websocket.send(json.dumps(info_final))