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 execute_docker(self,cmd="",sid="",containers=[]): cheungssh_info={"content":"","status":False} try: server_config=CheungSSHControler.convert_id_to_ip(sid=sid) if not server_config["status"]: for cid in containers: log={"status":False,"content":server_config["content"],"cid":cid} log=json.dumps(log,encoding="utf8",ensure_ascii=False) self.REDIS.incr("log.%s.current" % tid) self.REDIS.rpush("log.docker.container.%s" %self.parameters["tid"],log) print "解析配置失败",server_config["content"] raise CheungSSHError(server_config["content"]) ssh=CheungSSH_SSH() data=ssh.login(**server_config["content"]) if not data["status"]: print "登录失败" #####一次性失败一个服务器的全部docker for cid in containers: log={"status":False,"content":data["content"],"cid":cid} log=json.dumps(log,encoding="utf8",ensure_ascii=False) self.REDIS.incr("log.%s.current" % tid) self.REDIS.rpush("log.docker.container.%s" %self.parameters["tid"],log) raise CheungSSHError(data["content"]) #####这里不用多线程了,困难很多,设计到shell的复制 for c in containers: #####循环每一个容器,一个容器就是一个命令 print "执行命里干活" _cmd=cmd % (self.task_type,c) self.message_process(**{"cmd":_cmd,"sid":sid,"tid":self.parameters["tid"],"shell":ssh,"cid":c}) #####每一个服务器执行完成了所有的任务后注销shell ssh.logout() cheungssh_info["status"]=True except Exception,e: print "报错",str(e) cheungssh_info["status"]=False cheungssh_info["content"]=str(e)
def connect_ssh(self, sid=None, tid=None, instance=None): current_amount = "{tid}.current.logined.server.amount".format(tid=tid) ##### 用来存储登陆的结果 login_data_key = "{tid}.data.logined.server".format(tid=tid) cheungssh_info = {"status": True, "content": []} key = "{tid}.{sid}".format(sid=sid, tid=tid) server_config = ServersInventory().get_server(sid=sid)["content"] ssh = CheungSSH_SSH() channel = ssh.login(**server_config) channel["sid"] = ssh.sid if channel["status"] == True: instance.ServersSSHLoginPool[key] = { "ssh": ssh, "beginning_time": time.time() } print "登录成功,已缓存登录通道" else: print "登录失败,不缓存登录通道" Lock.acquire() self.login_list[key] = channel ##### 记录完成的服务器数量,用户显示登陆进度 REDIS.set( login_data_key, json.dumps(self.login_list, encoding="utf8", ensure_ascii=False)) REDIS.incr(current_amount) Lock.release()
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 ssh_check(self, **kws): ssh = CheungSSH_SSH() data = ssh.login(**kws) data["time"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) if data["status"]: data["status"] = "success" else: data["status"] = "failed" self.save(kws["id"], data)
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) #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("获取资产数据失败!")
class CheungSSHControler(object): def __init__(self): #####可以一次性初始化 #######需要传递redis连接 self.REDIS = REDIS self.SSH = CheungSSH_SSH() #####继承sshv2 #####调用command_contorler执行命令 #####connect开启连接 def controler_center(self, parameter={}): cmd = parameter.get("cmd", False) tid = parameter["tid"] pass def connect(self, sid=""): #####tid 是生成的id cheungssh_info = {"content": "", "status": False} try: server_config = ServersInventory().get_server(sid=sid) cheungssh_info = self.SSH.login( **server_config["content"]) ######返回整个实例 #####如果成功连接服务器,则存储连接 except Exception, e: print "connect错误", str(e) cheungssh_info["content"] = str(e) cheungssh_info["status"] = False return cheungssh_info
class CheungSSHControler(object): def __init__(self): self.REDIS = REDIS self.SSH = CheungSSH_SSH() def controler_center(self, parameter={}): cmd = parameter.get("cmd", False) tid = parameter["tid"] pass def connect(self, sid=""): cheungssh_info = {"content": "", "status": False} try: server_config = self.convert_id_to_ip(sid) if not server_config["status"]: raise CheungSSHError(server_config["content"]) #ip=server_config["content"]["ip"] #alias=server_config["content"]["alias"] if server_config["status"]: cheungssh_info = self.SSH.login(**server_config["content"]) else: cheungssh_info["content"] = server_config["content"] except Exception, e: print "connect错误", str(e) cheungssh_info["content"] = str(e) cheungssh_info["status"] = False return cheungssh_info
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 login(sid="", rid=""): cheungssh_info = {"content": "", "status": False} try: config = CheungSSHControler.convert_id_to_ip(sid) if not config["status"]: raise CheungSSHError(config["content"]) _config = config["content"] ssh = CheungSSH_SSH() connect = ssh.login(**_config) if connect["status"]: CheungSSHBatchCommand.shell_list.append(ssh) cheungssh_info = {"content": "已就绪", "status": True} else: cheungssh_info = { "content": connect["content"], "status": False } except Exception, e: cheungssh_info = {"content": str(e), "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 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 login(sid="", rid=""): #####返回的数据格式{sid:{"content":"...","status":True/False}} cheungssh_info = {"content": "", "status": False} try: config = CheungSSHControler.convert_id_to_ip(sid) if not config["status"]: raise CheungSSHError(config["content"]) _config = config["content"] ssh = CheungSSH_SSH() connect = ssh.login(**_config) if connect["status"]: CheungSSHBatchCommand.shell_list.append( ssh) #####没有的就不存,等要用的时候,找不到直接忽略不执行execute即可 cheungssh_info = {"content": "已就绪", "status": True} else: cheungssh_info = { "content": connect["content"], "status": False } except Exception, e: cheungssh_info = {"content": str(e), "status": False}
def run(self): while True: if self.queue.empty(): break kws = self.queue.get() self.sid = kws["id"] ssh = CheungSSH_SSH() info = ssh.login(**kws) if info["status"] is False: info = json.dumps(info, encoding="utf8", ensure_ascii=False) self.REDIS.hset(self.tid, "progress.{sid}".format(sid=self.sid), info) continue try: ssh.sftp_upload(self.tid, self.sid, self.source, self.destination) except Exception, e: info = {"content": str(e), "status": False} info = json.dumps(info, encoding="utf8", ensure_ascii=False) self.REDIS.hset(self.tid, "progress.{sid}".format(sid=self.sid), info) self.queue.task_done()
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 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 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 __init__(self): CheungSSH_SSH.__init__(self) self.base_prompt = r'[^\[#]([^#+])(>|#|\]|\$|\)|(\[y/N\]:|\?|(assword:?)|(?))) *$'
def __init__(self): #####可以一次性初始化 #######需要传递redis连接 self.REDIS = REDIS self.SSH = CheungSSH_SSH() #####继承sshv2
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
def login(self, **kws): ssh = CheungSSH_SSH() t = ssh.login(**kws) if not t["status"]: raise CheungSSHError(t["content"]) return ssh
#!/usr/bin/env python from cheungssh_sshv2 import CheungSSH_SSH a = CheungSSH_SSH()
def __init__(self, taskid="", stepid=""): self.taskid = taskid self.stepid = stepid CheungSSH_SSH.__init__(self)
def __init__(self): CheungSSH_SSH.__init__(self)
def __init__(self): self.REDIS = REDIS self.SSH = CheungSSH_SSH()