"group": group, "servers": [{ "ip": username + "@" + ip, "status": "ERR", "jindu": jindu, "cmd": cmd, "info": Show_Result_web_status }] }] } info['id'] = (str(random.randint(999999999, 99999999999999999))) info = json.dumps(info, encoding='utf8', ensure_ascii=False) #sendinfo.sendinfo(str({ie_key:info})) if Data.excutetype == 'cmd': sendinfo.sendinfo(str({ie_key: info})) else: checktime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) hwinfo = cache.get('hwinfo') if not hwinfo: hwinfo = {} ipinfo = {Data.hwtype: ResultSum, 'ip': ip, 'checktime': checktime} hwinfo[ip] = ipinfo else: #hwinfo[ip][Data.hwtype]=ResultSum if hwinfo.has_key(ip): hwinfo[ip][Data.hwtype] = ResultSum else: ipinfo = { Data.hwtype: ResultSum, 'ip': ip,
print '链接服务器错误' color_status=1 Data.All_Servers_num += 1 Result_status=False Data.FailIP.append(ip) ResultSum=str(e) bufflog=str(e) TmpShow=Format_Char_Show_web.Show_Char(ResultSum,1) jindu=int(float(Data.All_Servers_num)/float(Data.All_Servers_num_all)*100) Show_Result_web_status=Format_Char_Show_web.Show_Char(str(e).replace("<","<")+"\n"+username+"@"+ip,color_status) info={"msgtype":1,"content":[{"group":group,"servers":[{"ip":username+"@"+ip,"status":"ERR","jindu":jindu,"cmd":cmd,"info":Show_Result_web_status}]}]} info['id']=(str(random.randint(999999999,99999999999999999))) info=json.dumps(info,encoding='utf8',ensure_ascii=False) #sendinfo.sendinfo(str({ie_key:info})) if Data.excutetype=='cmd': sendinfo.sendinfo(str({ie_key:info})) print '这是发送给socket' else: print '这是sudo' checktime=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) hwinfo=cache.get('hwinfo') if not hwinfo: hwinfo={} ipinfo={Data.hwtype:ResultSum,'ip':ip,'checktime':checktime} hwinfo[ip]=ipinfo else: #hwinfo[ip][Data.hwtype]=ResultSum if hwinfo.has_key(ip): hwinfo[ip][Data.hwtype]=ResultSum else: ipinfo={Data.hwtype:ResultSum,'ip':ip,'checktime':checktime}
def SSH_cmd(ip,username,password,port,cmd,UseLocalScript,OPTime,ie_key): PROFILE=". /etc/profile 2&>/dev/null;. ~/.bash_profile 2&>/dev/null;. /etc/bashrc 2&>/dev/null;. ~/.bashrc 2&>/dev/null;" PATH="export PATH=$PATH:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin;" global All_Servers_num,All_Servers_num_all,All_Servers_num_Succ,Done_Status,Global_start_time,PWD,FailIP,Servers start_time=time.time() ResultSum='' ResultSumLog='' DeploymentStatus=False DeploymentInfo=None color_status=0 InGroup="" for a in HostsGroup: if ip in HostsGroup[a]: InGroup=a break try: o=None err=None ssh=paramiko.SSHClient() if UseKey=='Y': KeyPath=os.path.expanduser('~/.ssh/id_rsa') key=paramiko.RSAKey.from_private_key_file(KeyPath) ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username,pkey=key) else: ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username,password) stdin,stdout,stderr=ssh.exec_command(PROFILE+PATH+cmd) out=stdout.readlines() All_Servers_num += 1 print "\r" for o in out: ResultSum +=o ResultSumLog +=o.strip('\n') + '\\n' error_out=stderr.readlines() for err in error_out: ResultSum +=err ResultSumLog +=err.strip('\n') + '\\n' if err: FailIP.append(ip) color_status=1 ResultSum_count="服务器: %s@%s 错误消息: %s" %(username,ip,"命令失败") out='Null\n' else: error_out='NULL' #ResultSum_count="\033[1m\033[1;32m+OK [%s|%s] (%0.2f Sec, %d/%d Cmd:Sucess)\033[1m\033[0m" % (ip,username,float(time.time()-start_time),All_Servers_num,All_Servers_num_all) ResultSum_count="服务器: %s@%s " %(username,ip) All_Servers_num_Succ+=1 Show_Result_web_status=Format_Char_Show_web.Show_Char(ResultSum.replace("<","<")+username+"@"+ip,color_status) Show_Result=ResultSum + '\n' +ResultSum_count #jindu=("%0.2f" %(All_Servers_num/All_Servers_num_all))*100 jindu=int(float(All_Servers_num)/float(All_Servers_num_all)*100) TmpShow=Format_Char_Show_web.Show_Char(Show_Result+" 时间:"+OPTime+" 命令: "+cmd,color_status) #write_msg(TmpShow) #sendinfo.sendinfo(str({ie_key:TmpShow})) if color_status==1: info={"msgtype":1,"content":[{"group":InGroup,"servers":[{"ip":username+"@"+ip,"status":"ERR","jindu":jindu,"cmd":cmd,"info":Show_Result_web_status}]}]} else: info={"msgtype":1,"content":[{"group":InGroup,"servers":[{"ip":username+"@"+ip,"status":"OK","jindu":jindu,"cmd":cmd,"info":Show_Result_web_status}]}]} b_id=str(random.randint(999999999,99999999999999999)) info["id"]=b_id info=json.dumps(info,encoding='utf8',ensure_ascii=False) sendinfo.sendinfo(str({ie_key:info})) #serverinfo={InGroup:[ip:{"status":"OK","info":Show_Result}]} #serverinfo=[1,{InGroup:[{ip:{"ip":username+"@"+ip,"status":"OK","info":Show_Result}}]}] #serverinfo={ip:{"status":"UNSTART","groupid":InGroup,"ip":server_info[0][ip]+"@"+ip,"info":"暂无消息"}} #serverinfo=str(serverinfo).decode('latin-1').encode("utf-8") #serverinfo=json.dumps(serverinfo,encoding='utf8',ensure_ascii=False) #write_server_status("IP_Status===%s===%s===ok===消息:%s===/pic/green.png"%(InGroup,ip,Show_Result)) #write_server_status(str(serverinfo)) except Exception,e: color_status=1 FailIP.append(ip) All_Servers_num += 1 #ResultSum_count="\n\033[1m\033[1;31m-ERR [%s|%s] %s (%0.2f Sec %d/%d)\033[1m\033[0m\a" % (ip,username,e,float(time.time() - start_time),All_Servers_num,All_Servers_num_all) ResultSum_count="服务器: %s@%s 错误消息: %s" %(username,ip,e) Show_Result_web_status=ResultSum Show_Result= ResultSum+ResultSum_count TmpShow=Format_Char_Show_web.Show_Char(Show_Result+" 时间:"+OPTime+" 命令: "+cmd,color_status) #write_msg(TmpShow) jindu=int(float(All_Servers_num)/float(All_Servers_num_all)*100) #sendinfo.sendinfo(str({ie_key:TmpShow})) Show_Result_web_status=Format_Char_Show_web.Show_Char(str(e).replace("<","<")+"\n"+username+"@"+ip,color_status) info={"msgtype":1,"content":[{"group":InGroup,"servers":[{"ip":username+"@"+ip,"status":"ERR","jindu":jindu,"cmd":cmd,"info":Show_Result_web_status}]}]} info['id']=(str(random.randint(999999999,99999999999999999))) info=json.dumps(info,encoding='utf8',ensure_ascii=False) sendinfo.sendinfo(str({ie_key:info}))
#serverinfo=json.dumps(serverinfo,encoding='utf8',ensure_ascii=False) #write_server_status(str(serverinfo)) else: ssh.close() if All_Servers_num == All_Servers_num_all: #这里防止计数器永远相加下去 FailNum=All_Servers_num_all-All_Servers_num_Succ if FailNum>0: FailNumShow="\033[1m\033[1;31mFail:%d\033[1m\033[0m" % (FailNum) else: FailNumShow="Fail:%d" % (FailNum) #print "+Done (Succ:%d,%s, %0.2fSec CheungSSH(V:%d) Cheung Kei-Chuen All Right Reserved)" % (All_Servers_num_Succ,FailNumShow,time.time()-Global_start_time,VERSION) All_Servers_num =0 All_Servers_num_Succ=0 Done_Status='end' #os.system("""echo 'Done' >/tmp/status""") sendinfo.sendinfo(str({ie_key:'Done'})) def Read_config(file="%s/cheung/conf/cheung.conf"%HOME): global Servers,Useroot,Timeout,RunMode,UseKey,Deployment,ListenTime,ListenFile,ListenChar,ServersPort,ServersPassword,ServersUsername,ServersRootPassword,NoPassword,NoRootPassword,HostsGroup,HOSTSMD5,CONFMD5,sudo ServersPort={};ServersPassword={};ServersUsername={};ServersRootPassword={};Servers=[];HostsGroup={} try: HOSTSMD5=filemd5.main(HostsFile) CONFMD5=filemd5.main(ConfFile) except Exception,e: print "读取配置文件错误(%s)" % e sys.exit(1) c=ConfigParser.ConfigParser() try: c.read(file) except ConfigParser.ParsingError,e: print "文件%s格式错误.\a\n\t" % (file)
def SSH_cmd(ip, username, password, port, cmd, UseLocalScript, OPTime, ie_key): PROFILE = ". /etc/profile 2&>/dev/null;. ~/.bash_profile 2&>/dev/null;. /etc/bashrc 2&>/dev/null;. ~/.bashrc 2&>/dev/null;" PATH = "export PATH=$PATH:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin;" global All_Servers_num, All_Servers_num_all, All_Servers_num_Succ, Done_Status, Global_start_time, PWD, FailIP, Servers start_time = time.time() ResultSum = '' ResultSumLog = '' DeploymentStatus = False DeploymentInfo = None color_status = 0 InGroup = "" for a in HostsGroup: if ip in HostsGroup[a]: InGroup = a break try: o = None err = None ssh = paramiko.SSHClient() if UseKey == 'Y': KeyPath = os.path.expanduser('~/.ssh/id_rsa') key = paramiko.RSAKey.from_private_key_file(KeyPath) ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, port, username, pkey=key) else: ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, port, username, password) stdin, stdout, stderr = ssh.exec_command(PROFILE + PATH + cmd) out = stdout.readlines() All_Servers_num += 1 print "\r" for o in out: ResultSum += o ResultSumLog += o.strip('\n') + '\\n' error_out = stderr.readlines() for err in error_out: ResultSum += err ResultSumLog += err.strip('\n') + '\\n' if err: FailIP.append(ip) color_status = 1 ResultSum_count = "服务器: %s@%s 错误消息: %s" % (username, ip, "命令失败") out = 'Null\n' else: error_out = 'NULL' #ResultSum_count="\033[1m\033[1;32m+OK [%s|%s] (%0.2f Sec, %d/%d Cmd:Sucess)\033[1m\033[0m" % (ip,username,float(time.time()-start_time),All_Servers_num,All_Servers_num_all) ResultSum_count = "服务器: %s@%s " % (username, ip) All_Servers_num_Succ += 1 Show_Result_web_status = Format_Char_Show_web.Show_Char( ResultSum.replace("<", "<") + username + "@" + ip, color_status) Show_Result = ResultSum + '\n' + ResultSum_count #jindu=("%0.2f" %(All_Servers_num/All_Servers_num_all))*100 jindu = int(float(All_Servers_num) / float(All_Servers_num_all) * 100) TmpShow = Format_Char_Show_web.Show_Char( Show_Result + " 时间:" + OPTime + " 命令: " + cmd, color_status) #write_msg(TmpShow) #sendinfo.sendinfo(str({ie_key:TmpShow})) if color_status == 1: info = { "msgtype": 1, "content": [{ "group": InGroup, "servers": [{ "ip": username + "@" + ip, "status": "ERR", "jindu": jindu, "cmd": cmd, "info": Show_Result_web_status }] }] } else: info = { "msgtype": 1, "content": [{ "group": InGroup, "servers": [{ "ip": username + "@" + ip, "status": "OK", "jindu": jindu, "cmd": cmd, "info": Show_Result_web_status }] }] } b_id = str(random.randint(999999999, 99999999999999999)) info["id"] = b_id info = json.dumps(info, encoding='utf8', ensure_ascii=False) sendinfo.sendinfo(str({ie_key: info})) #serverinfo={InGroup:[ip:{"status":"OK","info":Show_Result}]} #serverinfo=[1,{InGroup:[{ip:{"ip":username+"@"+ip,"status":"OK","info":Show_Result}}]}] #serverinfo={ip:{"status":"UNSTART","groupid":InGroup,"ip":server_info[0][ip]+"@"+ip,"info":"暂无消息"}} #serverinfo=str(serverinfo).decode('latin-1').encode("utf-8") #serverinfo=json.dumps(serverinfo,encoding='utf8',ensure_ascii=False) #write_server_status("IP_Status===%s===%s===ok===消息:%s===/pic/green.png"%(InGroup,ip,Show_Result)) #write_server_status(str(serverinfo)) except Exception, e: color_status = 1 FailIP.append(ip) All_Servers_num += 1 #ResultSum_count="\n\033[1m\033[1;31m-ERR [%s|%s] %s (%0.2f Sec %d/%d)\033[1m\033[0m\a" % (ip,username,e,float(time.time() - start_time),All_Servers_num,All_Servers_num_all) ResultSum_count = "服务器: %s@%s 错误消息: %s" % (username, ip, e) Show_Result_web_status = ResultSum Show_Result = ResultSum + ResultSum_count TmpShow = Format_Char_Show_web.Show_Char( Show_Result + " 时间:" + OPTime + " 命令: " + cmd, color_status) #write_msg(TmpShow) jindu = int(float(All_Servers_num) / float(All_Servers_num_all) * 100) #sendinfo.sendinfo(str({ie_key:TmpShow})) Show_Result_web_status = Format_Char_Show_web.Show_Char( str(e).replace("<", "<") + "\n" + username + "@" + ip, color_status) info = { "msgtype": 1, "content": [{ "group": InGroup, "servers": [{ "ip": username + "@" + ip, "status": "ERR", "jindu": jindu, "cmd": cmd, "info": Show_Result_web_status }] }] } info['id'] = (str(random.randint(999999999, 99999999999999999))) info = json.dumps(info, encoding='utf8', ensure_ascii=False) sendinfo.sendinfo(str({ie_key: info}))
#serverinfo=json.dumps(serverinfo,encoding='utf8',ensure_ascii=False) #write_server_status(str(serverinfo)) else: ssh.close() if All_Servers_num == All_Servers_num_all: #这里防止计数器永远相加下去 FailNum = All_Servers_num_all - All_Servers_num_Succ if FailNum > 0: FailNumShow = "\033[1m\033[1;31mFail:%d\033[1m\033[0m" % (FailNum) else: FailNumShow = "Fail:%d" % (FailNum) #print "+Done (Succ:%d,%s, %0.2fSec CheungSSH(V:%d) Cheung Kei-Chuen All Right Reserved)" % (All_Servers_num_Succ,FailNumShow,time.time()-Global_start_time,VERSION) All_Servers_num = 0 All_Servers_num_Succ = 0 Done_Status = 'end' #os.system("""echo 'Done' >/tmp/status""") sendinfo.sendinfo(str({ie_key: 'Done'})) def Read_config(file="%s/cheung/conf/cheung.conf" % HOME): global Servers, Useroot, Timeout, RunMode, UseKey, Deployment, ListenTime, ListenFile, ListenChar, ServersPort, ServersPassword, ServersUsername, ServersRootPassword, NoPassword, NoRootPassword, HostsGroup, HOSTSMD5, CONFMD5, sudo ServersPort = {} ServersPassword = {} ServersUsername = {} ServersRootPassword = {} Servers = [] HostsGroup = {} try: HOSTSMD5 = filemd5.main(HostsFile) CONFMD5 = filemd5.main(ConfFile) except Exception, e: print "读取配置文件错误(%s)" % e