Beispiel #1
0
    def stop(self):
        """
		Stop the daemon
		"""
        # Get the pid from the pidfile
        try:
            pf = file(self.pidfile, 'r')
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None

        if not pid:
            message = "pidfile %s does not exist. osa Daemon not running?\n"
            sys.stderr.write(message % self.pidfile)
            return  # not an error in a restart
        # Try killing the daemon process
        try:
            while 1:
                os.kill(pid, SIGTERM)
                time.sleep(0.1)
        except OSError, err:
            err = str(err)
            if err.find("No such process") > 0:
                if os.path.exists(self.pidfile):
                    os.remove(self.pidfile)
            else:
                save_log('ERROR', 'Stop error,' + str(err))
                sys.exit(1)
Beispiel #2
0
def _get_con():
	'''
	获取数据库连接
	'''
	
	host = MYSQL['HOST']
	user = MYSQL['USER']
	passwd = MYSQL['PASSWD']
	db = MYSQL['DB']
	port = int(MYSQL['PORT'])
	
	i=0
	while True:
		if i > 10:
			save_log('ERROR', 'pooldb connection error !')
			sys.exit()
		time.sleep(round(float(random.randrange(0, 100, 1))/100,2))
		try:
			pooldb = PooledDB.PooledDB(MySQLdb, maxusage=MYSQL['SIZE'], 
					host=host, user=user, passwd=passwd, db=db ,port= port,charset='utf8')	
			return pooldb.connection()
			
		except Exception as e:
			i=i+1
			continue
Beispiel #3
0
def collectDo():

    #定义采集指令

    cmd = ''
    starttime = time.time()
    #获取监控时间
    monitime = _get_monitime()
    save_log('DEBUG', monitime + ' collect!')
    #获取IP地址列表
    iplist = cmdtosql.getIpList()
    save_log('INFO', 'total server num is:' + str(len(iplist)))
    #准备队列
    q = Queue()
    #IP地址入队
    for ip in iplist:
        q.put(ip)

    #采集所有数据
    try:
        res = allDatatoDb(cmd, q, monitime)
    except Exception as collerror:
        save_log('ERROR', 'collected error :' + str(collerror))
    ltime = time.mktime(time.strptime(_get_monitime(), "%Y-%m-%d %H:%M:%S"))
    mtime = ltime - time.time()
    ptime = time.time() - starttime
    save_log('DEBUG', 'collected time used :' + str(ptime))
    save_log('INFO', '---------------------------------------------')
    #等待所有子进程执行完毕
    time.sleep(100)
    sys.exit()
Beispiel #4
0
def collectDo():

	#定义采集指令

	cmd = ''
	starttime = time.time()
	#获取监控时间
	monitime = _get_monitime()
	save_log('DEBUG',monitime + ' collect!')	
	#获取IP地址列表 
	iplist = cmdtosql.getIpList()
	save_log('INFO','total server num is:'+str(len(iplist)))
	#准备队列
	q = Queue()
	#IP地址入队
	for ip in iplist:
        	q.put(ip)
	
	#采集所有数据
	try:		
		res=allDatatoDb(cmd,q,monitime)
	except Exception as collerror:
		save_log('ERROR','collected error :'+str(collerror))
	ltime = time.mktime(time.strptime(_get_monitime(), "%Y-%m-%d %H:%M:%S"))
	mtime = ltime - time.time()
	ptime = time.time() - starttime
	save_log('DEBUG','collected time used :'+str(ptime))
	save_log('INFO','---------------------------------------------')
	#等待所有子进程执行完毕
	time.sleep(100)
	sys.exit()
Beispiel #5
0
def update(sqlstr):
	'''
	更新数据库,update操作
	@sqlstr SQL语句
	return 更新的行数
	'''

	if sqlstr[0:6].upper() == 'UPDATE':
		sql = sqlstr
	else:
		return 0
	try:
		con = _get_pcon()
		cur = con.cursor()
		cur.execute(sql)
	except Exception as uerror:
		save_log('ERROR','update sql error 1:'+str(uerror)+',sql is :'+sqlstr)
		time.sleep(random.randint(0,10))
		
		try:
			con = _get_con()
			cur = con.cursor()
			cur.execute(sql)	
		except Exception as uerror:
			save_log('ERROR','update sql error 2:'+str(uerror)+',sql is :'+sqlstr)
			
	_exit(con, cur)
		
	return int(cur.rowcount)
