예제 #1
0
def batchServiceRestart(rev):
	'''
	@服务操作函数
	'''
	
	
	
	#判断是否选择了脚本操作
	citem = osaBatchLib.getConfigItem(rev)	
	
	if 'service_scriptfile' in citem:
		script = citem['service_scriptfile']
	else:		
		script = 'service '+str(citem['service_name'])+' '+citem['service_type']
		
	sr = osaBatchLib.scriptOrCmd(script)
	if sr:
		try:
			result = osaBatchLib.runCmdOrScript(script)
			return "{'status':'OK','result':'OK!'}"
		except Exception as e:
			save_log('ERROR','Cmd or Script is run Faild!'+str(e))
			result = 'Cmd or Script is run Faild!'+str(e)
			return "{'status':'ERROR','result':'services error!'}"	
	else:
		return "{'status':'ERROR','result':'Unknow error!'}"
예제 #2
0
파일: osaDamoClass.py 프로젝트: hacder/src
	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)
예제 #3
0
def chooseBatchDef(fromPhpCmd,rev):
	'''	
	Description: 接收来自PHP端的批量操作指令,执行指定函数
				 前缀:osa_ 加上 PHP端指令名称作函数名称.
				 批量操作的参数统一为:接到到的指令详情
	@fromPhpCmd 来自php端的批量操作指令
	@rev 接收到的指令内容
	return 返回执行结果
	'''
	try:
		
		batchlist = BATCHLIST.keys()
		
                for b in batchlist:
                        path = DIRS['PY_OSA_LIB']+'BatchDo/osa_'+ b +'.py'
                        if os.path.exists(path) and b == fromPhpCmd:
                                try:
                                        f = __import__('unctrlpy.lib.BatchDo.osa_'+b, globals(), locals(), ['index'], -1)
                                except Exception as e:
                                        save_log('ERROR','Import Error:'+str(e))
				break
		if not f:
			return "{'status': 'ERROR', 'result': 'Import batch file Error!'}"
		return f.index(rev)
	except Exception as e:
	
		save_log('ERROR','chooseBatchDef error:'+str(e))
		return "{'status': 'ERROR', 'result': 'chooseBatchDef error:'"+str(e)+"}"
예제 #4
0
def batchCmdOrShell(rev):
	'''
	@命令或者脚本执行函数
	'''
	
	
	
	#判断是否选择了脚本操作
	citem = osaBatchLib.getConfigItem(rev)
	
	if 'command_scriptfile' in citem:
		scmd = citem['command_scriptfile']
	else:		
		return "{'status':'ERROR','result':'Unknow error!'}"
	sr = osaBatchLib.scriptOrCmd(scmd)
	
	if sr:
		try:
			result = osaBatchLib.runCmdOrScript(scmd)
			return "{'status':'OK','result':'"+result+"'}"
		except Exception as e:
			save_log('ERROR',str(e))
			result = 'Cmd or Script is run Faild!'
			return "{'status':'ERROR','result':'"+result+"'}"	
	else:
		return "{'status':'ERROR','result':'Unknow error!'}"
예제 #5
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)
예제 #6
0
def rmgeneric(path, __func__):

    try:
        __func__(path)
        save_log('INFO', 'Removed: ' + str(path))
    except OSError, (errno, strerror):
        ERROR_STR = """Error removing %(path)s, %(error)s """
        save_log('ERROR', ERROR_STR % {'path': path, 'error': strerror})
        return False
예제 #7
0
파일: osaSysFunc.py 프로젝트: hacder/src
def rmgeneric(path, __func__):  
  
	try:  
		__func__(path)  
		save_log('INFO','Removed: '+str(path))  
	except OSError, (errno, strerror):  
		ERROR_STR= """Error removing %(path)s, %(error)s """  
		save_log('ERROR',ERROR_STR % {'path' : path, 'error': strerror })
		return False
예제 #8
0
파일: osaDamoClass.py 프로젝트: hacder/src
	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)
예제 #9
0
def batchAppInstalltion(rev):
	'''
	安装执行函数,实为调用一个shell脚本
	'''
	value = osaBatchLib.getConfigItem(rev)
	script=value['install_scriptfile']
	if script:
		try:
			result = osaBatchLib.runCmdOrScript(script)
			return "{'status':'OK','result':'"+result+"'}"
		except Exception ,e:
			save_log('ERROR',str(e))
			result = 'Install Script run failed!'
			return "{'status':'ERROR','result':'"+result+"'}"
