Python如何从字符串中提取uptime命令输出的指定字段
从shell输出中提取uptime字段的实现方法
你不需要把整个原始输出转为字典——原始输出混杂了文件列表、命令提示符、执行时间提示等无关内容,本身不是标准的序列化字典格式,直接转换必然失败。针对固定格式的命令输出,用分段截取+键值对匹配的方式提取即可,步骤如下:
- 先将捕获到的bytes类型返回值解码为普通字符串
- 定位到uptime命令对应的输出块,过滤无关内容
- 逐行拆分冒号分隔的键值对,存入结构化字典
可直接运行的代码示例
import re # raw_output 替换为你实际捕获到的shell返回bytes值 raw_output = b""" adjDisc/, adjprov/, ains/, alarm/, alatypes/, almBase/, ALPL/, alrmst, ALSO/, applblki/, aTrace/, BackPlane/, baseUtils/, brownout/, bwm/, cac/, cdb/, chkpt/, CLAF/, clustering/, cmnfpga/, comms/, config/, configFile/, control/, cpl, cplutils/, create_file, csclient/, dasm_cfm/, datasync/, dbalrms/, dbman/, dbrst/, ddf/, decommission/, diag/, difReasons, doc/, dov/, ds1tm/, dsbl/, edf, ehf/, epl/, EqptAttr/, eqptgrp/, eqpt_mode/, eqpt_stats/, eslots/, fhgraph/, filesync/, flashBurn/, flightrec/, fpo/, fsm/, ftp/, ftpClient/, gzip/, hal/, hdsmlinkdata/, heapStats, httpc/, i2c/, imon/, ins/, intDiag/, intrrpts/, ipc/, ipm/, irq1/, irq2/, IRQ6/, isc/, l2Services/, leds/, loadinfo/, loadMgmt/, logs/, lua/, manufacturing/, memStats, misconnection/, mmon/, mofshadow/, nbi_common_utils/, necht/, niapp/, nlc/, nncli/, oamfac/, obm/, observer/, opmCtrl/, opmCtrlFlex/, OSRP/, otdr/, owireci/, passive_slots/, pathopt/, pbe/, pdns/, PhotonicNBI/, photonicsNVSRecovery/, photonic_ots/, photop/, plog/, PM/, pm/, pmbase/, pmp/, pods/, powerAudit/, pramUtil/, ras/, RASDBGI, rdbg, rmcemon/, round_trip_delay/, rpr/, rtrvlog/, sbf/, scmpml/, secure_erase_cmn/, setpriv, shelfinfo/, shelfSync/, slc/, slotseq/, snmp/, SNMPTranslator/, socKernel/, socLa/, SONMP/, sorn/, sov/, spfpga/, spsid_dump, SpSwSubFailReason, spsync/, sptools/, svrest/, sync/, tar/, targetshell/, tcsdebug/, tdrf/, tdrfShow, teas/, telnet/, tidci/, tl1ci/, TL1EvtSeq/, tl1_to_avp/, tod/, top/, tpUtl/, tr/, trace/, tracepoints/, TRCntrl/, ts1forn/, tsam/, tsbase/, tsds3ec1/, tsemotr/, tsexer/, tsfpo/, tsl2/, tsmdd_qry/, tsm_prov/, tsm_sbf/, tsngm/, tsocn/, tsotnsw/, tsplug/, tsprot/, tsprsta/, tssmux/, tsstm1ee4/, tsxc_sbf/, ts_allocation/, ud2_fwd/, udp_fwd/, upgrade/, uptime, vbus/, vfs/, vfs_signal_debug/, vkgcct/, vkgfan/, vkginv/, vkgio/, vkgpwr/, vk_i2c_acc/, vneProxy/, vosa/, *=quit TID="Sub_6500_3":Shelf=1 Slot15-docInst: unset, ome_sp2_vx_appl: OME1280.BP Command completed at TUE JUN 07, 2022 - 04:58:42 (UTC) ----> ~ uptime Last restart occurred at: FRI MAY 27, 2022 at 07:42:31 (UTC) Time since restart: 10 days 21 hrs 16 mins 13 secs Actual Cumulative uptime: 489 days 7 hrs 30 mins Logged Cumulative uptime: 488 days 11 hrs 54 mins Actual Continuous uptime: 118 days 15 hrs 47 mins Command completed at TUE JUN 07, 2022 - 04:58:44 (UTC) ----> """ # 解码bytes为字符串 output_text = raw_output.decode("utf-8").strip() # 正则截取uptime命令的有效输出区间 uptime_segment = re.search( r"----> ~ uptime\s*(.*?)\s*Command completed at", output_text, re.S ).group(1) # 逐行提取键值对 uptime_data = {} for line in uptime_segment.splitlines(): line = line.strip() if not line: continue # 按第一个冒号拆分键和值,避免值内容里的冒号导致拆分错误 key, val = line.split(":", 1) uptime_data[key.strip()] = val.strip()
提取结果说明
执行代码后得到的uptime_data字典会包含所有目标字段:
- Last restart occurred at:设备上次重启时间,示例值为
FRI MAY 27, 2022 at 07:42:31 (UTC) - Time since restart:上次重启到当前的运行时长,示例值为
10 days 21 hrs 16 mins 13 secs - Actual Cumulative uptime:设备实际累计运行时长,示例值为
489 days 7 hrs 30 mins - Logged Cumulative uptime:系统记录的累计运行时长,示例值为
488 days 11 hrs 54 mins - Actual Continuous uptime:设备实际连续运行时长,示例值为
118 days 15 hrs 47 mins
如果后续设备输出格式有微调,只需要修改正则匹配的区间规则即可,不需要改动核心的键值对提取逻辑。
内容的提问来源于stack exchange,提问作者HSHEKHAR
相关产品推荐
相关产品推荐