Beispiel #6
0
def getIdByCmd(cmdTitle):
	'''
	根据指令名获取指令Id
	@cmdTitle: 指令名称
	'''
	
	con = _get_pcon()
	cur = con.cursor()
	
	try:
		cur.execute("select id from osa_command where oCmdTitle='%s'" % cmdTitle)
	except Exception as e:
		time.sleep(0.01)
		cur.execute("select id from osa_command where oCmdTitle='%s'" % cmdTitle)
		save_log('ERROR',e)
		return 'null'
	
	res=cur.fetchone()	
	
	if not res:
		id = 'null'
	else:
		id = res[0]
	
	_exit(con, cur)
	
	return id
Beispiel #7
0
def GetConfigFile(ip,cname):
	'''
	@ip unctrlpy端的ip地址
	@cname 配置文件名
	return 给PHP的文件名和文件大小 or False
	'''

	port = get_fsocket_port()
	toUnctrlpyCmd = 'SYSTEM_RUN_COMMAND!{"getconfigfile":"'+cname+'|'+str(port)+'"}'
	fromUnctrlpyData = hostSocket.FproSocket(ip, SOCKET['REMOTE_PORT'], toUnctrlpyCmd)
	
	if not os.path.exists(DIRS['CTEMP']):
		os.system('mkdir -p '+ DIRS['CTEMP'])
		os.system('chmod 777 '+ DIRS['CTEMP'])
	
	lstr = (DIRS['CTEMP'])[-1:]
	fname = DIRS['CTEMP'] + str(cname)  +  '.tmp.' + time.strftime("%Y-%d-%m_%H%M%S", time.localtime())
	
	if lstr != '/':
		fname = DIRS['CTEMP'] + str(cname)  +  '.tmp.' + time.strftime("%Y-%d-%m_%H%M%S", time.localtime())
        
	fileseze = None
	
	try:
		fileseze = file_recv_main(host='0.0.0.0',port=int(port),filename = fname)
	except Exception as e:
		save_log('ERROR',e)
	
	if fileseze:
		r = "RETURN_SYSTEM_RUN_COMMAND!['"+fname+'|'+str(fileseze)+"']"
		os.system('chmod 777 '+fname)
		return r
	
	return "File get faid!"
Beispiel #8
0
def SaveConfigFile(ip,cname,filename):
	'''
	@ip 远程IP地址
	@cname 配置文件名称
	'''
	
	rport = GetRemotoPort(ip = ip,portlist = FSOCKET['portlist'])

	toUnctrlpyCmd = 'SYSTEM_RUN_COMMAND!{"saveconfigfile":"'+cname+'|'+str(rport)+'"}'
	fromUnctrlpyData = hostSocket.FproSocket(ip, SOCKET['REMOTE_PORT'], toUnctrlpyCmd)
	fname = filename
	result = None
	
	if hostSocket.PortIsAlive(ip,rport):
		
		try:
			result = osaSendFile(filename=fname,remoteip=ip,port=int(rport))
		except Exception as e:
			save_log('ERROR',e)
	else:
		time.sleep(0.1)
		result = osaSendFile(filename=fname,remoteip=ip,port=int(rport))
	
	if result == 1:
		r = "RETURN_SYSTEM_RUN_COMMAND!['"+cname+' save ok'+"']"
		return r
	else:
		time.sleep(0.1)
		result = osaSendFile(filename=fname,remoteip=ip,port=int(rport))
		if result == 1:
			r = "RETURN_SYSTEM_RUN_COMMAND!['"+cname+' save ok'+"']"
			return r
		return None
Beispiel #9
0
def  IsWebAlive(oItemConfig):
	'''
	检测网页是否存活,返回元组:包括状态和网页内容(如果需要)
	'''
	url = oItemConfig['url']
	try:
		socket.setdefaulttimeout(MONITOR['timeout'])
		result = urllib2.urlopen(url)		
	except:
		try:
			time.sleep(1)
			socket.setdefaulttimeout(MONITOR['timeout'])
			result = urllib2.urlopen(url)
		except Exception as e:		
			save_log('ERROR','request url fialed! url:'+url)
			return str(0),str(e)
	content = result.read()
	code = str(result.code)
	httpcode = oItemConfig['httpcode'].split(',')
	if code in httpcode:
		c1 = 1 #网页存活有两个条件,第一个条件是状态码存在
	else:
		c1 = 0	
	c2 = 1 #假设第二个条件为真:关键字都匹配
	for i in range(len(oItemConfig['keywords'].split(','))):
		if not oItemConfig['keywords'].split(',')[i] in content:
			c2 = 0	#满足某个关键字不匹配,则条件二为假
	if c1 and c2:
		return str(1),content
	else:
		return str(0),content