예제 #10
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)
예제 #11
0
파일: osaSysFunc.py 프로젝트: hacder/src
def mvfile(src, dst , filetype):
	
	for i in os.listdir(src):
		filepath = src + os.sep + i
		if src.endswith(os.sep):
			filepath = src + i		
		if os.path.isdir(filepath):
			mvfile(filepath, dst,filetype)
		elif i.endswith(filetype) or re.search(filetype,i):
			try:				
				shutil.move(filepath, dst)
				save_log('INFO','move: '+filepath +' to ' +dst)				
			except Exception as error:
				save_log('ERROR','move:'+filepath +' to' +dst+ ' is error!')
				return False	
	return True 
예제 #12
0
def mvfile(src, dst, filetype):

    for i in os.listdir(src):
        filepath = src + os.sep + i
        if src.endswith(os.sep):
            filepath = src + i
        if os.path.isdir(filepath):
            mvfile(filepath, dst, filetype)
        elif i.endswith(filetype) or re.search(filetype, i):
            try:
                shutil.move(filepath, dst)
                save_log('INFO', 'move: ' + filepath + ' to ' + dst)
            except Exception as error:
                save_log('ERROR',
                         'move:' + filepath + ' to' + dst + ' is error!')
                return False
    return True
예제 #13
0
def ayCmd(fromAngentCmd):
	'''
	@fromPhpCmd: 来自agent端的指令	
	'''
	try:
		phpdict = {}
		batchlist = BATCHLIST.keys()
		if re.search('BATCH_',fromAngentCmd):
			phpdict = eval(fromAngentCmd)
		if not phpdict or not phpdict['command']:
			return False
		if phpdict['command'] in batchlist:
			return phpdict['command']
		return False		
	except Exception as allargs:				
		errlog = 'ayCmdToConsole Error : %s ' % allargs
		save_log('WARNING', errlog)	
		return False
예제 #14
0
파일: osaFilelib.py 프로젝트: briankang/osa
def isMySelfCmd(fromPhpCmd):
	'''
	@cmd 转发给unctrlpy端的指令
		判断该指令是否需要加工处理
		return 需要加工的函数 or False
	'''
	try:
		mylist = ['getconfigfile','saveconfigfile']
		num = len(fromPhpCmd.split('!'))
		cmstr  = (((fromPhpCmd.split('!')[num-1]).split(':')[0]).replace('"','')).replace('{','')
		for i in mylist:
			if str(cmstr) == str(i):
				
				return str(i)
	except Exception as e:
		save_log('ERROR',str(e))
		return False
	return False
예제 #15
0
def batchConfigBackup(rev):
    '''
	@配置文件备份
	'''

    #源文件
    citem = osaBatchLib.getConfigItem(rev)
    sfilelist = citem['config_backup_sourcefile'].split('|')

    for sfile in sfilelist:

        sname = os.path.basename(sfile)

        #文件保存目标位置
        dfile = citem['config_backup_dir']

        if citem['config_backup_rule'] == '1' or citem[
                'config_backup_rule'] == 1:
            if dfile.endswith(os.sep):
                dpath = dfile + sname + '.bak'
            else:
                dpath = dfile + os.sep + sname + '.bak'
        else:
            if dfile.endswith(os.sep):
                dpath = dfile + sname + '.bak.' + str(
                    time.strftime('%Y-%m-%d_%H:%M:%S', time.localtime()))
            else:
                dpath = dfile + os.sep + sname + '.bak.' + str(
                    time.strftime('%Y-%m-%d_%H:%M:%S', time.localtime()))

        if not os.path.exists(dfile):
            try:
                os.makedirs(dfile)
            except Exception as e:
                save_log('ERROR', 'mkdir error:' + str(e))
                return "{'status':'ERROR','result':'x0052,mkdir error.'}"

        try:
            shutil.copyfile(sfile, dpath)
        except Exception as e:
            save_log('ERROR', 'copy file error:' + str(e))
            return "{'status':'ERROR','result':'x0051,copy file error.'}"

    return "{'status':'OK','result':'config backup succeed!'}"
