def modify_crontab_list(self,action="create/modify",data={}): #####action 为create/modify,data是一个dict格式 #####创建计划任务 #####data数据格式:{"sid":"","runtime":"","cmd":"","dest":""} ,如果是modify,应该有tid字段 cheungssh_info={"status":False,"content":""} crontab_format="{runtime} {cmd} #{dest}".format(runtime=data["time"],cmd=data["cmd"],dest=data["description"]) try: #####判断sed的分隔符 _sed_t=Crontab.get_sed_separate(crontab_format)#####获取判断字符是否符合规格 if not _sed_t["status"]: raise CheungSSHError(_sed_t["content"]) else: char=_sed_t["content"] ssh=CheungSSH_SSH() configuration = ServersInventory().get_server(sid=data["sid"]) if not configuration["status"]:raise IOError(configuration["content"]) a=ssh.login(**configuration["content"]) if a["status"]: username=configuration["content"]["username"] path=os.path.join("/var/spool/cron/",username) if data["action"]=="modify": #####修改计划任务列表 info=ssh.execute("sed -i '{id}s{char}.*{char}{crontab_format}{char}' {path}".format(char=char,id=data["line_id"],path=path,crontab_format=crontab_format))######替换新的内容 if not info["status"]: raise CheungSSHError(info["content"]) else: #####在文件末尾追加 info=ssh.execute(""" echo '{crontab_format}' >>{path} """.format(crontab_format=crontab_format,path=path)) if not info["status"]: raise CheungSSHError(info["content"]) cheungssh_info["status"] = True else: cheungssh_info["content"]=a["content"] except Exception,e: cheungssh_info={"content":str(e),"status":False}
def delete_crontab(sid,tid): cheungssh_info={"content":"","status":False} ssh=CheungSSH_SSH() conf=CheungSSHControler.convert_id_to_ip(sid) try: if not conf["status"]: raise CheungSSHError(conf["content"]) a=ssh.login(**conf["content"]) if a["status"]: info=ssh.execute("whoami") if info["status"]: user=info["content"].split("\n")[1:][:-1][0] path=os.path.join("/var/spool/cron/",user) info=ssh.execute("sed -i '{id}s/.*/#/' {path}".format(id=tid,path=path)) if not info["status"]: raise CheungSSHError(info["content"]) else: #REDIS.hdel("CHB0833279333-1",conf["content"]["alias"]) data=REDIS.hget("CHB0833279333-1",conf["content"]["alias"]) data=json.loads(data) del data[tid] data=json.dumps(data,encoding="utf8",ensure_ascii=False) REDIS.hset("CHB0833279333-1",conf["content"]["alias"],data) cheungssh_info["status"]=True else: cheungssh_info["content"]=a["content"] except Exception,e: cheungssh_info["status"]=False cheungssh_info["content"]=str(e)
def save_crontab_to_server(action="create/modify",data={}): cheungssh_info={"status":False,"content":""} crontab_format="{runtime} {cmd} #{dest}".format(runtime=data["runtime"],cmd=data["cmd"],dest=data["dest"]) now_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) try: _sed_t=CheungSSHCrontabControler.get_sed_separate(crontab_format) if not _sed_t["status"]: raise CheungSSHError(_sed_t["content"]) else: char=_sed_t["content"] ssh=CheungSSH_SSH() conf=CheungSSHControler.convert_id_to_ip(data["sid"]) if not conf["status"]: raise CheungSSHError(conf["content"]) a=ssh.login(**conf["content"]) if a["status"]: username=conf["content"]["username"] path=os.path.join("/var/spool/cron/",username) if action=="modify": info=ssh.execute("sed -i '{id}s{char}.*{char}{crontab_format}{char}' {path}".format(char=char,id=data["tid"],path=path,crontab_format=crontab_format)) if not info["status"]: raise CheungSSHError(info["content"]) old_data=REDIS.hget("CHB0833279333-1",data["alias"]) if old_data is None:old_data={} else:old_data=json.loads(old_data) data_line={"time":data["runtime"],"dest":data["dest"],"cmd":data["cmd"],"sid":data["sid"],"alias":data["alias"],"collect_time":now_time} line_count=data["tid"] else: info=ssh.execute(""" echo '{crontab_format}' >>{path} """.format(crontab_format=crontab_format,path=path)) if not info["status"]: raise CheungSSHError(info["content"]) info=ssh.execute(""" cat {path}|wc -l """.format(path=path)) if not info["status"]: raise CheungSSHError(info["content"]) line_count=info["content"].split("\r\n")[1] old_data=REDIS.hget("CHB0833279333-1",data["alias"]) if old_data is None:old_data={} else:old_data=json.loads(old_data) data_line={"time":data["runtime"],"dest":data["dest"],"cmd":data["cmd"],"sid":data["sid"],"alias":data["alias"],"collect_time":now_time} old_data[line_count]=data_line _old_data=json.dumps(old_data,encoding="utf8",ensure_ascii=False) REDIS.hset("CHB0833279333-1",data["alias"],_old_data) cheungssh_info={"status":True,"content":old_data} else: cheungssh_info["content"]=a["content"] old_data={} except Exception,e: cheungssh_info={"content":str(e),"status":False}
def save_crontab_to_server(action="create/modify",data={}): #####action 为create/modify,data是一个dict格式 #####创建计划任务 #####data数据格式:{"sid":"","runtime":"","cmd":"","dest":""} ,如果是modify,应该有tid字段 cheungssh_info={"status":False,"content":""} crontab_format="{runtime} {cmd} #{dest}".format(runtime=data["runtime"],cmd=data["cmd"],dest=data["dest"]) now_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) try: #####判断sed的分隔符 _sed_t=CheungSSHCrontabControler.get_sed_separate(crontab_format)#####获取判断字符是否符合规格 if not _sed_t["status"]: raise CheungSSHError(_sed_t["content"]) else: char=_sed_t["content"] ssh=CheungSSH_SSH() conf=CheungSSHControler.convert_id_to_ip(data["sid"]) if not conf["status"]: raise CheungSSHError(conf["content"]) a=ssh.login(**conf["content"]) if a["status"]: username=conf["content"]["username"] path=os.path.join("/var/spool/cron/",username) if action=="modify": #####修改计划任务列表 info=ssh.execute("sed -i '{id}s{char}.*{char}{crontab_format}{char}' {path}".format(char=char,id=data["tid"],path=path,crontab_format=crontab_format))######替换新的内容 if not info["status"]: raise CheungSSHError(info["content"]) old_data=REDIS.hget("CHB0833279333-1",data["alias"]) if old_data is None:old_data={} else:old_data=json.loads(old_data) data_line={"time":data["runtime"],"dest":data["dest"],"cmd":data["cmd"],"sid":data["sid"],"alias":data["alias"],"collect_time":now_time} line_count=data["tid"] else: #####在文件末尾追加 info=ssh.execute(""" echo '{crontab_format}' >>{path} """.format(crontab_format=crontab_format,path=path)) if not info["status"]: raise CheungSSHError(info["content"]) info=ssh.execute(""" cat {path}|wc -l """.format(path=path))#####统计最后一行的tid if not info["status"]: raise CheungSSHError(info["content"]) line_count=info["content"].split("\r\n")[1]#####自己递增行号 #####修改redis记录 old_data=REDIS.hget("CHB0833279333-1",data["alias"]) if old_data is None:old_data={} else:old_data=json.loads(old_data) data_line={"time":data["runtime"],"dest":data["dest"],"cmd":data["cmd"],"sid":data["sid"],"alias":data["alias"],"collect_time":now_time} #####统一的代码部分 old_data[line_count]=data_line#####把新创建的计划任务行,集合起来 _old_data=json.dumps(old_data,encoding="utf8",ensure_ascii=False) REDIS.hset("CHB0833279333-1",data["alias"],_old_data) cheungssh_info={"status":True,"content":old_data}#####返回原始数据给上层django,最后dumps到前端 else: cheungssh_info["content"]=a["content"] old_data={}#####登录失败后的默认值 except Exception,e: cheungssh_info={"content":str(e),"status":False}
def execute_app(appid, username, is_super): cheungssh_info = {"content": [], "status": False} app_conf = False #####设置默认的值,下面要对这个进行判断 try: data = CheungSSHAppAdmin.get_app_list(username, is_super) #####获取全部app数据, if not data["status"]: raise CheungSSHError("读取应用配置出错![%s]" % data["content"]) else: content = data["content"] app_conf = CheungSSHAppAdmin.check_appid_conf( content, appid) #####查询app对应的配置信息 if not app_conf["status"]: raise CheungSSHError("该APP不存在! [%s]" % app_conf["content"]) #####得到了数据,获取sid sid = app_conf["content"]["sid"] #####数据格式为alias,sid,command等 server_conf = cheungssh_modul_controler.CheungSSHControler.convert_id_to_ip( sid) #####获取服务器的配置 if not server_conf["status"]: raise CheungSSHError("应用数据处理失败!%s" % server_conf["content"]) #####在开始之前,修改app状态 CheungSSHAppAdmin.set_app_status("执行中", "", appid) #####成功获取服务器配置信息,开始登录 ssh = CheungSSH_SSH() tmp = ssh.login(**server_conf["content"]) #####检查是否登录成功 if not tmp["status"]: raise CheungSSHError(tmp["content"]) #####ssh登录成功了 command = app_conf["content"]["app_command"] #####app的命令 check_command = app_conf["content"][ "app_check_command"] #####检查命令 command_result = ssh.execute(command, ignore=True) #####APP的执行结果 if re.search("echo *\$\? *$|^ *$", check_command): print "执行系统定义的检查命令" #####如果前端设定的检查命令是echo $?或者为空,则默认使用命令执行的结果; cheungssh_info = command_result print cheungssh_info, 55555555555555555555 else: check_command_result = ssh.execute( check_command) #####app执行后检查命令的结果 cheungssh_info["content"] = "%s </br> %s" % ( command_result["content"], check_command_result["content"] ) #####把执行命令和命令检查的结果叠加在一起 cheungssh_info["status"] = check_command_result[ "status"] #####把命令检查的状态设定为命令最终执行的状态 except Exception, e: cheungssh_info["content"] = str(e) cheungssh_info["status"] = False
def upload_script_and_execute_command(self, **parameters): cheungssh_info = {"status": False, "content": ""} #if not parameters["username"] == "root": # raise CheungSSHError("非管理员账号,不能采集目标服务器资产") try: ###########上传资产查询文件 ssh = CheungSSH_SSH() login = ssh.login(**parameters) if not login["status"]: raise CheungSSHError("登录错误: %s" % login["content"]) try: sid = parameters["id"] alias = parameters["alias"] #########逐个获取每一个资产项目,下面是有自定义资产添加的功能的代码 info = {} ##########用于存储一个机器的全部资产收集数据 #tmp_assets_conf=copy.deepcopy(assets_conf) ########复制一个,用来使用,必须深拷贝 #custom_assets_class_list=REDIS.get("custom.assets.class.list") #if not custom_assets_class_list is None: # custom_assets_class_list=msgpack.unpackb(custom_assets_class_list)#####如果没有自定义资产,那么下面的json代码就要报错 #else: # custom_assets_class_list={} #tmp_assets_conf=dict(tmp_assets_conf,**custom_assets_class_list) #for asset in tmp_assets_conf.keys(): _assets_conf = copy.deepcopy(self.assets_conf) for asset in _assets_conf.keys(): ######不能用中文 #####print tmp_assets_conf[asset]["command"] if _assets_conf[asset].has_key("asset_type"): if _assets_conf[asset]["asset_type"] == "static": #######静态资产,不执行命令 continue if asset == "time": _assets_conf[asset][ "value"] = self.time ########在原来的assets_conf上加了value字段 continue cmd = _assets_conf[asset]["command"][ssh.kws['os_type']] data = ssh.execute(cmd=cmd, sid=parameters["id"], tid=0, ignore=True) ######执行资产列表的命令 if data["status"] is True: #######判断是否执行成功 try: result = "\n".join( data["content"].split('\r\n')[1:-1]) #print data['content'].split('OKD'),8888888888888888888888888888888888888888888 except Exception, e: result = "获取数据失败 %s" % str(e) else: result = "获取数据失败 %s" % data["content"] _assets_conf[asset][ "value"] = result ########在原来的assets_conf上加了value字段 self.assets_data[sid] = { "sid": sid, "alias": alias, "data": _assets_conf } print "已经取得资产信息." except ValueError: raise CheungSSHError("获取资产数据失败!")
def deployment_script_init_and_execute(sid,sfile,username): cheungssh_info={"content":"","status":False} tid=str(random.randint(90000000000000000000,99999999999999999999)) try: sfile=os.path.join(cheungssh_settings.script_dir,username,os.path.basename(sfile)) dfile=os.path.join('/tmp/',tid) host=cheungssh_modul_controler.CheungSSHControler.convert_id_to_ip(sid) if not host["status"]:raise CheungSSHError(host['content']) _host_info=host['content'] sftp=CheungSSHFileTransfer() login=sftp.login(**_host_info) print 676767 if not login["status"]: print login["content"],"登录失败" raise CheungSSHError(login["content"]) cheungssh_info=sftp.upload(sfile,dfile,"") sftp.logout() if not cheungssh_info["status"]:raise CheungSSHError(cheungssh_info["content"]) cheungssh_info["dfile"]=dfile ssh=CheungSSH_SSH() login=ssh.login(**_host_info) if not login["status"]:raise CheungSSHError(login["content"]) cheungssh_info=ssh.execute(dfile,ignore=True) ssh.logout() except Exception,e: cheungssh_info["status"]=False cheungssh_info["content"]=str(e)
def get_docker(self,**parameter): cheungssh_info={"content":"","status":False} try: SSH=CheungSSH_SSH() SSH.login(**parameter) sid=parameter["id"] alias=parameter["alias"] ip=parameter["ip"] images=SSH.execute(cmd=self.get_docker_image_command,sid=sid,tid="0",ignore=True) container=SSH.execute(cmd=self.get_docker_container_command,sid=sid,tid="0",ignore=True) self.format_docker_image_list(images,alias,ip,sid) self.format_docker_container_list(container,alias,ip,sid) except Exception,e: print "redis错误",e,1111111111111111111111 cheungssh_info["status"]=False cheungssh_info["content"]=str(e)
def execute_app(appid, username, is_super): cheungssh_info = {"content": [], "status": False} app_conf = False try: data = CheungSSHAppAdmin.get_app_list(username, is_super) if not data["status"]: raise CheungSSHError("读取应用配置出错![%s]" % data["content"]) else: content = data["content"] app_conf = CheungSSHAppAdmin.check_appid_conf(content, appid) if not app_conf["status"]: raise CheungSSHError("该APP不存在! [%s]" % app_conf["content"]) sid = app_conf["content"]["sid"] server_conf = cheungssh_modul_controler.CheungSSHControler.convert_id_to_ip( sid) if not server_conf["status"]: raise CheungSSHError("应用数据处理失败!%s" % server_conf["content"]) CheungSSHAppAdmin.set_app_status("执行中", "", appid) ssh = CheungSSH_SSH() tmp = ssh.login(**server_conf["content"]) if not tmp["status"]: raise CheungSSHError(tmp["content"]) command = app_conf["content"]["app_command"] check_command = app_conf["content"]["app_check_command"] command_result = ssh.execute(command, ignore=True) if re.search("echo *\$\? *$|^ *$", check_command): print "执行系统定义的检查命令" cheungssh_info = command_result print cheungssh_info, 55555555555555555555 else: check_command_result = ssh.execute(check_command) cheungssh_info["content"] = "%s </br> %s" % ( command_result["content"], check_command_result["content"]) cheungssh_info["status"] = check_command_result["status"] except Exception, e: cheungssh_info["content"] = str(e) cheungssh_info["status"] = False
def delete_crontab_list(self,data): cheungssh_info={"content":"","status":False} try: configuration = ServersInventory().get_server(sid=data["sid"]) if not configuration["status"]:raise IOError(configuration["content"]) ssh=CheungSSH_SSH() status=ssh.login(**configuration["content"]) if not status["status"]: ######登录是失败的 raise CheungSSHError(status["content"]) else: info=ssh.execute("whoami") if info["status"]: path=os.path.join("/var/spool/cron/",configuration["content"]["username"]) info=ssh.execute("sed -i '{line_id}s/.*/#/' {path}".format(line_id=data["line_id"],path=path))#####删除远程服务器上的 if not info["status"]: raise CheungSSHError(info["content"]) cheungssh_info["status"]=True except Exception,e: cheungssh_info["status"]=False cheungssh_info["content"]=str(e)
def upload_script_and_execute_command(self,**parameters): cheungssh_info={"status":False,"content":""} #if not parameters["username"] == "root": # raise CheungSSHError("非管理员账号,不能采集目标服务器资产") try: ssh=CheungSSH_SSH() login=ssh.login(**parameters) if not login["status"]: raise CheungSSHError("登录错误: %s" %login["content"]) try: sid = parameters["id"] alias =parameters["alias"] info={} #tmp_assets_conf=copy.deepcopy(assets_conf) #custom_assets_class_list=REDIS.get("custom.assets.class.list") #if not custom_assets_class_list is None: # custom_assets_class_list=msgpack.unpackb(custom_assets_class_list) #else: # custom_assets_class_list={} #tmp_assets_conf=dict(tmp_assets_conf,**custom_assets_class_list) #for asset in tmp_assets_conf.keys(): _assets_conf=copy.deepcopy(self.assets_conf) for asset in _assets_conf.keys(): if _assets_conf[asset].has_key("asset_type"): if _assets_conf[asset]["asset_type"]=="static": continue if asset=="time": _assets_conf[asset]["value"]=self.time continue cmd=_assets_conf[asset]["command"][ssh.kws['os_type']] data=ssh.execute(cmd=cmd,sid=parameters["id"],tid=0,ignore=True) if data["status"] is True: try: result="\n".join(data["content"].split('\r\n')[1:-1]) #print data['content'].split('OKD'),8888888888888888888888888888888888888888888 except Exception,e: result="获取数据失败 %s" % str(e) else: result="获取数据失败 %s" % data["content"] _assets_conf[asset]["value"]=result self.assets_data[sid]={"sid":sid,"alias":alias,"data":_assets_conf} print "已经取得资产信息." except ValueError: raise CheungSSHError("获取资产数据失败!")
def get_crontab_list(self,sid):######data应该是存放的ip的相关登录信息 cheungssh_info={"content":[],"status":False} cmd="/usr/bin/crontab -l" crontab_data=[] try: configuration = ServersInventory().get_server(sid=sid) if not configuration["status"]:raise IOError(configuration["content"]) ssh=CheungSSH_SSH() status=ssh.login(**configuration["content"]) if not status["status"]: ######登录是失败的 raise CheungSSHError(status["content"]) else: ########登录成功的 data=ssh.execute(cmd,ignore=True) if re.search("-bash: /usr/bin/crontab: No such file",data["content"]): pass else: ######命令执行结果成功了 #print "结果:",data["content"] crontab_list=data["content"] #crontab_list="\n".join(crontab_list.split('\n')[1:][:-1]) crontab_list="\n".join(crontab_list.split('\n')[1:][:-1]) #print crontab_list,555555555555555555555555555555555555555 #print crontab_list.split('abcded'),555555555555555555555555555555555555555 line_id = 0 for line in crontab_list.split('\n'): line_id += 1 if re.search('^ *#',line): continue elif re.search('^ *$',line): continue try: crontab_time=" ".join(line.split()[:5]) if re.search("#",line): crontab_cmd=" ".join(line.split()[5:][:-1]) else: crontab_cmd=" ".join(line.split()[5:]) if len(crontab_cmd)==0: if not len(line.split())==6:######考虑只有一个命令的情况,没有注释的情况或者参数的情况 continue else: crontab_cmd=" ".join(line.split()[5:]) if re.search("#",line): crontab_dest=line.split("#")[-1] else: crontab_dest="" crontab_data.append( {"cmd":crontab_cmd, "time":crontab_time, "description":crontab_dest, "sid":sid, "username":configuration["content"]["username"], "alias":configuration["content"]["alias"], "line":line_id, } ) except Exception,e: print "报错了",str(e) pass cheungssh_info["content"]=crontab_data cheungssh_info["status"]=True