Beispiel #10
0
def IsDataBaseNormal(oItemConfig,serverip):
	'''
	检测数据库的状态,并判断thread_connected和threads_running是否超过用户设定
	'''
	try:
		con=MySQLdb.connect(host=serverip,port=int(oItemConfig['port']),user=oItemConfig['user'],passwd=oItemConfig['password'])
	except Exception as error:
		save_log("ERROR","connect mysql "+serverip+":"+oItemConfig['user']+"fail! ERROR:"+str(error))
		return ('0',"不能连接到数据库"+str(serverip)+":"+str(oItemConfig['port']))
	
	res =""
	stat="1"
	cursor=con.cursor()
	n=cursor.execute('show status;')
	show_status = cursor.fetchall()
	
	for status in show_status:
		if status[0] == 'Threads_connected':
			if int(status[1]) > int(oItemConfig['pvalue']):
				stat="0"
				res = "Thread_connected"+":"+str(status[1])
		if status[0] == 'Threads_running':
			if int(status[1]) > int(oItemConfig['tvalue']):
				stat="0"
				res = "Threads_running"+":"+str(status[1])
	return (stat,res)
Beispiel #11
0
def batchSendCmd(rev,ip,type):
	'''
	@组装发送指令
	'''
	
	#重新组装发送指令
	
	cmddict = revToDict(rev)
	
	cmddict['type'] = type
	
	cmddict['clientip'] = ip
	
	
	#判断远程受控端是否可以连接
	try:
		isalive = hostSocket.PortIsAlive(ip,port=SOCKET['REMOTE_PORT'])
	except Exception as e:
		save_log('ERROR',ip+' port is not alive!'+str(e))
			
	if isalive == False:
		result = "{'batchinfo':"+str(cmddict)+",'command':'batchresult','batchresult':{'status':'ERROR','result':'can not connected client ip!'}}"
		
		osaResult.batchresult(result)
		sys.exit()
	
	#通知远程服务器
	fromUnctrlpyData = hostSocket.FproSocket(ip, SOCKET['REMOTE_PORT'], str(cmddict))
	
	return fromUnctrlpyData
Beispiel #12
0
def _get_con():
    '''
	获取数据库连接
	'''

    host = MYSQL['HOST']
    user = MYSQL['USER']
    passwd = MYSQL['PASSWD']
    db = MYSQL['DB']
    port = int(MYSQL['PORT'])

    i = 0
    while True:
        if i > 10:
            save_log('ERROR', 'pooldb connection error !')
            sys.exit()
        time.sleep(round(float(random.randrange(0, 100, 1)) / 100, 2))
        try:
            pooldb = PooledDB.PooledDB(MySQLdb,
                                       maxusage=MYSQL['SIZE'],
                                       host=host,
                                       user=user,
                                       passwd=passwd,
                                       db=db,
                                       port=port,
                                       charset='utf8')
            return pooldb.connection()

        except Exception as e:
            i = i + 1
            continue
Beispiel #13
0
	def stop(self):
		"""
		Stop the daemon
		"""
		# Get the pid from the pidfile
		try:
			pf = file(self.pidfile,'r')
			pid = int(pf.read().strip())
			pf.close()
		except IOError:
			pid = None
	
		if not pid:
			message = "pidfile %s does not exist. osa Daemon not running?\n"
			sys.stderr.write(message % self.pidfile)
			return # not an error in a restart
		# Try killing the daemon process	
		try:
			while 1:
				os.kill(pid, SIGTERM)
				time.sleep(0.1)
		except OSError, err:
			err = str(err)
			if err.find("No such process") > 0:
				if os.path.exists(self.pidfile):
					os.remove(self.pidfile)
			else:
				save_log('ERROR','Stop error,'+str(err))
				sys.exit(1)
Beispiel #14
0
def update(sqlstr):
    '''
	更新数据库,update操作
	@sqlstr SQL语句
	return 更新的行数
	'''

    if sqlstr[0:6].upper() == 'UPDATE':
        sql = sqlstr
    else:
        return 0
    try:
        con = _get_pcon()
        cur = con.cursor()
        cur.execute(sql)
    except Exception as uerror:
        save_log('ERROR',
                 'update sql error 1:' + str(uerror) + ',sql is :' + sqlstr)
        time.sleep(random.randint(0, 10))

        try:
            con = _get_con()
            cur = con.cursor()
            cur.execute(sql)
        except Exception as uerror:
            save_log(
                'ERROR',
                'update sql error 2:' + str(uerror) + ',sql is :' + sqlstr)

    _exit(con, cur)

    return int(cur.rowcount)
