def start_tcp_server(self, ip, port, flag, error): """ 功能描述:开启TCP Server 参数: ip: TCP server所在主机IP地址 port: TCP Server监听的端口号 flag: 服务器运行标识 error: 服务器运行的错误信息 """ if check_port_status(ip, port): try: factory = protocol.Factory() factory.protocol = TSServProtocol log_data = "waiting for connection..." log.debug_info(log_data) reactor.listenTCP(port, factory, interface=ip) reactor.callLater(1, self._check_flag, flag) reactor.run() except Exception, e: log_data = "ListenTCP occurs exception, error info is %s" % e log.debug_info(log_data) flag.value = 3 # 开启服务器监听发生异常 error.value = log_data
def telnet_write(self, text, loglevel=None): """Writes the given text plus a newline into the connection. The newline character sequence to use can be [#Configuration|configured] both globally and per connection basis. The default value is `CRLF`. This keyword consumes the written text, until the added newline, from the output and logs and returns it. The given text itself must not contain newlines. Use `Write Bare` instead if either of these features causes a problem. *Note:* This keyword does not return the possible output of the executed command. To get the output, one of the `Read ...` keywords must be used. See `Writing and reading` section for more details. See `Logging` section for more information about log levels. """ self._verify_connection() #调用的telnet_write_bare中有清空前面数据的操作,此处删除 if self._newline in text: raise RuntimeError("'Write' keyword cannot be used with strings " "containing newlines. Use 'Write Bare' instead.") self.telnet_write_bare(text + self._newline) # Can't read until 'text' because long lines are cut strangely in the output write_info = "cur newline :" + (self._newline).replace("\r", "CR").replace("\n", "LF") log.debug_info(write_info) return self.telnet_read_until(self._newline, loglevel)
def init_keygoe_system(self): """ 始化语音卡设备 """ if (VOIP_FUN_OK == self.obj.init_keygoe_system()): log_info = u"开始初始化语音卡设备..." log.user_info(log_info) else: log_info = u"启动系统初始化失败" raise RuntimeError(log_info) nRet = self.obj.wait_trunk_init() if (VOIP_FUN_FIAL == nRet): log_info = u"初始化模拟中继通道失败" raise RuntimeError(log_info) log.debug_info(u"可用Trunk 是 %d" % nRet) for i in range(16): #1111111111111111(2进制)表示可用Trunk有16个 if ((nRet & 1) == 1): self.trunk_id_list.append((i + 1)) nRet = (nRet >> 1) log_info = u"完成系统初始化,可用模拟通道列表如下:" log.user_info(log_info) log.user_info(self.trunk_id_list)
def _send_udp_package(self, dst_ip, dst_port, send_msg, status): """ 功能描述:发送udp报文到UDP Server,并接收回应,验证链路是否通 参数: dst_ip: UDP报文的目的IP dst_port: UDP报文的目的port send_msg: UDP报文的消息内容 status: 链路状态,为1,表示链路正常,为2,表示端口被占用,为3表示connectTCP发生异常,负数表示失败的次数,为0表示链路不通 返回值: ATTUDPCLIENT_SUC, log_data 表示通 ATTUDPCLIENT_FAIL, log_data 表示不通 ATTUDPCLIENT_PORT_BUSY, log_data 表示端口被占用 """ # 检测端口是否被占用,如果源端口为0,表示不用指定源端口,则不用检测 if self.src_port == 0 or check_port_status(self.src_ip, self.src_port, "UDP"): # 设置目的IP和目的端口 TSClntDatagramProtocol.dst_ip = dst_ip TSClntDatagramProtocol.dst_port = int(dst_port) # 设置发送的消息,如果send_msg是列表则直接赋值,如果不是列表,则将send_msg加入到TSClntDatagramProtocol.send_data列表中 if type(send_msg) == type([]): TSClntDatagramProtocol.send_data = send_msg else: TSClntDatagramProtocol.send_data.append(send_msg) protocol = TSClntDatagramProtocol() try: # 判断是否需要绑定源端口 if self.src_port == 0: reactor.listenUDP(0, protocol) else: reactor.listenUDP(self.src_port, protocol, interface=self.src_ip) reactor.callLater(30, self._check_recv_flag) reactor.run() except Exception, e: status.value = 3 log_data = "send udp package ocurrs exception, error info is %s" % e log.debug_info(log_data) if TSClntDatagramProtocol.connection_status: fail_num = TSClntDatagramProtocol.connection_status.count(0) if fail_num == 0: # 没有失败的记录,发送报文全部成功 status.value = 1 else: # 有失败记录,返回失败的次数,用负数表示 status.value = -fail_num else: status.value = 0
def connectionMade(self): """ 当连接建立时,打印客户端的ip和端口 """ client_ip = self.transport.getPeer().host client_port = self.transport.getPeer().port log_data = 'connected from %s:%s' % (client_ip, client_port) log.debug_info(log_data)
def datagramReceived(self, datagram, address): """ 将收到的信息md5加密后,发送回client """ log_data = "from %s, recv: %s" % (address, datagram) log.debug_info(log_data) response_data = hashlib.md5(datagram).hexdigest().upper() self.transport.write(response_data, address)
def dataReceived(self, data): """ 将收到的信息md5加密后,发送回client """ log_data = 'recv data is: %s' % data log.debug_info(log_data) # MD5加密收到的数据后发回给客户端 response_data = hashlib.md5(data).hexdigest().upper() self.transport.write(response_data)
def _send_tcp_package(self, dst_ip, dst_port, send_msg, status): """ 功能描述:发送tcp报文到TCP Server,并接收回应,验证链路是否通 参数: dst_ip: TCP报文的目的IP dst_port: TCP报文的目的port send_msg: TCP报文的消息内容 status: 链路状态,为1,表示链路正常,为2,表示端口被占用,为3表示connectTCP发生异常,负数表示失败的次数,为0表示链路不通 返回值: ATTTCPCLIENT_SUC, log_data 表示通 ATTTCPCLIENT_FAIL, log_data 表示不通 ATTTCPCLIENT_PORT_BUSY, log_data 表示端口被占用 """ # 检测端口是否被占用,如果源端口为0,表示不用指定源端口,则不用检测 if self.src_port == 0 or check_port_status(self.src_ip, self.src_port): # 设置发送的消息,如果send_msg是列表则直接赋值,如果不是列表,则将send_msg加入到TSClntProtocol.send_data列表中 if type(send_msg) == type([]): TSClntProtocol.send_data = send_msg else: TSClntProtocol.send_data.append(send_msg) try: # 判断是否需要绑定源端口 if self.src_port == 0: reactor.connectTCP(dst_ip, int(dst_port), TSClntFactory()) else: reactor.connectTCP(dst_ip, int(dst_port), TSClntFactory(), bindAddress=(self.src_ip, self.src_port)) reactor.run() except Exception, e: status.value = 3 log_data = "send tcp package ocurrs exception, error info is %s" % e log.debug_info(log_data) if TSClntProtocol.connection_status: fail_num = TSClntProtocol.connection_status.count(0) if fail_num == 0: # 没有失败的记录,发送报文全部成功 status.value = 1 else: # 有失败记录,返回失败的次数,用负数表示 status.value = -fail_num else: status.value = 0
def sendData(self): # 将send_data列表中的数据一个一个的发送出去,发送完后断开连接 if len(TSClntProtocol.send_data): TSClntProtocol.data = TSClntProtocol.send_data.pop(0) log_data = '...sending %s...' % TSClntProtocol.data log.debug_info(log_data) if isinstance(TSClntProtocol.data, unicode): TSClntProtocol.data = TSClntProtocol.data.encode("utf-8") self.transport.write(str(TSClntProtocol.data)) else: self.transport.loseConnection()
def _check_flag(self, flag): """ 检查服务器标识 flag.value=1,表示继续运行服务器, flag.value=0,表示需要关闭服务器 """ if flag.value == 0: reactor.stop() log_data = "UDPServer Stopped" log.debug_info(log_data) else: reactor.callLater(1, self._check_flag, flag)
def sendDatagram(self): # 将send_data列表中的数据一个一个的发送出去,发送完后退出reactor循环 if len(TSClntDatagramProtocol.send_data): TSClntDatagramProtocol.data = TSClntDatagramProtocol.send_data.pop( 0) log_data = '...sending %s...' % TSClntDatagramProtocol.data log.debug_info(log_data) if isinstance(TSClntDatagramProtocol.data, unicode): TSClntDatagramProtocol.data = TSClntDatagramProtocol.data.encode( "utf-8") self.transport.write(str(TSClntDatagramProtocol.data)) else: reactor.stop()
def datagramReceived(self, datagram, host): log_data = 'Datagram from %s received: %s ' % (host, repr(datagram)) log.debug_info(log_data) TSClntDatagramProtocol.recv_flag = 1 # 加密发送的数据,用于验证接收的数据是否正确 encoded_send_data = hashlib.md5( TSClntDatagramProtocol.data).hexdigest().upper() # 检测接收的数据是否正确,用于判断链路是否正常 if encoded_send_data == datagram: TSClntDatagramProtocol.connection_status.append(1) else: TSClntDatagramProtocol.connection_status.append(0) # 继续发送数据 self.sendDatagram()
def start_udp_server(self, ip, port, flag, error): """ 功能描述:开启UDP Server 参数: ip: UDP server所在主机IP地址 port: UDP Server监听的端口号 flag: 服务器运行标识 """ if check_port_status(ip, port, "UDP"): try: reactor.listenUDP(port, TSServDatagramProtocol(), interface=ip) reactor.callLater(1, self._check_flag, flag) reactor.run() except Exception,e: log_data = "ListenUDP occurs exception, error info is %s" % e log.debug_info(log_data) flag.value = 3 error.value = log_data
def stop_ping(self,pid): ''' 停止进程并返回丢包率,打印ping执行。 ''' lost_percent = None str_data = '' process_obj = self.dict_process_obj[pid] counter = 0 while counter < 20: content = getsize(process_obj.ping_tmp_file) if content > 0L: break else: counter += 1 time.sleep(1) try: if process_obj.is_alive: ret,data = attcommonfun.get_process_children(process_obj.pid) if ret == attcommonfun.ATTCOMMONFUN_SUCCEED: dict_process = data for process_pid, process_name in dict_process.items(): if process_name not in ["ATT.exe","robot.exe","cmd.exe"]: try: os.kill(process_pid, 9) except: pass try: os.kill(process_obj.pid, 9) except: pass time.sleep(0.5) else: pass except Exception,e: ret_data = u"停止ping进程发生异常: %s" % e log.debug_info(ret_data)
def _connect_ftp(self, host, port=21, username='', password='', timeout=20): """ 功能描述:连接并登录FTP服务器 参数: host: FTP服务器地址 port: FTP服务器监听端口,默认为21 username: 连接服务器的用户名,空表示匿名登录,一般服务器对匿名登录的用户有权限限制 password: 连接服务器的密码 timeout: 连接超时时长,单位为秒 返回: 成功返回:(ATTFTPCLENT_SUC,成功信息) 失败返回:(ATTFTPCLENT_FAIL,失败信息) """ #add by jias 20130808 if self.login: info = u"已经连接并登录FTP服务器" return ATTFTPCLENT_SUC, info try: # 创建对象,并连接服务器 self.ftp = ftplib.FTP() ret_info = self.ftp.connect(host, int(port), int(timeout)) log.debug_info(u"连接FTP服务器成功.详细信息为:%s" % ret_info) except Exception, e: ret_info = u"连接FTP服务器发生异常:%s" % e log.debug_err(ret_info) #add by jias 20130808 恢复conn前状态 if self.ftp: self.ftp.close() self.ftp = None return ATTFTPCLENT_FAIL, ret_info
""" if check_port_status(ip, port, "UDP"): try: reactor.listenUDP(port, TSServDatagramProtocol(), interface=ip) reactor.callLater(1, self._check_flag, flag) reactor.run() except Exception,e: log_data = "ListenUDP occurs exception, error info is %s" % e log.debug_info(log_data) flag.value = 3 error.value = log_data else: log_data = "The addr %s:%s have been used, choose another port please!" % (ip, str(port)) log.debug_info(log_data) flag.value = 2 def stop_udp_server(self, flag): """ 关闭UDPServer """ flag.value = 0 class ATTUDPServer(object): """ ATTUDPServer
def telnet_login(self, username, password, login_prompt='Login: '******'Password: '******''' output = self._submit_credentials(username, password, login_prompt, password_prompt, success_prompt) if self._prompt_is_set(): success, output2 = self._read_until_prompt() else: success, output2 = self._verify_login_without_prompt( login_timeout, login_incorrect) output += output2 self._log(output) if not success: raise AssertionError('Login incorrect') return output ''' self._verify_timeout(login_timeout) if float(login_timeout) <= float(self._timeout): raise Exception (u"成功登录时间小于或等于模块系统设置时间,请设置成功登录时间大于模块系统设置时间") tStart = time.time() sleep_time = 0.05 #cmd telnet 在3次登录失败的情况下 会退出连接 ,程序会么? #故要和输入的用户名和密码一起判断 newline_list = ['\n', '\r', '\r\n'] log_title = u"自动获取newline成功,适配到的是:%s ('LF','CR','CRLF'相当于'\\n','\\r','\\r\\n')" #add by jias 2013-11-11 #如果用户设置了, 则不再遍历 if self.newline_set_flg == True: newline_list = [self._newline] log_title = u"当前newline为:%s ('LF','CR','CRLF'相当于'\\n','\\r','\\r\\n')" index = 0 newline_setok = False isFirst = True istate = 0 #0表示没有提示,1表示用户名提示,2表示密码提示 while True: # 验证登录超时时间 lwb:2013-05-02 self._verify_login_timeout(tStart,login_timeout) if index >= len(newline_list): #一轮完成了 ,还不成功 说明输入错误 log_data = u"登录失败,请确认输入的用户名和密码是否正确。若有设置newline, 请确认newline是否正确。" raise Exception(log_data) cur_newline = newline_list[index] if (False == newline_setok): log_data = u"当前用%s作为newline登录"%cur_newline.replace('\n', 'LF').replace('\r', 'CR') log.user_info(log_data) if (not isFirst) and (istate != 1): telnetlib.Telnet.write(self, self._encode(cur_newline)) log_data = u"再按一次" log.debug_info(log_data) output = "" read = "" #找login_prompt for i in range(3): #担心有延时读两次 self._verify_login_timeout(tStart,login_timeout) # 找到用户名提示符,并输入用户名 lwb:2013-05-02 read = self.telnet_read() if len(read.strip()) <= 0: #没有数据 continue output += read if login_prompt.strip() == (output.splitlines()[-1]).strip(): #找到输入name提示 istate = 1 break elif password_prompt.strip() == (output.splitlines()[-1]).strip(): #找到输入pass提示 istate = 2 break else: istate = 0 if (isFirst): if (1 != istate ): log_data = u"没有找到%s提示符,请确认输入是否正确"%login_prompt raise Exception(log_data) isFirst = False else: if (istate == 1): if (not newline_setok): self._newline = cur_newline newline_setok = True log_data = log_title % cur_newline.replace('\n', 'LF').replace('\r', 'CR') log.user_info(log_data) #下面 输入用户名和密码 elif (istate == 2): if (not newline_setok): self._newline = cur_newline newline_setok = True log_data = log_title % cur_newline.replace('\n', 'LF').replace('\r', 'CR') log.debug_info(log_data) continue #回到 while(True) else: istate = 0 #test log_data = u"没有用户名提示, 也没有密码输入提示" log.debug_info(log_data) index += 1 #遍历下一个newline continue #回到 while(True) #对登录用户名进行一个字符一个字符的写入 list_username = list(username) for i in range(len(list_username)): telnetlib.Telnet.write(self, self._encode(list_username[i])) time.sleep(sleep_time) try: telnetlib.Telnet.write(self, self._encode(cur_newline)) except Exception: log_data = u"写newline%s错误"%cur_newline.replace('\n', 'LF').replace('\r', 'CR') raise Exception(log_data) """ # 找密码提示符 find_password = False for j in range(3): self._verify_login_timeout(tStart,login_timeout) read = self.telnet_read() if len(read.strip()) <= 0: #没有数据 time.sleep(sleep_time) continue output += read if password_prompt.strip() == (output.splitlines()[-1]).strip(): find_password = True break else: time.sleep(sleep_time) continue if (find_password): #得到password提示认为new正确 #self._newline = cur_newline #test loginfo = u"找到newline %s"% cur_newline.replace('\n', 'LF').replace('\r', 'CR') log.user_info(loginfo) else: #没找到 #下一个newline pass """ time.sleep(1) #对登录密码进行一个字符一个字符的写入 list_password = list(password) for i in range(len(list_password)): telnetlib.Telnet.write(self, self._encode(list_password[i])) time.sleep(sleep_time) try: telnetlib.Telnet.write(self, self._encode(cur_newline)) except Exception: log_data = u"写newline%s错误"%cur_newline.replace('\n', 'LF').replace('\r', 'CR') raise Exception(log_data) #找成功登录提示符 for i in range(3): self._verify_login_timeout(tStart, login_timeout) read = self.telnet_read() log_data = u"read onece:%s"%read log.debug_info(log_data) if len(read.strip()) <= 0: #没有数据 continue output += read if success_prompt.strip() == (output.splitlines()[-1]).strip(): self._newline = cur_newline newline_setok = True log_data = log_title % cur_newline.replace('\n', 'LF').replace('\r', 'CR') log.user_info(log_data) log_data = u"用户登录成功" log.user_info(log_data) return output elif login_prompt.strip() == (output.splitlines()[-1]).strip(): istate = 1 #两次输入newline 又回到用户名提示 #表示换行正确,用户名和密码错误 self._newline = cur_newline newline_setok = True log_data = log_title % cur_newline.replace('\n', 'LF').replace('\r', 'CR') log.user_info(log_data) log_data = u"请检查用户名和密码是否正确" log.debug_info(log_data)#todo raise 太多尝试会报 FAIL : EOFError: telnet connection closed break elif password_prompt.strip() == (output.splitlines()[-1]).strip(): istate = 2 log_data = u"读取到的最后一行是: %s" % output.splitlines()[-1] log.debug_info(log_data) #break #err 输入密码(密码不显示)还没有得到成功提示符时(延时),最后一行是password_prompt continue else: istate = 3 if (False == newline_setok): #按两次没有用户名提示, 也没有登录成功,newline错误 ,下一个 #test log_data = u"按两次没有用户名提示, 也没有登录成功" log.debug_info(log_data) index += 1 #遍历下一个newline return output