Difference between Http and Https?
What difference between HA active/active and HA active/passive
HA act/act, separate connection table, sync connection for TCP sync/ack, can be happened on either active node
HA act/pas, unique connection table, but sync over failover link, one failed, another one can quickly pick up
How to isolate or action on malicious patching/downloading
https inspection, send to antivirus, anti-bot, sandbox before to user.
What is https inspection on the firewall
Generate ssl cert at the firewall, act as man-in-the-middle between user and server, user -> FW(443), FW inspection > FW -> Server(443)
What is Health Checker option on the F5
What is OSPF area, why need area?
reduce LSU/LSA ; Routing table optimization;
What is spanning-tree protocol
L2 loop prevent in a broadcast domain; such as broadcast storm, broad received on a switch interface will flood to all interfaces except the reciving one, if the topology is not loop-free, there is likely to have loop all broadcast packets.
What tables can be read from switch, what is CEF?
mac-address table (mac-interface mapping)
arp-table (mac-ip mapping)
cef talbe (stored RIB for quicker fwd)
routing table (routes-nexthop mapping)
How is Traceroute work?
What is the wireless LAN controller?
What do you think of whitebox switch?
What is voice traffic to be treated in QoS, and why.
EF class map
priority queue
What is NBAR
Network Based Application Recognition (NBAR) is a mechanism that classifies and regulates bandwidth for network applications to ensure that available resources are utilized as efficiently as possible
# connection vs connectionless
What are TCP Flags?
TCP flags are used within TCP packet transfers to indicate a particular connection state or provide additional information. Therefore, they can be used for troubleshooting purposes or to control how a particular connection is handled. There are a few TCP flags that are much more commonly used than others as such “SYN”, “ACK”, and “FIN”. However, in this post, we’re going to go through the full list of TCP flags and outline what each one is used for.
List of TCP Flags
Each TCP flag corresponds to 1 bit in size. The list below describes each flag in greater detail. Additionally, check out the corresponding RFC section attributed to certain flags for a more comprehensive explanation.
SYN - The SYN, or Synchronisation flag, is used as a first step in establishing a 3-way handshake between two hosts. Only the first packet from both the sender and receiver should have this flag set. The following diagram illustrates a 3-way handshake process.
ACK - The ACK flag, which stands for “Acknowledgment”, is used to acknowledge the successful receipt of a packet. As we can see from the diagram above, the receiver sends an ACK as well as a SYN in the second step of the 3-way handshake process to tell the sender that it received its initial packet.
FIN - The FIN flag, which stands for “Finished”, means there is no more data from the sender. Therefore, it is used in the last packet sent from the sender.
URG - The URG flag is used to notify the receiver to process the urgent packets before processing all other packets. The receiver will be notified when all known urgent data has been received. See RFC 6093 for more details.
PSH - The PSH flag, which stands for “Push”, is somewhat similar to the URG flag and tells the receiver to process these packets as they are received instead of buffering them.
RST - The RST flag, which stands for “Reset”, gets sent from the receiver to the sender when a packet is sent to a particular host that was not expecting it.
ECE - This flag is responsible for indicating if the TCP peer is ECN capable. See RFC 3168 for more details.
CWR - The CWR flag, which stands for Congestion Window Reduced, is used by the sending host to indicate it received a packet with the ECE flag set. See RFC 3168 for more details.
NS (experimental) - The NS flag, which stands for Nonce Sum, is still an experimental flag used to help protect against accidental malicious concealment of packets from the sender. See RFC 3540for more details.
Analyzing TCP Flags in the CLI
You can view which TCP flags are being used for every TCP packet directly from within your command line interface. To do so, you need to run a tcpdump. This needs to be done by a root user so if you don’t have root access, try running the following:
sudo tcpdump
This will allow you to analyze all packets being sent and will display packets containing any of the TCP flags. However, if you would like to run a tcpdump only on packets containing a certain flag you can use one of the following commands.
ACK sudo tcpdump 'tcp[13] & 16 != 0'
SYN sudo tcpdump 'tcp[13] & 2 != 0'
FIN sudo tcpdump 'tcp[13] & 1 != 0'
URG sudo tcpdump 'tcp[13] & 32 != 0'
PSH sudo tcpdump 'tcp[13] & 8 != 0'
RST sudo tcpdump 'tcp[13] & 4 != 0'
Summary
Knowing your TCP flags can be quite useful for troubleshooting purposes. If you need to quickly analyze your TCP packets, it’s easy to run a tcpdump command for a particular flag and then retrieve the results you require. Be sure to check out the RFC section of any of the corresponding TCP flags above to go into even greater detail of what each one is used for and how it works.
IP Header
Traceroute 原理
假设你想探测从你的电脑到目标服务器经过了哪些节点:
第一步 (TTL = 1): 你的电脑发送一个 TTL 为 1 的数据包。它到达第一个路由器后,TTL 减 1 变成 0。路由器丢弃该包,并给你发回一个“超时”通知。这样你就知道了第一个路由器的地址。
第二步 (TTL = 2): 你的电脑发送一个 TTL 为 2 的数据包。它顺利通过第一个路由器(TTL 变 1),到达第二个路由器时 TTL 变 0。第二个路由器发回“超时”通知。你拿到了第二个路由器的地址。
循环往复: 电脑不断递增 TTL(3, 4, 5...),像剥洋葱一样,一层层探测出路径上所有的路由器。
到达终点: 当数据包最终到达目标服务器时,服务器发现自己就是目的地,不再转发,因此不会回传“超时”消息,而是根据协议回传一个 “目标达成” 的响应(如 ICMP Echo Reply)。
当你运行命令时,每一行通常显示 3 个时间(例如 15ms 14ms 16ms):
这是因为 Traceroute 对每个节点都会发送 3 个探测包,以确保数据的准确性并观察网络波动。
星号 (* * *): 表示该节点请求超时。这不一定代表网络断了,通常是因为该路由器配置了“不响应探测”以保护隐私或减轻负载。
延迟跳跃: 如果第 4 跳是 20ms,第 5 跳突然变成 200ms,说明瓶颈就在这两个节点之间。
ip ping within same broadcast domain, but with different subnet mask config
设备判断对方位置行为掩码较长(子网小)的一方认为对方是“远程/外网”寻找网关,不发本地 ARP掩码较短(子网大)的一方认为对方是“本地/内网”直接发送 ARP 请求 MAC
How arp reachability work
ARP 的工作机制是一个典型的 “广播请求,单播响应” 过程。
第一步:查找 ARP 缓存 (Check Cache)
第二步:发送 ARP 请求 (The Broadcast Request)
第三步:目标响应 (The Unicast ARP Reply)
第四步:更新与传输 (Update CAM table and Send)
PMTUD 如何工作
PMTUD 发生在三次握手之后的实际数据传输过程中。三次握手期间数据传输期间(动态)覆盖范围仅协商两端终端的能力 MSS (max seg size)
2. 动态调整时机:收到 ICMP DF need 反馈后调小路径 MTU 3. 定期尝试恢复 (PMTU Aging)
在现代互联网环境中,很多防火墙为了安全会丢弃所有的 ICMP 包。
现象: 源端收不到 Fragmentation Needed 消息,于是它会不断重传那个大包,而路由器继续静默丢弃。
后果: 这就是著名的 “黑洞路由” (PMTUD Blackhole)。你的 TCP 三次握手(小包)能通,但一旦传输大块数据(如登录后的页面加载),连接就会卡死。
解决方法: 这就是为什么在之前的讨论中,我建议你在防火墙或 Prisma Access 上配置 MSS Clamping (MSS 钳制)。它在 TCP 协商阶段直接把 MSS 改小,从而从源头上避免产生需要 PMTUD 介入的大包。
IGP vs BGP 区别, IGP vs BGP 优缺点, IGP vs BGP on convergence time
IGP 建立基础: 内部路由器通过 OSPF 互相认识,确保内部 IP 互通(Next-hop 可达)。
iBGP 传递信息: 内部路由器之间运行 iBGP,同步外部互联网的路由。
eBGP 对外连接: 边界路由器通过 eBGP 与运营商(ISP)交换路由信息。
收敛这么慢是 BGP 刻意的设计,而非缺陷:
稳定性高于一切: 互联网非常庞大,如果某根海底光纤每秒闪断一次,BGP 若实时同步,全球路由器的 CPU 都会因为计算路由而崩溃。因此 BGP 使用了 Route Flap Damping(路由震荡抑制)。
邻居关系: IGP 像是在对讲机里广播,所有人瞬间听到;BGP 像是在发传真,需要建立连接、排队发送、对方确认。
latency between US and EU, how to troubleshoot
1. 使用 MTR (My Traceroute) —— 观察点: 留意延迟在哪一跳发生了阶跃式增长
2. 区分“网络延迟”与“协议延迟”,如果 Ping 只有 70ms,但网页加载要 500ms,问题可能出在 TCP 三次握手 或 TLS 握手 多次往返导致的累积延迟。
3. 检查 BGP 路由绕路 (Routing Asymmetry)
开启 BBR: 正如我们之前讨论的,在长距离、高延迟链路上开启 BBR 拥塞控制算法 能极大地提升带宽利用率。
ISIS 路由是什么
相比于 OSPF,IS-IS 在电信级网络中具有显著优势:
更好的扩展性: IS-IS 处理路由条目的能力比 OSPF 更强,能承载更庞大的网络拓扑。
安全性与纯净: IS-IS 直接运行在**数据链路层(L2)**之上(使用特定的 MAC 地址),不依赖 IP 协议。这意味着它不容易受到 IP 层的黑客攻击(如针对端口的攻击)。
支持多协议 (TLV 架构): IS-IS 使用 TLV (Type-Length-Value) 三元组来携带数据。如果想让它支持 IPv6,只需要增加一种新的 TLV,而不需要像 OSPF 那样彻底重写协议(从 OSPFv2 到 OSPFv3)。
收敛极快: 虽然 OSPF 已经很快了,但在超大型拓扑中,IS-IS 的 SPF 算法优化(如 Partial SPF)效率更高。
BGP route selection and control example
当 BGP 路由器从不同的邻居收到多条通往同一个目的地的路由时,它会按顺序对比以下属性,一旦比出胜负,后面的规则就不再看:
Weight (权重): 仅限本地路由器生效(思科私有)。越高越优。
Local Preference (本地优先级): 在整个 AS 内部传播。越高越优。
Origin (起源): 优选本地生成的路由(Next Hop 为 0.0.0.0)。
AS_Path (路径长度): 经过的 AS 数量越少越优。
Origin Type: IGP > EGP > Incomplete。
MED (多出口鉴别器): 告诉邻居 AS 应该从哪个入口进来。越低越优。
Neighbor Type: eBGP(外部) 优于 iBGP(内部)。 ...(后续还有 6 条用于打破平局,如最小 Router ID 等)。
场景 1:控制“出向流量”(我想走哪家)
需求: 你希望访问国外学术资源时,优先走联通,因为联通的国际出口通常更顺畅。
控制手段:Local Preference (LP)
操作: 1. 在与联通建立的 BGP 会话中,将入方向的所有路由 LP 设为 200。 2. 在与电信建立的 BGP 会话中,LP 保持默认值 100。
结果: 整个公司内部的所有路由器都会因为 LP=200 而优先把包发给联通。
场景 2:控制“入向流量”(让别人走哪家)
需求: 电信的带宽很大且便宜,你希望外部用户访问你公司的服务器时,优先从电信进来。
控制手段:AS_Path Prepending (路径堆叠)
操作:
当你向联通通告你的网段时,故意在路径里多写几次自己的 AS 号(例如:65001 65001 65001)。
当你向电信通告时,保持原始状态(65001)。
结果: 互联网上的其他用户在看路由表时,会发现“走联通要经过 3 个 AS,走电信只要 1 个”,从而优先从电信进入你的网络。
场景 3:
Inbound (进阶)MED告诉隔壁邻居(同一运营商),从我哪个接口进来。
在上海链路发送路由,设置 MED = 10。
在北京链路发送路由,设置 MED = 100。
意图: 10 < 100,所以请走上海。
在处理跨境网络(如 Prisma Access)时,直接修改属性可能被运营商忽略。这时会用到 Community tag。
原理: 这是一个打在路由条目上的“标签”。
例子: 你可以给路由打上一个标签 65001:666。运营商收到后,根据事先约定好的规则(Policy),看到这个标签就自动把该路由的优先级调低。这在管理全球复杂的公网流量时非常高效。
非抢占性: BGP 属性修改后,路由表不会瞬间切换,需要等到 TCP 会话触发更新。
RR and Conferderance 优缺点
RR 核心思想: 指定一个路由器为“反射器”,打破 iBGP 不转发路由的限制。它像一个中心分发点。(配置极其简单, 扩展性好, multi RR) (-cpu cost, single rr failue)
confederation 核心思想: 将一个大的 AS 拆分成多个小的“私有 AS”(Sub-AS)。对外看起来是一个 AS,内部则是 eBGP 关系的连接. (配置非常复杂, hard migration)
QoS config setting
一套完整的 QoS 配置通常遵循 “识别 -> 标记 -> 策略 -> 应用” 的流程(即典型的 MQC 架构:Modular QoS CLI)。
第一步:分类与识别 (Classification)
首先,你得告诉路由器哪些流量是“重要”的。
方法: 通过 ACL 匹配 IP 地址,或者通过 NBAR 识别协议(如 Zoom, Webex)。
例子: 匹配所有 VoIP 语音流量。
第二步:标记 (Marking/Coloring)
在数据包的 IP 头部打上标签,方便后续节点识别。
二层标记 (CoS): 位于 802.1Q 头部(取值 0-7)。
三层标记 (DSCP): 位于 IP 头部(更常用,取值 0-63)。
EF (Expedited Forwarding): 语音专用,最高优先级。
AF (Assured Forwarding): 关键业务数据(如 ERP, 数据库)。
CS (Class Selector): 兼容老旧设备。
第三步:策略与队列管理 (Policing, Shaping & Queuing)
这是 QoS 的具体执行阶段。
流量监管 (Policing): 超过带宽就直接丢包(适合限制下载)。
流量整形 (Shaping): 超过带宽先缓存,慢慢发(适合平滑突发流量)。
排队调度 (Queuing): * PQ (Priority Queuing): 绝对优先,语音包不走完,别的包不能动。
CBWFQ / LLQ: 现代网络主流,给不同等级的业务分配最小保证带宽。
第四步:应用 (Application)
将配置好的策略挂载到具体的接口(Interface)上。
假设你要保证公司的 VoIP 语音 优先,并限制 普通上网流量:
Plaintext
! 1. 定义分类
class-map match-any VOICE_CLASS
match protocol rtp audio # 识别语音
! 2. 定义策略
policy-map QOS_OUTBOUND
class VOICE_CLASS
priority percent 30 # 开启 LLQ,保证 30% 带宽,延迟极低
class class-default
fair-queue # 剩下的流量公平排队
! 3. 应用到出口网关
interface GigabitEthernet0/1
service-policy output QOS_OUTBOUND
业务类型
建议标记 (DSCP)
VoIP 语音
EF (46)
Priority Queue (PQ)
对延迟和抖动极度敏感。
视频会议
AF41 (34)
CBWFQ + 预留带宽
吞吐量大,允许少量延迟。
关键业务 (ERP)
AF21 (18)
保证最小带宽
不能断开,但延迟要求一般。
普通上网
Default (0)
Best Effort
有剩余带宽才给用。
Trust Boundary (信任边界): 接入交换机必须配置 mls qos trust dscp,否则它可能会把包头里的标记直接擦除(重置为 0)。
入站 vs 出站: 绝大多数 QoS 策略应用在 Outbound (出站) 方向。因为你无法控制别人怎么发包给你,你只能控制自己怎么发包出去。
硬件队列瓶颈: 如果物理接口真的满了,QoS 只能改善延迟,不能“变出”更多带宽。
如果你是在配置 Prisma Access 或 SD-WAN 链路:
端到端一致性: 确保标记从内网交换机一直保留到 VPN 隧道内部。
MSS Clamping 与 MTU: 在配置 QoS 的同时,务必检查 MTU,因为分片会导致 QoS 识别失效。
在一个复杂的网络中,数据包会经过交换机(二层)和路由器(三层)。
二层交换机(效率优先): 传统的二层交换机为了实现极速转发,其芯片(ASIC)通常只扫描到数据帧的二层头部(802.1Q)。如果只用 DSCP,交换机就必须深入剥开 IP 报头去读取信息,这会消耗更多的计算资源。CoS (Class of Service) 就像是贴在信封表面的“加急”贴纸,让交换机看一眼就决定走哪个快速通道。
三层路由器(跨网段优先): 当数据包跨越路由器进入另一个网络时,二层的 802.1Q 头部(包含 CoS)会被彻底剥离并丢弃。如果没有三层的 DSCP,QoS 标记在经过第一台路由器后就丢失了。DSCP 是写在 IP 报头里的,无论经过多少跳,只要路由器不主动修改它,标记就会一直存在。
二层 CoS (802.1p): 它位于 VLAN Tag(802.1Q)中的 PRI 字段。只有在 Trunk 链路(或者带 Tag 的接入链路)上,这个字段才存在。
三层 DSCP: 它位于 IPv4 头的 ToS (Type of Service) 字段或 IPv6 头的 Traffic Class 字段。它是 IP 协议的一部分,不依赖于物理链路类型。
在企业级网络配置中,它们通常是协同工作的,这被称为 QoS 映射 (Mapping):
进入端(Ingress): 你的 IP 电话发出一个语音包,打上了 DSCP EF (46) 标记。
交换机处理: 接入交换机收到后,根据内部映射表,自动在二层 VLAN 头部打上 CoS 5。这样,包在通过交换机之间的 Trunk 链路时,就能享受高优先级队列。
路由器处理: 包到达路由器,VLAN 头部被拆掉,准备发往 VPN 隧道。路由器看到 DSCP 46,于是决定将其放入隧道的 LLQ(低延迟队列)。
云端/对端(Egress): 远端设备根据残留的 DSCP 标记,重新在本地二层打上 CoS,确保最后一公里的优先级。
RSVP TE working theory
RSVP-TE (Resource Reservation Protocol - Traffic Engineering) 是 MPLS 网络中的核心控制协议。它的存在是为了解决传统路由协议(如 OSPF/IS-IS)只能计算“最短路径”而无法感知“链路带宽”的缺陷。
简单来说,RSVP-TE 的工作就是在 MPLS 网络中预定出一条满足特定约束条件(如带宽、延迟、特定路径)的标签交换路径(LSP)。
RSVP-TE 的运行可以分为:计算路径 -> 发起请求 -> 建立预留。
第一步:路径计算 (CSPF)
在建立路径前,头节点(Ingress LSR)使用 CSPF (Constraint-based SPF)。
传统 SPF: 只看 Cost 值,选最短的路。
CSPF: 除了 Cost,还要看链路剩余带宽、管理组(颜色)、跳数限制等。
结果: 生成一条明确的路径列表(ERO,Explicit Route Object)。
第二步:向下游发送 PATH 消息
头节点发出一个 PATH 消息,顺着计算出的路径向目的地进发。
内容: 包含所需的带宽需求(Label Request)和路径列表(ERO)。
动作: 每一跳路由器收到后,先检查自己是否有足够的带宽。如果有,就继续传给下一跳。
第三步:向上游发送 RESV 消息
当 PATH 消息到达目的地(Egress LSR)后,目的地会回传一个 RESV 消息。
分配标签: 它是从下游往上游分发标签的。
资源预留: 每一跳路由器收到 RESV 消息后,正式在接口上锁定(预留)带宽,并把标签交给上游邻居。
完成: 当头节点收到 RESV 消息,这条 TE 隧道 (LSP) 就正式建立通了。
为了实现复杂的流量工程,RSVP 消息里封装了三个关键对象:
ERO (Explicit Route Object): 显式路由对象。它规定了路径必须经过哪些点,类似于“GPS 导航路线图”。
Label Request / Label Object: 用于分发 MPLS 标签,确保数据层能通过标签转发。
Session Attribute: 包含隧道的优先级(Setup/Holding Priority)。这决定了当带宽不足时,重要的隧道是否可以“抢占”普通隧道的带宽。
A. 快速重路由 (FRR - Fast Reroute)
这是 RSVP-TE 最强大的地方。当物理链路突然断开时,路由器不需要等待协议重新收敛,而是直接切换到预先建立好的备份隧道(Bypass Tunnel)。
收敛时间: 通常小于 50ms。
B. 带宽保证与准入控制
它可以确保高优先级的业务(如 5G 切片、语音干线)始终有独占的带宽。如果链路带宽满了,新的低优先级请求会被直接拒绝(Admission Control),而不是大家一起卡顿。
Top
PS
free -h
memory
diff
Linux Find Out Which Process Is Listening Upon a Port
netstat command
Kubernetes
kubectl exec -n rancid-dev -it rancid-citadel-29426100-2g2rj -- /bin/bash
kubectl exec -n enterprise-network-mcp-dev -it enterprise-network-mcp -- /bin/bash
what is the difference between python2 and python3 on divide algorith
3/2 = ?
python3 = 1.4
python2 = 1
========================
a = '1'
b = '3'
int(a)+int(b)
========================
vowels('cradle')
['a','e']
c= ["'a"',"'e'",'"i"',"'o","'u"]
d= []
def vowels(a):
b = [x for x in a]
for i in b:
if i in c:
d.append(i)
vowels("ireland")
========================
simple just count how many vowels in the word.
import re
def count_vowels(str):
return len(re.findall(("a|e|i|o|u"), str, re.IGNORECASE))
print (count_vowels( "foobar" )) # 3
print (count_vowels( "gym" )) # 0
print (count_vowels( "ireland" )) # 3
========================
Given raw text, find which words within the text that contain each vowel and return it as an object
# and y this time
vowels = ['a','e','i','o','u','y']
text = "You may be sitting quietly in your armchair, but you are far from motionless. I don't mean merely that your heart is beating, your blood is coursing through your veins and you are panting at the prospect of learning so many fascinating things from this book. In short, I don't mean simply that you are physically and mentally alive."
response = {
'a':['apple','april'],
'e':['apple','red'],
'i':['it','kit'],
etc
}
# note: a word can exist under multiple keys.
# if poss
vowels = ['a','e','i','o','u','y']
text = "You may be sitting quietly in your armchair, but you are far from motionless. I don't mean merely that your heart is beating, your blood is coursing through your veins and you are panting at the prospect of learning so many fascinating things from this book. In short, I don't mean simply that you are physically and mentally alive."
========================
text = 'You mat be, i call matt be two'
wordlist = text.lower().split()
c= [ list(x) for x in wordlist ]
for i in c:
if ',' in i:
i.remove(',')
new_wordlist = ["".join(x) for x in c]
response = {}
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
#response = response.fromkeys(vowels,[])
response = {'a': [], 'e': [], 'i': [], 'o': [], 'u': [], 'y': []}
print (wordlist)
print (response)
#
print ( )
def res(w,v):
wordlist=w
vowels=v
for i in wordlist:
for j in vowels:
if j in i:
#print(i, j, response[j])
response[j].append(i)
response[j]=list(set(response[j]))
return response
import json
print (json.dumps(res(new_wordlist,vowels), indent=4))
========================
Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example:
Given the following matrix:
[
[ 1 , 2 , 3 ],
[ 4 , 5 , 6 ],
[ 7 , 8 , 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
class Solution:
# @param matrix, a list of lists of integers
# @return a list of integers
def spiralOrder(self, matrix):
result = []
if matrix == []:
return result
left = 0
right = len(matrix[0]) - 1
top = 0
bottom = len(matrix) - 1
# (left, right, top, bottom) = 定义 左,右,上,下, 然后按逻辑推
while left <= right and top <= bottom:
print left, right, top, bottom
for j in xrange(left, right + 1):
result.append(matrix[top][j])
print left, right, top, bottom
for i in xrange(top + 1, bottom):
result.append(matrix[i][right])
print left, right, top, bottom
for j in reversed(xrange(left, right + 1)):
if top < bottom:
result.append(matrix[bottom][j])
print left, right, top, bottom
for i in reversed(xrange(top + 1, bottom)):
if left < right:
result.append(matrix[i][left])
print left, right, top, bottom
left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
print left, right, top, bottom
return result
==================
Phone Screen#
requirement:
devices = ['ssw-001.alt1', 'fsw-001.alt1', "esw-003.dub1", "sww-002.alt1", "fsw-003.alt1", "esw-002.dub1"]
output:
alt1{
ssw[
sww-001.alt1,
sww-002.alt1
]
fsw[
fsw-001.alt1,
fsw-003.alt1
]
}
dub1{
esw[
esw-003.dub1
]
sww[
sww-002.dub1
]
ANS######################
import json
mydict={}
for dev in devices:
location = dev[-4:]
type = dev[0:3]
if location not in mydict: # 检测location是否存在于现有 字典
mydict[location]= {} # 创建新的key as location 并定义为 空dictionary
if type not in mydict[location]:
mydict[location][type]=[] # 创建新的key as type, 并定义为 空list
mydict[location][type].append(dev)
检测输出1:
print (json.dumps(mydict, indent=4))
>>>x
{
"alt1": {
"sww": [
"sww_001.alt1",
"sww-002.alt1"
]
},
"alt2": {
"fsw": [
"fsw_001.alt2"
]
},
"dub1": {
"esw": [
"esw-003.dub1",
"esw-002.dub1"
]
},
"alt3": {
"fsw": [
"fsw-003.alt3"
]
}
}
>>> x["dub1"]
{'esw': ['esw-003.dub1', 'esw-002.dub1']}
>>> x["dub1"]["esw"]
['esw-003.dub1', 'esw-002.dub1']
>>> x["dub1"]["esw"][1]
'esw-002.dub1'
检测输出2:
for x in mydict:
print (x)
for y in mydict[x]:
print (y,':',mydict[x][y])
alt1
sww : ['sww_001.alt1', 'sww-002.alt1']
alt2
fsw : ['fsw_001.alt2']
dub1
esw : ['esw-003.dub1', 'esw-002.dub1']
alt3
fsw : ['fsw-003.alt3']