Beispiel #15
0
def send_one_ping(my_socket, dest_addr, ID):
	"""
	Send one ping to the given >dest_addr<.
	"""
	dest_addr  =  socket.gethostbyname(dest_addr)
 
	# Header is type (8), code (8), checksum (16), id (16), sequence (16)
	my_checksum = 0
 
	# Make a dummy heder with a 0 checksum.
	header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
	bytesInDouble = struct.calcsize("d")
	data = (192 - bytesInDouble) * "Q"
	data = struct.pack("d", time.time()) + data
 
	# Calculate the checksum on the data and the dummy header.
	my_checksum = checksum(header + data)
 
	# Now that we have the right checksum, we put that in. It's just easier
	# to make up a new header than to stuff it into the dummy.
	header = struct.pack(
		"bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1
	)
	packet = header + data
	try:	
		my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1
	except Exception as e:
		save_log('ERROR','ping error:'+str(e))	
Beispiel #16
0
def getIdByCmd(cmdTitle):
    '''
	根据指令名获取指令Id
	@cmdTitle: 指令名称
	'''

    con = _get_pcon()
    cur = con.cursor()

    try:
        cur.execute("select id from osa_command where oCmdTitle='%s'" %
                    cmdTitle)
    except Exception as e:
        time.sleep(0.01)
        cur.execute("select id from osa_command where oCmdTitle='%s'" %
                    cmdTitle)
        save_log('ERROR', e)
        return 'null'

    res = cur.fetchone()

    if not res:
        id = 'null'
    else:
        id = res[0]

    _exit(con, cur)

    return id
Beispiel #17
0
def mut_process():
	'''
	@生成多进程,执行计划任务
	'''
	#根据ID生成子进程
	tinfolist = getTaskList()
	
	if tinfolist != None:
		tq = putTaskId(tinfolist)		
		while True:
			if tq.qsize() == 0:
				break		
		
			for x in xrange(TASK['maxprocess']):
				tinfo = getTaskId(tq)
				if tinfo == None:
					break
				save_log('INFO','Task run :'+str(tinfo))
				try:
					#处理子进程退出信号
					signal.signal(signal.SIGCHLD,signal.SIG_IGN)
					i = Process(target=doTaskMain, args = [tinfo])
					i.start()
				except Exception as taskerror:
					save_log('ERROR','task process error:'+str(taskerror))
Beispiel #18
0
def Update_osa_serverinfo(data):
	'''
	更新osa_serverinfo表里的oStatus和oNotiNum字段
	'''
	time.sleep(round(float(random.randrange(0, 100, 1))/100,2))
	sql="UPDATE osa_serverinfo SET oStatus='"+data[3]+"',oNotiNum="+str(data[4])+" WHERE id="+str(data[0])
	try:
		update(sql)
	except Exception as e:
		save_log('ERROR','sql:'+sql+'fail! ERROR:'+str(e))
Beispiel #19
0
def Update_osa_alarms(data):
	'''
	更新osa_alarms表里的oNextCheckTime字段 
	'''
	sql= "UPDATE osa_alarms SET oNextCheckTime='"+data[14]+"' WHERE id="+str(data[0])
	try:
		time.sleep(round(float(random.randrange(0, 100, 1))/100,2))
		update(sql)
	except Exception as e:
		save_log('ERROR','Update_osa_alarms sql:'+sql+'fail! ERROR:'+str(e))	
Beispiel #20
0
def insertMonitor(ip, cmd, monitime):
	'''
	监控记录入库
	@ip: 被监控主机Ip
	@cmd: 包括指令名称
	'''

	oipid = 'null'
	# 获取oipid
	oipid = getIdByIp(ip)
	if oipid == 'null' or not oipid:
		oipid = 0

	oMonTextRemote = False

	if hostSocket.PortIsAlive(ip, SOCKET['REMOTE_PORT']):
        # 从远程服务器获取数据  
		oMonTextRemote = hostSocket.proSocket(ip, SOCKET['REMOTE_PORT'], cmd)
                

	if oMonTextRemote:
		oMonText = oMonTextRemote.split('!')
	else:
		oMonText = ['mon_all_stat','null']

	#开锁,解决数据库资源争用问题
	lock = setLock()
	cmdid = 'null'
	# 获取cmdid(指令ID)
	try:	
		cmdid = addCmdgetId(cmd)
		if cmdid == 'null' or not cmdid:
			time.sleep(random.randint(0,10))
			cmdid = addCmdgetId(cmd)
	except Exception as e:
		time.sleep(random.randint(0,10))
		cmdid = 0
		save_log( 'ERROR',  'cmdid error:'+str(e) +','+ cmd )
	
	cmdtext = oMonText[1]
	
	try:
		sql = "insert into osa_monitor(oIpid, oCmdid, oMonTime, oMonText) \
				values (%(oipid)d, %(cmdid)d, '%(monitime)s','%(cmdtext)s')" % vars()
		con = _get_pcon()
		cur = con.cursor()
		cur.execute(sql)
	
	except TypeError,e:
		con = _get_con()
		cur = con.cursor()
		cur.execute(sql)
		os.system('rm -f ' + lock)
		save_log('WARNING','insertMonitor : '+str(e))
		sys.exit()