예제 #16
0
파일: osaFilelib.py 프로젝트: briankang/osa
def GetConfigFile(ip,cname,port):
	'''
	@ip agent端的ip地址
	@cname 配置文件名
	@port 远程机器文件传端口
	return 给PHP的文件名和文件大小 or False
	'''

	cfile = CFILENAME[cname]
	
	try:
		S = osaSendFile(filename=cfile,remoteip=ip,port=int(port))
	except Exception as e:
		save_log('ERROR',e)
		time.sleep(1)
		S = osaSendFile(filename=cfile,remoteip=ip,port=int(port))
	
	if S:
		toAgentCmd = 'SYSTEM_RUN_COMMAND!{"getconfigfile":"sentfileok"}'
	return toAgentCmd
예제 #17
0
파일: osaFilelib.py 프로젝트: briankang/osa
def SaveConfigFile(ip,cname,port):
	'''
	@ip 远程IP地址
	@cname 配置文件名称
	'''
	
	cfile = CFILENAME[cname]
	fsize = None
	
	try:
		fsize = file_recv_main(host='0.0.0.0',port=int(port),filename = cfile)
	except Exception as e:
		save_log('ERROR',str(e))
		return False

	if fsize:
		os.system('/usr/bin/dos2unix -k '+ cfile)
		return 'SYSTEM_RUN_COMMAND!{"saveconfigfile":"saveok"}'
	
	return None
예제 #18
0
def batchConfigBackup(rev):
	'''
	@配置文件备份
	'''
	
	#源文件
	citem = osaBatchLib.getConfigItem(rev)
	sfilelist = citem['config_backup_sourcefile'].split('|')
	
	for sfile in sfilelist:
	
		sname = os.path.basename(sfile)
	
		#文件保存目标位置
		dfile = citem['config_backup_dir']
		
		if citem['config_backup_rule'] == '1' or citem['config_backup_rule'] == 1 :
			if dfile.endswith(os.sep):
				dpath = dfile + sname + '.bak'
			else:
				dpath = dfile + os.sep + sname + '.bak'  
		else:
			if dfile.endswith(os.sep):
				dpath = dfile + sname + '.bak.' + str(time.strftime('%Y-%m-%d_%H:%M:%S', time.localtime()))
			else:
				dpath = dfile + os.sep + sname + '.bak.' + str(time.strftime('%Y-%m-%d_%H:%M:%S', time.localtime()))
			
		if not os.path.exists(dfile):
			try:
				os.makedirs(dfile)
			except Exception as e:
				save_log('ERROR','mkdir error:'+str(e))
				return "{'status':'ERROR','result':'x0052,mkdir error.'}"
	
		try:
			shutil.copyfile(sfile,dpath)
		except Exception as e:
			save_log('ERROR','copy file error:'+str(e))
			return "{'status':'ERROR','result':'x0051,copy file error.'}"	
	
	return "{'status':'OK','result':'config backup succeed!'}"
예제 #19
0
파일: osaDamoClass.py 프로젝트: hacder/src
	def start(self):
		"""
		Start the daemon
		"""
		# Check for a pidfile to see if the daemon already runs
		try:
			pf = file(self.pidfile,'r')
			pid = int(pf.read().strip())
			pf.close()
		except IOError:
			pid = None
	
		if pid:
			message = "Start error,pidfile %s already exist. Daemon already running?\n"
			save_log('ERROR',message)
			sys.stderr.write(message % self.pidfile)
			sys.exit(1)
		
		# Start the daemon
		self._daemonize()
		self._run()
예제 #20
0
    def start(self):
        """
		Start the daemon
		"""
        # Check for a pidfile to see if the daemon already runs
        try:
            pf = file(self.pidfile, 'r')
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None

        if pid:
            message = "Start error,pidfile %s already exist. Daemon already running?\n"
            save_log('ERROR', message)
            sys.stderr.write(message % self.pidfile)
            sys.exit(1)

        # Start the daemon
        self._daemonize()
        self._run()
