get a substring from a file shell script

2020-02-07 07:26发布

I need a little help with this shell script. I have a variable, represents a IP/TCP header. I need filter a traffic capture by the header selected.

> var=ttl 128
> 
> tcpdump -Xvv -n -i eth0 -c 300 > capture.txt 2>/dev/null
> 
> grep -i "$var" capture.txt > resultGrep.txt

The result of the tcpdump command is some like this

15:29:18.164566 IP (tos 0x0, ttl 1, id 2394, offset 0, flags [none], proto UDP (17), length 125)
    10.0.0.155.58363 > 239.255.255.254.1900: UDP, length 97
    0x0000:  4600 0024 0000 0000 0102 3ad3 0a00 0000  F..$......:.....
    0x0010:  e000 0001 9404 0000 1101 ebfe 0000 0000  ................
    0x0020:  0300 0000 0000 0000 0000 0000 0000       ..............
15:29:18.164566 IP (tos 0x0, ttl 128, id 2394, offset 0, flags [none], proto UDP (17), length 125)
    10.0.0.131.58363 > 239.255.255.250.1900: UDP, length 97
    0x0000:  4600 0024 0000 0000 0102 3ad3 0a00 0000  F..$......:.....
    0x0010:  e000 0001 9404 0000 1101 ebfe 0000 0000  ................
    0x0020:  0300 0000 0000 0000 0000 0000 0000       ..............

I need have ip address source and ip address destination, in the example the output result must be

10.0.0.131.58363 > 239.255.255.250.1900

标签: linux shell grep
2条回答
你好瞎i
2楼-- · 2020-02-07 08:07

Try doing this directly in a Unix pipe over tcpdump :

tcpdump -Xvv -n -i eth0 -c 300 |
grep -oP "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,5}\s+>\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,5}"

This is rock solid ;)

查看更多
叼着烟拽天下
3楼-- · 2020-02-07 08:15

well my understanding of the question is, you want to extract things from your resultGrep.txt, not capture.txt

then:

grep -oP '[\d\.]*\s*>\s*[\d\.]*' resultGrep.txt

see test:

kent$  echo "15:29:18.164566 IP (tos 0x0, ttl 1, id 2394, offset 0, flags [none], proto UDP (17), length 125)
dquote>     10.0.0.131.58363 > 239.255.255.250.1900: UDP, length 97
dquote>     0x0000:  4600 0024 0000 0000 0102 3ad3 0a00 0000  F..$......:.....
dquote>     0x0010:  e000 0001 9404 0000 1101 ebfe 0000 0000  ................
dquote>     0x0020:  0300 0000 0000 0000 0000 0000 0000       .............."|grep  -oP '[\d\.]*\s*>\s*[\d\.]*'
10.0.0.131.58363 > 239.255.255.250.1900
查看更多
登录 后发表回答