Beispiel #21
0
def doTaskMain(tinfo):
	'''
	@tinfo 批量操作指令类型
	@执行计划任务
	'''
	cmdstr, ip = ayCmdToConsole(tinfo)
	try:
		type = 'task'
		chooseBatchDef(cmdstr,tinfo,type)
	except Exception as e:
		save_log('ERROR','TASK batch chooseBatchDef error:'+str(e))	
Beispiel #22
0
def insertMonitor(ip, cmd, monitime):
    '''
	监控记录入库
	@ip: 被监控主机Ip
	@cmd: 包括指令名称
	'''

    oipid = 'null'
    # 获取oipid
    oipid = getIdByIp(ip)
    if oipid == 'null' or not oipid:
        oipid = 0

    oMonTextRemote = False

    if hostSocket.PortIsAlive(ip, SOCKET['REMOTE_PORT']):
        # 从远程服务器获取数据
        oMonTextRemote = hostSocket.proSocket(ip, SOCKET['REMOTE_PORT'], cmd)

    if oMonTextRemote:
        oMonText = oMonTextRemote.split('!')
    else:
        oMonText = ['mon_all_stat', 'null']

    #开锁,解决数据库资源争用问题
    lock = setLock()
    cmdid = 'null'
    # 获取cmdid(指令ID)
    try:
        cmdid = addCmdgetId(cmd)
        if cmdid == 'null' or not cmdid:
            time.sleep(random.randint(0, 10))
            cmdid = addCmdgetId(cmd)
    except Exception as e:
        time.sleep(random.randint(0, 10))
        cmdid = 0
        save_log('ERROR', 'cmdid error:' + str(e) + ',' + cmd)

    cmdtext = oMonText[1]

    try:
        sql = "insert into osa_monitor(oIpid, oCmdid, oMonTime, oMonText) \
				values (%(oipid)d, %(cmdid)d, '%(monitime)s','%(cmdtext)s')" % vars()
        con = _get_pcon()
        cur = con.cursor()
        cur.execute(sql)

    except TypeError, e:
        con = _get_con()
        cur = con.cursor()
        cur.execute(sql)
        os.system('rm -f ' + lock)
        save_log('WARNING', 'insertMonitor : ' + str(e))
        sys.exit()
Beispiel #23
0
def InsertInto_osa_serverinfo(oMonitorId,oIpOrUrl,oStatus,oNotiNum):
	'''
	为osa_serverinfo表增加新的条目
	'''
	sql = "INSERT INTO  osa_serverinfo (`oMonitorId`, `oIpOrUrl`, `oStatus`, `oNotiNum`, `oAddTime`) VALUES ("+str(oMonitorId)+",'"+oIpOrUrl+"','"+oStatus+"',"+str(oNotiNum)+",'"+str(_get_time(1))+"')" 
	try:
		con = _get_pcon()
		cur = con.cursor()
		cur.execute(sql)
	except Exception as e:
		save_log('ERROR','sql INSERT fail! sql:'+sql+'ERROR:'+str(e))
		return 
	return 
Beispiel #24
0
def mut_process(cmd,q,monitime):
	if cmd.isspace() or not cmd:
		cmd = 'SYSTEM_RUN_COMMAND!{"mon_all_stat":""}' 
	for x in xrange(PNUM['num']):
		ip = q.get()
		try:
			signal.signal(signal.SIGCHLD,signal.SIG_IGN)
			i = Process(target=cmdtosql.insertMonitor, args = [ip,cmd,monitime])
			i.start()
						
		except Exception as e:			
			save_log('ERROR','Process Exception:' + str(e))
		if q.qsize() == 0:
			break
Beispiel #25
0
	def _daemonize(self):
		"""
		@osa 守护进程主方法
		"""
		
		#脱离父进程
		try: 
			pid = os.fork() 
			if pid > 0:
				sys.exit(0) 
		except OSError, e: 
			sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
			save_log('ERROR',"osa damo fork #1 failed:"+str(e.strerror))
			sys.exit(1)
