从本地ping终端设备

在不同的平台如windows和ubuntu下ping返回的结果是不同的,包括操作系统语言不同,返回结果也不同,可根据实际情况添加条件
if "丢失 = 0" in output or "0% packet loss" in output or "0% loss" in output or "0% 包丢失" in output:

  

    # 检查通信是否正常
    def Ping(self, host, timeout=60):
        try:
            self.logger.info('【{}】检查{}通信是否正常...'.format(self.orin_type, host))
            start = time.time()
            cmd = f"ping {host}"
            if sys.platform == "win32":
                self.logger.info('【{}】运行环境为{}'.format(self.orin_type, sys.platform))
            elif sys.platform == "linux":
                cmd = f"ping -c 3 {host}"
                self.logger.info('【{}】运行环境为{}'.format(self.orin_type, sys.platform))
            while True:
                current = time.time()
                if current - start > timeout:
                    self.logger.error('【{}】{}与本地网络连接失败。'.format(self.orin_type, host))
                    return False
                output = subprocess.getoutput(cmd)
                print('    %s' % output)
                if "丢失 = 0" in output or "0% packet loss" in output or "0% loss" in output or "0% 包丢失" in output:
                    self.logger.info('【{}】{}通信正常'.format(self.orin_type, host))
                    return True
                else:
                    continue
        except Exception:
            print(traceback.format_exc())
            self.logger.error(traceback.format_exc())
            return False

 

posted @ 2022-08-02 10:36  小柴i  阅读(43)  评论(0编辑  收藏  举报