将tshark的结果清理为更好的可读CDP客户端

时间:2017-07-19 08:58:25

标签: awk grep tshark

我试图从命令输出中删除我不需要的信息,这样我就可以为linux构建一个简单的CDP客户端。现在,我正在使用grep来过滤tshark的结果。我正在运行的命令是:

tshark -i enp0s25 -a duration:30 -V -f "ether host 01:00:0c:cc:cc:cc" -c 2 | grep -e "IP Address" -e "Device ID:" -e "Software version: Cisco IOS Software" -e "Port ID:" -e "VTP Management Domain:" -e "Native VLAN:" -e "Voice VLAN:" -e "Duplex:" -e "Power Available:"

我得到的结果目前采用以下格式:

    Device ID: SW17.241.host.local
    Device ID: SW17.241.host.local
    Software version: Cisco IOS Software, C3560 Software (C3560-IPSERVICESK9-M), Version 12.2(55)SE10, RELEASE SOFTWARE (fc2)
        IP Address: 172.16.17.241
Port ID: FastEthernet0/3
VTP Management Domain: NAME
    VTP Management Domain: NAME
Native VLAN: 5
    Native VLAN: 5
Duplex: Full
    Duplex: Full
    Voice VLAN: 300
        IP Address: 172.16.17.241
Power Available: 
    Power Available: 0 mW
    Power Available: 4294967295 mW
Device ID: SW17.241.host.local
    Device ID: SW17.241.host.local
    Software version: Cisco IOS Software, C3560 Software (C3560-IPSERVICESK9-M), Version 12.2(55)SE10, RELEASE SOFTWARE (fc2)
        IP Address: 172.16.17.241
Port ID: FastEthernet0/3
VTP Management Domain: NAME
    VTP Management Domain: NAME
Native VLAN: 5
    Native VLAN: 5
Duplex: Full
    Duplex: Full
    Voice VLAN: 300
        IP Address: 172.16.17.241
Power Available: 
    Power Available: 0 mW
    Power Available: 4294967295 mW

正如你所看到的,我得到了很多重复的线条。我想只获得每一行的一个实例。例如,线路" Power Available:" 不需要在那里。我只需要看到可用电源线:4294967295 mW 此外,该行" IP地址:172.16.17.241"出现不止一次。我只需要一次。

我希望看到类似的内容:

Device ID: Software Version: Port ID: VTP Management Domain: Native VLAN: Duplex: Voice VLAN: Power Available:

2 个答案:

答案 0 :(得分:0)

$ cat awk-script
BEGIN{
  str="Device ID:Software version:Port ID:VTP Management Domain:Native VLAN:Duplex:Voice VLAN:Power Available.*[1-9]"
  split(str,s,":")
}
{
  for(i=1;i<=length(s);i++)
    if ($0 ~ s[i] && s[i]){
      s[i]=0;print $0
    }
}

$ tshark -i enp0s25 -a duration:30 -V -f "ether host 01:00:0c:cc:cc:cc" -c 2 | awk -f awk-script
    Device ID: SW17.241.host.local
    Software version: Cisco IOS Software, C3560 Software (C3560-IPSERVICESK9-M), Version 12.2(55)SE10, RELEASE SOFTWARE (fc2)
Port ID: FastEthernet0/3
VTP Management Domain: NAME
Native VLAN: 5
Duplex: Full
    Voice VLAN: 300
    Power Available: 4294967295 mW

简要说明:

  • 将所有需要的过滤值记录到str
  • Power Available.*[1-9]提取行中包含非零值的行包含“Power Available”
  • 如果已经命中特定值,则遍历文件,将标志设置为“0”。因此,对于每个过滤值,它们将被打印一次

答案 1 :(得分:0)

谢谢你们。我实际上让它工作,甚至更好,我使用tcpdump和上面建议的awk脚本。结果是在github上: http://github.com/yurividal/tuxCDP 随意贡献