Beispiel #26
0
def ger_snmp_get(agent,ip,key,port,oid):
    if port is None:
        port = 161
    cg=cmdgen.CommandGenerator()
    errorIndication, errorStatus, errorIndex, varBindTable = cg.getCmd(
        cmdgen.CommunityData(agent, key,1),
        cmdgen.UdpTransportTarget((ip, port)),
        #cmdgen.UdpTransportTarget((ip, port),timeout=15,retries=3)
        oid
    )
    if varBindTable:
        return varBindTable
    else:
        save_log('ERROR', ip+errorIndication)        
        sys.exit(0)
Beispiel #27
0
def mut_process(cmd, q, monitime):
    if cmd.isspace() or not cmd:
        cmd = 'SYSTEM_RUN_COMMAND!{"mon_all_stat":""}'
    for x in xrange(PNUM['num']):
        ip = q.get()
        try:
            signal.signal(signal.SIGCHLD, signal.SIG_IGN)
            i = Process(target=cmdtosql.insertMonitor,
                        args=[ip, cmd, monitime])
            i.start()

        except Exception as e:
            save_log('ERROR', 'Process Exception:' + str(e))
        if q.qsize() == 0:
            break
Beispiel #28
0
    def _daemonize(self):
        """
		@osa 守护进程主方法
		"""

        #脱离父进程
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError, e:
            sys.stderr.write("fork #1 failed: %d (%s)\n" %
                             (e.errno, e.strerror))
            save_log('ERROR', "osa damo fork #1 failed:" + str(e.strerror))
            sys.exit(1)
Beispiel #29
0
def index(rev,type,ip,x=''):
	'''
	@批量更新配置文件主函数
	return 空
	'''
	if not rev or not ip:
		return False
	if not type:
		type = 'batch'
	
	try:
		r = batchFileSend(rev,ip,type)
	except Exception as e:
		save_log('ERROR','BATCH_CONFIG_UPDATE:'+str(e))
	#子线程退出
	sys.exit()
def index(rev,type,ip,x=''):
	'''
	@批量分发文件主函数
	return 空
	'''
	if not rev or not ip:
		return False
	if not type:
		type = 'batch'
	try:
		save_log('INFO','Threed:'+str(x)+' start!ip:'+ip+',cmd : BATCH_DOCUMENT_DISTRIBUTION。')
		r = batchFileSend(rev,ip,type)
	except Exception as e:
		save_log('ERROR','BATCH_DOCUMENT:'+str(e))
	#子线程退出
	sys.exit()
Beispiel #31
0
def index(rev, type, ip, x=''):
    '''
	@ 磁盘空间检查执行主函数
	return 空
	'''
    if not rev or not ip:
        return False
    if not type:
        type = 'batch'

    try:
        r = osaBatchLib.batchSendCmd(rev, ip, type)
    except Exception as e:
        save_log('ERROR', 'BATCH_DISKSPACE_CHECK:' + str(e))
    #子线程退出
    sys.exit()
Beispiel #32
0
def index(rev,type,ip,x=''):
	'''
	@ 磁盘空间检查执行主函数
	return 空
	'''
	if not rev or not ip:
		return False
	if not type:
		type = 'batch'
	
	try:
		r = osaBatchLib.batchSendCmd(rev,ip,type)
	except Exception as e:
		save_log('ERROR','BATCH_DISKSPACE_CHECK:'+str(e))
	#子线程退出
	sys.exit()
Beispiel #33
0
def index(rev,type,ip,x=''):
	'''
	@批量清理文件主函数
	return 空
	'''
	if not rev or not ip:
		return False
	if not type:
		type = 'batch'
	
	try:
		r = osaBatchLib.batchSendCmd(rev,ip,type)
	except Exception as e:
		save_log('ERROR','BATCH_FILE_CLEANER:'+str(e))
	#子线程退出
	sys.exit()
def index(rev, type, ip, x=''):
    '''
	@批量更新配置文件主函数
	return 空
	'''
    if not rev or not ip:
        return False
    if not type:
        type = 'batch'

    try:
        r = batchFileSend(rev, ip, type)
    except Exception as e:
        save_log('ERROR', 'BATCH_CONFIG_UPDATE:' + str(e))
    #子线程退出
    sys.exit()