예제 #21
0
class Daemon:
    """
	osa daemon class.	
	Usage: subclass the Daemon class and override the _run() method
	"""
    def __init__(self,
                 pidfile,
                 stdin='/dev/null',
                 stdout='/dev/null',
                 stderr='/dev/null'):
        self.stdin = stdin
        self.stdout = stdout
        self.stderr = stderr
        self.pidfile = pidfile

    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)

        #脱离终端
        os.setsid()
        #修改当前工作目录
        os.chdir(DIRS['ROOT'])
        #加载环境变量
        osapath = DIRS['ROOT']
        sys.path.append(osapath)
        #重设文件创建权限
        os.umask(0)

        #第二次fork,禁止进程重新打开控制终端
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError, e:
            sys.stderr.write("fork #2 failed: %d (%s)\n" %
                             (e.errno, e.strerror))
            save_log('ERROR', "osa damo fork #2 failed:" + str(e.strerror))
            sys.exit(1)
예제 #22
0
파일: osaClient.py 프로젝트: briankang/osa
def socketAccp(host = '0.0.0.0', port = SOCKET['PORT']):
	'''
	@host: 主机Ip
	@port: socket port
	'''

        # 创建流式套接字
	sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	
	try:
		sock.bind((host, port))
	except Exception as e:
		save_log('ERROR','client bind error:'+str(e))
	
	sock.listen(SOCKET['LISTEN'])
	
	while True:
		con, addr = sock.accept()
		con.settimeout(SOCKET['TIMEOUT'])
		t = threading.Thread(target=doSocket, args=[con,addr])
		t.setDaemon(0)
		t.start()
예제 #23
0
파일: osaClient.py 프로젝트: briankang/osa
def execCMD(cmd):
	'''
	@execCMD: 执行指令
	@cmd: 指令
	return status(指令执行状态)
	info (指令执行返回的数据)
	'''
	
	try:
		infos = ayCmdToExec(cmd)
		
		if len(infos) == 3:
			return infos[0], infos[1]
		execC = execShellScript(infos[0])
				
		if len(execC[1]) > 10:
			return infos[0], reWithToPhp(infos[1], execC[0], value=execC[1])
		else:
			if len(execC[0]) == 1:
				return infos[0], reWithToPhp(infos[1], execC[0], value=execC[1])
			return infos[0], reWithToPhp(infos[1], execC[0][0], execC[0][1], execC[1])
	except Exception as e:
		save_log("ERROR", 'Command Error!'+ cmd + ' 可能原因是:'+ str(e))
		return 'Command Error!','Command Error'
예제 #24
0
def osaSendFile(filename='', remoteip='', port=''):
    '''
	@filename 发送的文件名
	@remoteip 远程IP地址
	'''
    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:

        #fhead=struct.pack(FSOCKET['cfmt'],filename,0,0,0,0,0,0,0,0,os.stat(filename).st_size,0,0)
        ####修改传送方式,文件名和长度设置为定长,不能超过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

        sendSock.send(fhead)

    except Exception as e:
        save_log('ERROR', e)

    fp = open(filename, 'rb')

    while True:
        filedata = fp.read(BUFSIZE)

        if not filedata:
            break
        try:
            sendSock.send(filedata)
        except Exception as e:
            save_log('ERROR', e)
            return None
    fp.close()
    sendSock.close()

    return 1
예제 #25
0
파일: osaFileSend.py 프로젝트: hacder/src
def osaSendFile(filename='',remoteip='',port=''):
	'''
	@filename 发送的文件名
	@remoteip 远程IP地址
	'''
	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:
		
		#fhead=struct.pack(FSOCKET['cfmt'],filename,0,0,0,0,0,0,0,0,os.stat(filename).st_size,0,0)
		####修改传送方式,文件名和长度设置为定长,不能超过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	
	
		sendSock.send(fhead)

	except Exception as e:
		save_log('ERROR',e)

	fp = open(filename,'rb')

	while True:
		filedata = fp.read(BUFSIZE)

		if not filedata: 
			break
		try:
			sendSock.send(filedata)
		except Exception as e:
			save_log('ERROR',e)
			return None
	fp.close()
	sendSock.close()
	
	return 1
예제 #26
0
파일: osaClient.py 프로젝트: briankang/osa
def doSocket(connection,addr):
	'''
	@connection: socket连接
	'''

	try:
		i=0
		j=0
		data = recvs = ''
		while True:
			data = connection.recv(SOCKET['BUFSIZE'])
			if data == '':
				i=i+1
			recvs = recvs + data
			if data.endswith('EOF') or recvs == 'PORT_IS_ALIVE' or i > 2 or j > 10:
				break
			time.sleep(round(float(random.randrange(0, 10000, 1))/10000,4))
			j = j + 1
		#recvs = connection.recv(SOCKET['BUFSIZE'])
		
		ip=addr[0]
		
		if recvs == 'PORT_IS_ALIVE':
			save_log('INFO', recvs)			
			connection.close()
			sys.exit()
		
		if not recvs or recvs == '':
			connection.close()
                        sys.exit()		

		try:
			cmd = decode(recvs)
		except Exception as e:			
			save_log('ERROR', 'decode error:'+str(e)+',recvs :'+str(recvs))
			connection.close()
			sys.exit()
			
		if cmd == 'CMD_STAT':
			save_log('INFO', cmd)
			connection.send(encode('CMD_STAT_OK'))
			connection.close()
			sys.exit()
		
		if cmd.endswith('check'):
			save_log('CHECK', cmd)
			connection.send(encode('error'))
			connection.close()
			sys.exit()	
		
		# is myself def
		cname = isMySelfCmd(cmd)
		
		
		#if batch cmd
		
		batch = isBatchCmd(ayCmd(cmd))
		
		if cname:
			try:
				infos = OsaChooseDef(defname=cname,ip = ip,fromPhpCmd=cmd)
			except Exception,e:
				connection.close()
				save_log('ERROR', str(e))
		#处理批量操作分支
		elif batch:
			connection.close()
			rinfo = chooseBatchDef(ayCmd(cmd),cmd)
			save_log('INFO',str(ayCmd(cmd)))
			##处理批量操作结果			
			ret = "{'batchinfo':"+str(cmd)+",'command':'batchresult','batchresult':"+str(rinfo)+"}"
			port=SOCKET['AGENTPORT']
			r = RproSocket(ip, port, ret)
			if r:
				sys.exit()
			else:
				time.sleep(0.3)
				r = RproSocket(ip, port, str(ret), type=None)
				sys.exit()
예제 #27
0
파일: osaClient.py 프로젝트: briankang/osa
			connection.close()
			rinfo = chooseBatchDef(ayCmd(cmd),cmd)
			save_log('INFO',str(ayCmd(cmd)))
			##处理批量操作结果			
			ret = "{'batchinfo':"+str(cmd)+",'command':'batchresult','batchresult':"+str(rinfo)+"}"
			port=SOCKET['AGENTPORT']
			r = RproSocket(ip, port, ret)
			if r:
				sys.exit()
			else:
				time.sleep(0.3)
				r = RproSocket(ip, port, str(ret), type=None)
				sys.exit()
		else:
			infos = execCMD(cmd)
		save_log('INFO', infos[0])
		ldata=len(encode(infos[1]))
		toAngentData=encode(infos[1])
		
		try:
			connection.send(toAngentData)
		except Exception as e:
			connection.send(infos[1])
			sys.exit()
		
		connection.close()
		sys.exit()
	except Exception as e:
		save_log('ERROR', 'python recv error:'+str(e))
		connection.close()
		sys.exit()
예제 #28
0
def file_recv_main(host='0.0.0.0', port=int(get_fsocket_port()), filename=''):
    '''
	   @host 监听本机
	   @port 接收文件时监控的端口
	   @filename 接收文件的临时保存路径和名称
	'''
    BUFSIZE = FSOCKET['bufsize']

    #用来计算特定格式的输出的大小是几个字节
    FILEINFO_SIZE = struct.calcsize(FSOCKET['fmt'])

    recvSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    recvSock.bind((host, port))

    recvSock.listen(int(FSOCKET['listen']))

    while True:

        try:

            conn, addr = recvSock.accept()
            info = 'File recv from:' + str(addr)
            save_log('INFO', info)
        except socket.error, args:
            (errno, err_msg) = args
            errlog = 'Connect server failed: %s, errno=%d' % (err_msg, errno)
            save_log('ERROR', errlog)

        #####修改接收长度为定值,兼容端口检测######
        fhead = conn.recv(1024)

        if fhead == 'PORT_IS_ALIVE':
            continue

        info = 'File recv from:' + str(addr)
        save_log('INFO', info)

        try:
            f = fhead.split('||||')[0]
            filesize = int(fhead.split('||||')[1])
        except Exception as e:
            save_log('ERROR', str(e) + '' + str(fhead))

        fp = open(filename, 'wb')

        restsize = filesize

        while restsize > 0:
            if restsize > BUFSIZE:
                filedata = conn.recv(BUFSIZE)
            else:
                filedata = conn.recv(restsize)
            fp.write(filedata)
            restsize = restsize - len(filedata)
        fp.close()
        conn.close()
        if filesize != os.stat(filename).st_size:
            save_log('ERROR', 'File transfer fails ! ')
            return False
        info = info + ' File name: ' + str(f) + ' ,filesize:' + str(
            filesize) + ' byte, save as :' + str(filename)
        save_log('INFO', info)
        break
        recvSock.close()
예제 #29
0
def batchFileRecv(rev):
    '''
	@文件接收函数
	'''

    #文件保存目标位置
    citem = osaBatchLib.getConfigItem(rev)
    dfile = citem['targetpath']
    #文件名
    dfilename = os.path.basename(dfile)
    #文件目录
    fdir = os.path.dirname(dfile)
    #目标目录不存在则创建
    if not os.path.exists(fdir):
        try:
            os.makedirs(fdir)
        except Exception as e:
            save_log('ERROR', 'mkdir is error:' + str(e))
            return "{'status':'ERROR','result':'x0027'}"

    #端口号
    fileport = osaBatchLib.getConfigPort(rev)

    #临时文件
    tempfile = osaBatchLib.tempFilePath(rev)
    #开始接收文件
    try:
        fsize = file_recv_main(host='0.0.0.0',
                               port=int(fileport),
                               filename=tempfile)
    except Exception as e:
        save_log('ERROR', 'file recv error:' + str(e))
        return "{'status':'ERROR','result':'x0026'}"

    if fsize:
        #对文件进行处理
        advance = citem['advance'].split('|')
        backfile = dfile + '.bak.' + str(
            time.strftime('%Y-%m-%d_%H:%M:%S', time.localtime()))
        if advance[0] == 'cut':
            if os.path.exists(dfile):
                try:
                    os.rename(dfile, backfile)
                    os.rename(tempfile, dfile)
                except Exception as e:
                    save_log('ERROR', str(e))
                    return "{'status':'ERROR','result':'x0022'}"

            else:
                try:
                    os.rename(tempfile, dfile)
                except:
                    shutil.copy(tempfile, dfile)
        elif advance[0] == 'copy':
            if os.path.exists(dfile):
                try:
                    os.rename(dfile, backfile)
                    os.rename(tempfile, dfile)
                    os.remove(backfile)
                except Exception as e:
                    save_log('ERROR', str(e))
                    return "{'status':'ERROR','result':'x0023'}"

            else:
                try:
                    os.rename(tempfile, dfile)
                except:
                    shutil.copy(tempfile, dfile)
        else:
            return "{'status':'ERROR','result':'x0021'}"
        if advance[1] == 'document_integrity':
            dict = osaBatchLib.revToDict(rev)
            if dict['md5'] != osaBatchLib.md5sum(dfile):
                return "{'status':'ERROR','result':'x0024'}"
        #执行脚本或者指令
        scmd = citem['distribution_script']
        sr = osaBatchLib.scriptOrCmd(scmd)
        if sr:
            try:
                result = osaBatchLib.runCmdOrScript(scmd)
                return "{'status':'OK','result':'" + result + "'}"
            except Exception as e:
                save_log('ERROR', str(e))
                result = 'Cmd or Script is Faild!'
                return "{'status':'ERROR','result':'" + result + "'}"
        return "{'status':'OK','result':'OK'}"
    return "{'status':'ERROR','result':'x0025'}"
예제 #30
0
파일: osaFileRecv.py 프로젝트: hacder/src
def file_recv_main(host='0.0.0.0',port=int(get_fsocket_port()),filename = ''):
	'''
	   @host 监听本机
	   @port 接收文件时监控的端口
	   @filename 接收文件的临时保存路径和名称
	'''
	BUFSIZE = FSOCKET['bufsize']
	
	#用来计算特定格式的输出的大小是几个字节
	FILEINFO_SIZE = struct.calcsize(FSOCKET['fmt'])
	
	recvSock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

	recvSock.bind((host,port))

	recvSock.listen(int(FSOCKET['listen']))
	
	
	while True:
		
		try:
		
			conn,addr = recvSock.accept()
			info = 'File recv from:'+ str(addr)
			save_log('INFO', info)
		except socket.error, args:
			(errno, err_msg) = args
                	errlog = 'Connect server failed: %s, errno=%d' % (err_msg, errno)
                	save_log('ERROR', errlog)
			
		#####修改接收长度为定值,兼容端口检测######
		fhead = conn.recv(1024)
		
		if fhead == 'PORT_IS_ALIVE':
			continue
			
		info = 'File recv from:'+ str(addr)
		save_log('INFO', info)
		
		try:	
			f=fhead.split('||||')[0]
			filesize=int(fhead.split('||||')[1])
		except Exception as e:
			save_log('ERROR', str(e)+''+str(fhead))

		fp = open(filename,'wb')
	
		restsize = filesize

		while restsize > 0:
    			if restsize > BUFSIZE:
       				filedata = conn.recv(BUFSIZE)
    			else:
        			filedata = conn.recv(restsize)
    			fp.write(filedata)
    			restsize = restsize-len(filedata)
		fp.close()
		conn.close()
		if filesize != os.stat(filename).st_size :
			save_log('ERROR','File transfer fails ! ' )
			return False
		info = info + ' File name: '+ str(f) +' ,filesize:'+ str(filesize) + ' byte, save as :'+ str(filename)
		save_log('INFO',info )
		break	
		recvSock.close()
예제 #31
0
def batchFileRecv(rev):
	'''
	@文件接收函数
	'''
	
	#文件保存目标位置
	citem = osaBatchLib.getConfigItem(rev)
	dfile = citem['targetpath']
	#文件名
	dfilename = os.path.basename(dfile)
	#文件目录
	fdir = os.path.dirname(dfile)
	#目标目录不存在则创建
	if not os.path.exists(fdir):
		try:
			os.makedirs(fdir)
		except Exception as e:
			save_log('ERROR','mkdir is error:'+str(e))
			return "{'status':'ERROR','result':'x0027'}"
			
			
		
	#端口号
	fileport = osaBatchLib.getConfigPort(rev)
	
	#临时文件
	tempfile = osaBatchLib.tempFilePath(rev)
	#开始接收文件
	try:
		fsize = file_recv_main(host='0.0.0.0',port=int(fileport),filename = tempfile)
	except Exception as e:
		save_log('ERROR','file recv error:'+str(e))
		return "{'status':'ERROR','result':'x0026'}"	
		
	if fsize:
		#对文件进行处理
		advance = citem['advance'].split('|')
		backfile = dfile+'.bak.'+str(time.strftime('%Y-%m-%d_%H:%M:%S', time.localtime()))
		if advance[0] == 'cut':
			if os.path.exists(dfile):
				try:
					os.rename(dfile,backfile)
					os.rename(tempfile,dfile)
				except Exception as e:			
					save_log('ERROR',str(e))
					return "{'status':'ERROR','result':'x0022'}"
					
			else:
				try:
					os.rename(tempfile,dfile)
				except:
					shutil.copy(tempfile,dfile)
		elif advance[0] == 'copy':
			if os.path.exists(dfile):
				try:
					os.rename(dfile,backfile)
					os.rename(tempfile,dfile)
					os.remove(backfile)
				except Exception as e:
					save_log('ERROR',str(e))
					return "{'status':'ERROR','result':'x0023'}"
					
			else:
				try:
					os.rename(tempfile,dfile)
				except:
					shutil.copy(tempfile,dfile)
		else:
				return "{'status':'ERROR','result':'x0021'}"
		if advance[1] == 'document_integrity':
			dict = osaBatchLib.revToDict(rev)
			if dict['md5'] != osaBatchLib.md5sum(dfile):
				return "{'status':'ERROR','result':'x0024'}"
		#执行脚本或者指令
		scmd = citem['distribution_script']
		sr = osaBatchLib.scriptOrCmd(scmd)
		if sr:
			try:
				result = osaBatchLib.runCmdOrScript(scmd)
				return "{'status':'OK','result':'"+result+"'}"
			except Exception as e:
				save_log('ERROR',str(e))
				result = 'Cmd or Script is Faild!'
				return "{'status':'ERROR','result':'"+result+"'}"	
		return "{'status':'OK','result':'OK'}"
	return "{'status':'ERROR','result':'x0025'}"