2013-02-22 21 views
0

我有一大堆數據信息的數據文件,並試圖從文件中提取IP時間和長度。我設法提取時間,但我不知道如何提取長度和IP。有沒有一種方法可以搜索並查看長度,然後打印長度是多少?從打印中提取python中的特定行

import sys 
import string 


text_file = file('MyTraceOutput.txt', "r") 

for line in text_file: 
    columns = line.split(' ') 

    if columns: 
     print "Time", columns[0] 

什麼我迄今

這是繼續數據文件的一部分......

reading from file enel573-project1-1-0.pcap, link-type EN10MB (Ethernet) 

2.000000 arp who-has 192.168.0.1 (ff:ff:ff:ff:ff:ff) tell 192.168.0.2 
2.000023 arp who-has 192.168.0.1 (ff:ff:ff:ff:ff:ff) tell 192.168.0.3 
2.000044 arp reply 192.168.0.1 is-at 00:00:00:00:00:01 
2.000044 IP (tos 0x0, ttl 64, id 0, offset 0, flags [none], proto: TCP (6), length: 40, bad cksum 0 (->f97c)!) 192.168.0.2.49153 > 192.168.0.1.80: S, cksum 0x0000 (incorrect (-> 0x6e3d), 0:0(0) win 65535 
2.000116 arp reply 192.168.0.1 is-at 00:00:00:00:00:01 
2.000128 arp who-has 192.168.0.2 (ff:ff:ff:ff:ff:ff) tell 192.168.0.1 
2.000128 arp reply 192.168.0.2 is-at 00:00:00:00:00:02 
2.000141 IP (tos 0x0, ttl 64, id 0, offset 0, flags [none], proto: TCP (6), length: 40, bad cksum 0 (->f97b)!) 192.168.0.3.49153 > 192.168.0.1.80: S, cksum 0x0000 (incorrect (-> 0x6e3c), 0:0(0) win 65535 
2.000152 arp who-has 192.168.0.3 (ff:ff:ff:ff:ff:ff) tell 192.168.0.1 
2.000165 arp reply 192.168.0.3 is-at 00:00:00:00:00:03 
2.000178 IP (tos 0x0, ttl 64, id 1, offset 0, flags [none], proto: TCP (6), length: 40, bad cksum 0 (->f97a)!) 192.168.0.1.80 > 192.168.0.3.49153: S, cksum 0x0000 (incorrect (-> 0x6e2b), 0:0(0) ack 1 win 65535 
2.000189 IP (tos 0x0, ttl 64, id 1, offset 0, flags [none], proto: TCP (6), length: 40, bad cksum 0 (->f97a)!) 192.168.0.3.49153 > 192.168.0.1.80: ., cksum 0x0000 (incorrect (-> 0x6e2c), ack 1 win 65535 
2.000202 IP (tos 0x0, ttl 64, id 2, offset 0, flags [none], proto: TCP (6), length: 44, bad cksum 0 (->f975)!) 192.168.0.3.49153 > 192.168.0.1.80: ., cksum 0x0000 (incorrect (-> 0x18d3), 1:5(4) ack 1 win 65535 
2.000214 IP (tos 0x0, ttl 64, id 2, offset 0, flags [none], proto: TCP (6), length: 40, bad cksum 0 (->f979)!) 192.168.0.1.80 > 192.168.0.3.49153: ., cksum 0x0000 (incorrect (-> 0x6e28), ack 5 win 65535 
2.000253 IP (tos 0x0, ttl 64, id 3, offset 0, flags [none], proto: TCP (6), length: 44, bad cksum 0 (->f974)!) 192.168.0.3.49153 > 192.168.0.1.80: ., cksum 0x0000 (incorrect (-> 0x18cf), 5:9(4 

回答

2

一種可能的方式做到這一點是使用str.translate

>>> from string import printable, digits 
>>> select_set = ''.join(set(printable) - set(digits + '. ')) 
>>> st = "2.000000 arp who-has 192.168.0.1 (ff:ff:ff:ff:ff:ff) tell 192.168.0.2" 
>>> st.translate(None, select_set).split() 
['2.000000', '192.168.0.1', '192.168.0.2'] 

另一種選擇是使用正則表達式

>>> import re 
>>> re.findall('[\d\.]+',st) 
['2.000000', '192.168.0.1', '192.168.0.2'] 

所以你的程序變爲

import sys 
import string 


text_file = file('MyTraceOutput.txt', "r") 

for line in text_file: 
    columns = re.findall('[\d\.]+',line) 

    if columns: 
     print "Time {}, IP_Range {}-{}".format(*columns)