Beispiel #35
0
def osaSendFile(filename='',remoteip='',port=''):
	'''
	@filename 发送的文件名
	@remoteip 远程IP地址
	@remoteip 远程接收端口
	'''

	if not filename or not remoteip:
		return 0

	BUFSIZE = int(FSOCKET['bufsize'])
	sendSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	sendSock.connect((remoteip,port))
	try:
		####修改传送方式,文件名和长度设置为定长,不能超过1024####		
		#fhead=struct.pack(FSOCKET['cfmt'],filename,0,0,0,0,0,0,0,0,os.stat(filename).st_size,0,0)		
		fhead = str(filename) + '||||' + str( os.stat(filename).st_size ) + '||||'
 		if len(fhead) > 1024:
			save_log('ERROR','filename or file path is too long,Recommend less than 1024。')
			return 0
		
		nfhead = ''
		for i in xrange(1024 - len(fhead)):
			nfhead = '@' + nfhead

                fhead = fhead + nfhead
               
	except Exception as e:
		save_log('ERROR','fhead is error:  '+str(e)+' , fhead : '+ str(fhead))
		
	sendSock.send(fhead)

	fp = open(filename,'rb')

	while True:
		filedata = fp.read(BUFSIZE)

		if not filedata: 
			break

		sendSock.send(filedata)

	fp.close()
	sendSock.close()
	
	return 1
Beispiel #36
0
def _get_pcon():
	'''
	获取数据库连接
	'''
	j=0
	while True:
		if j>10:
			save_log('ERROR', 'MySQLdb connection error !')
			sys.exit()
		time.sleep(round(float(random.randrange(0, 100, 1))/100,2))
		try:
			MDB = MySQLdb.connect(host=MYSQL['HOST'],user=MYSQL['USER'],
					passwd=MYSQL['PASSWD'],db=MYSQL['DB'],port=int(MYSQL['PORT']),charset='utf8')
			return MDB
		except Exception as e:		
			j=j+1
			continue
Beispiel #37
0
def batchresult(r):
    '''
	@处理批量操作结果
	'''
    rdict = eval(r)
    oCmdType = rdict['batchinfo']['command']
    oBatchid = rdict['batchinfo']['id']
    oClientip = rdict['batchinfo']['clientip']
    oRunTime = _get_time(flag=1)
    oResult = str(rdict['batchresult'])
    if rdict['batchinfo']['type'] == 'batch':
        isql = "INSERT INTO `osa_tasknow_result` (`oCmdType`,  `oRunTime`, `oTaskNowid`,`oClientip`, `oResult`) VALUES ('" + oCmdType + "', '" + str(
            oRunTime) + "', " + str(oBatchid) + ", '" + str(
                oClientip) + "', \"" + oResult + "\")"
    else:
        isql = "INSERT INTO `osa_taskplan_result` (`oCmdType`, `oRunTime`, `oTaskPlanid`, `oClientip`, `oResult`) VALUES ('" + oCmdType + "', '" + str(
            oRunTime) + "', " + str(oBatchid) + ", '" + str(
                oClientip) + "', \"" + oResult + "\")"

    try:
        con = _get_pcon()
        cur = con.cursor()
        cur.execute(isql)
    except Exception as inserror:
        _exit(con, cur)
        save_log(
            'ERROR', 'insert into db error 1,sql is:' + isql + ",error info:" +
            str(inserror))
        time.sleep(random.randint(0, 10))
        try:
            con = _get_con()
            cur = con.cursor()
            cur.execute(isql)
        except Exception as inserror:

            save_log(
                'ERROR', 'insert into db error 2,sql is:' + isql +
                ",error info:" + str(inserror))
        finally:
            _exit(con, cur)
            sys.exit()
    finally:
        _exit(con, cur)
        sys.exit()
Beispiel #38
0
def socketAccp(host="0.0.0.0", port=SOCKET["PORT"]):
    """
	server指令接收模块
	@host: 主机Ip
	@port: socket端口
	"""

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((host, port))
    sock.listen(SOCKET["LISTEN"])
    while True:
        try:
            connection, address = sock.accept()
            connection.settimeout(SOCKET["TIMEOUT"])
            t = threading.Thread(target=socketDo, args=[connection, address])
            t.start()
        except Exception as e:
            save_log("ERROR", "server socket accept error : " + str(e))
Beispiel #39
0
def socketAccp(host='0.0.0.0', port=SOCKET['PORT']):
    '''
	server指令接收模块
	@host: 主机Ip
	@port: socket端口
	'''

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((host, port))
    sock.listen(SOCKET['LISTEN'])
    while True:
        try:
            connection, address = sock.accept()
            connection.settimeout(SOCKET['TIMEOUT'])
            t = threading.Thread(target=socketDo, args=[connection, address])
            t.start()
        except Exception as e:
            save_log('ERROR', 'server socket accept error : ' + str(e))
Beispiel #40
0
def SendMail(type,user_list,item,subitem):
	'''
	邮件通知函数,建立邮件内容并发送给指定用户
	'''
	if type == 'RECOVERNOTIFY':
		mailbody = 'Message level:INFO,'+str(CreateMailBody('RECOVERNOTIFY',item,subitem))
		emailaddrlist = GetUserEmailAddress(user_list)
		for emailaddr in emailaddrlist:
			try:
				notifyByEmail(subject='[INFO]Notify from OSA',content = mailbody,address = emailaddr)
			except Exception as e:
				save_log('ERROR',"send mail fail! ERROR:"+str(e))
	if type == 'STATUS_EXCEPTION':
		mailbody = 'Message level:ERROR,'+str(CreateMailBody('STATUS_EXCEPTION',item,subitem))
		emailaddrlist = GetUserEmailAddress(user_list)
		for emailaddr in emailaddrlist:
			try:
				notifyByEmail(subject='[ERROR]Notify from OSA',content = mailbody,address = emailaddr)
			except Exception as e:
				save_log('ERROR',"send mail fail! ERROR:"+str(e))		
Beispiel #41
0
def CreateAlarmMsg(oItemName,oItemid,oServerip,oAlarmInfo,oType):
	'''
	增加新的告警信息:往osa_alarmmsg表里增加新的条目
	'''
	now = _get_time(1)	
	sql = "INSERT INTO  osa_alarmmsg (`oAddTime`, `oItemName`, `oItemid`, `oServerip`, `oAlarmInfo`, `oType`) VALUES ('"+now+"','"+oItemName+"',"+str(oItemid)+",'"+oServerip+"','"+oAlarmInfo+"',"+str(oType)+")"
	
	try:
		con = _get_pcon()
		cur = con.cursor()
		cur.execute(sql)
	
	except Exception as e:
		save_log('ERROR','sql INSERT fail! sql:'+sql+',ERROR:'+str(e))	
		_exit(con, cur)
		
		return 
	finally:
		_exit(con, cur)
		return 
Beispiel #42
0
def chooseoRunCycle():
	'''
	@根据周期,返回数据列表
	'''
	rinfo = getoRunCycle()
	
	rlist = []
	
	for r in rinfo:
		
		if r[7] != None:
			cmdinfo = ''
			try:
				cmdinfo = getoCombinCmd(int(r[0]),r[4])						
			except Exception as e:
				save_log('ERROR','getoCombinCmd error:'+str(e))
			
			if cmdinfo:
				save_log('INFO','TASK CMD:'+str(cmdinfo[0][0]))
				rlist.append(cmdinfo[0][0])
				nexttime = getNextRunTime(r)
				if nexttime == False or not nexttime:
					Isql = "INSERT INTO `osa_complantask`(oCmdType,oTaskplanid,oRunCycle,oRunDate,oRunTime) select oCmdType,id,oRunCycle,oRunDate,oRunTime from osa_taskplan"
					try:
						con = cmdtosql._get_pcon()
						cur = con.cursor()
						cur.execute(Isql)			
						
					except Exception as Ierror:
						save_log('ERROR','osa_complantask INSERT ERROR:'+str(Ierror)+',sql is: '+Isql)
					finally:
						cmdtosql._exit(con, cur)
					Dsql = 	"DELETE from osa_taskplan WHERE id = "+str(r[0])
					try:
						con = cmdtosql._get_pcon()
						cur = con.cursor()
						cur.execute(Dsql)							
					except Exception as Ierror:
						save_log('ERROR','osa_taskplan DELETE ERROR:'+str(Ierror)+',sql is: '+Dsql)						
					finally:
						cmdtosql._exit(con, cur)						
				else:				
				
					usql = "UPDATE `osa_taskplan` set oStatus = '运行中',oRunNextTime = '"+nexttime+"',oRunLastTime = '"+str(cmdtosql._get_time(flag=1))+"' WHERE id = "+str(r[0])				
					cmdtosql.update(usql)
		else:
			nexttime = getNextRunTime(r)
			usql = "UPDATE `osa_taskplan` set oStatus = '运行中',oRunNextTime = '"+nexttime+"',oRunLastTime = '"+str(cmdtosql._get_time(flag=1))+"' WHERE id = "+str(r[0])				
			cmdtosql.update(usql)
			
	return rlist
Beispiel #43
0
def _get_pcon():
    '''
	获取数据库连接
	'''
    j = 0
    while True:
        if j > 10:
            save_log('ERROR', 'MySQLdb connection error !')
            sys.exit()
        time.sleep(round(float(random.randrange(0, 100, 1)) / 100, 2))
        try:
            MDB = MySQLdb.connect(host=MYSQL['HOST'],
                                  user=MYSQL['USER'],
                                  passwd=MYSQL['PASSWD'],
                                  db=MYSQL['DB'],
                                  port=int(MYSQL['PORT']),
                                  charset='utf8')
            return MDB
        except Exception as e:
            j = j + 1
            continue