简体   繁体   中英

get a substring from a file shell script

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

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 ;)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM