linux 的 grep 命令 和 ngrep 命令

基本 grep 使用

[root@www ~]# grep [-acinv] [--color=auto] '搜寻字符串' filename
选项与参数:
-a :将 binary 文件以 text 文件的方式搜寻数据
-c 只输出匹配行的计数。计算找到 '搜寻字符串' 的次数
-h 查询多文件时不显示文件名。
-i 不区分大小写(只适用于单字符)。所以大小写视为相同
-l 查询多文件时只输出包含匹配字符的文件名。
-n 显示匹配行及行号。
-s 不显示不存在或无匹配文本的错误信息。
-v :反向选择,亦即显示出没有 '搜寻字符串' 内容的那一行!显示不包含匹配文本的所有行。
--color=auto :可以将找到的关键词部分加上颜色的显示喔!


将/etc/passwd,有出现 root 的行取出来
# grep root /etc/passwd

将/etc/passwd,有出现 root 的行取出来,同时显示这些行在/etc/passwd的行号
# grep -n root /etc/passwd
在关键字的显示方面,grep 可以使用 --color=auto 来将关键字部分使用颜色显示。 这可是个很不错的功能啊!但是如果每次使用 grep 都得要自行加上 --color=auto 又显的很麻烦~ 此时那个好用的 alias 就得来处理一下啦!你可以在 ~/.bashrc 内加上这行:『alias grep='grep --color=auto'』再以『 source ~/.bashrc 』来立即生效即可喔! 这样每次运行 grep 他都会自动帮你加上颜色显示啦

将/etc/passwd,将没有出现 root 的行取出来
# grep -v root /etc/passwd

将/etc/passwd,将没有出现 root 和nologin的行取出来
# grep -v root /etc/passwd | grep -v nologin

用 dmesg 列出核心信息,再以 grep 找出内含 eth 那行,要将捉到的关键字显色,且加上行号来表示:
[root@www ~]# dmesg | grep -n --color=auto 'eth'

用 dmesg 列出核心信息,再以 grep 找出内含 eth 那行,在关键字所在行的前两行与后三行也一起捉出来显示
[root@www ~]# dmesg | grep -n -A3 -B2 --color=auto 'eth'

根据文件内容递归查找目录

# grep ‘energywise’ *           #在当前目录搜索带'energywise'行的文件
# grep -r ‘energywise’ *        #在当前目录及其子目录下搜索'energywise'行的文件
# grep -l -r ‘energywise’ *     #在当前目录及其子目录下搜索'energywise'行的文件,但是不显示匹配的行,只显示匹配的文件
这几个命令很使用,是查找文件的利器。

grep与正规表达式

字符类
字符类的搜索:如果我想要搜寻 test 或 taste 这两个单字时,可以发现到,其实她们有共通的 't?st' 存在~这个时候,我可以这样来搜寻:
[root@www ~]# grep -n 't[ae]st' regular_express.txt

字符类的反向选择 [^] :如果想要搜索到有 oo 的行,但不想要 oo 前面有 g,如下
[root@www ~]# grep -n '[^g]oo' regular_express.txt
[root@www ~]# grep -n '[^a-z]oo' regular_express.txt
[root@www ~]# grep -n '[0-9]' regular_express.txt

行首与行尾字节 ^ $
行首字符:如果我想要让 the 只在行首列出呢? 这个时候就得要使用定位字节了!我们可以这样做:
[root@www ~]# grep -n '^the' regular_express.txt
如果我不想要开头是英文字母,则可以是这样:
[root@www ~]# grep -n '^[^a-zA-Z]' regular_express.txt
^ 符号,在字符类符号(括号[])之内与之外是不同的! 在 [] 内代表『反向选择』,在 [] 之外则代表定位在行首的意义!

那如果我想要找出来,行尾结束为小数点 (.) 的那一行:
[root@www ~]# grep -n '\.$' regular_express.txt
特别注意到,因为小数点具有其他意义(底下会介绍),所以必须要使用转义字符(\)来加以解除其特殊意义!
找出空白行:
[root@www ~]# grep -n '^$' regular_express.txt
因为只有行首跟行尾 (^$),所以,这样就可以找出空白行啦!

任意一个字节 . 与重复字节 *
这两个符号在正则表达式的意义如下:
. (小数点):代表『一定有一个任意字节』的意思;
* (星号):代表『重复前一个字符, 0 到无穷多次』的意思,为组合形态
假设我需要找出 g??d 的字串,亦即共有四个字节, 起头是 g 而结束是 d ,我可以这样做:
[root@www ~]# grep -n 'g..d' regular_express.txt

如果我想要字串开头与结尾都是 g,但是两个 g 之间仅能存在至少一个 o ,亦即是 gog, goog, gooog.... 等等,那该如何?
[root@www ~]# grep -n 'goo*g' regular_express.txt

如果我想要找出 g 开头与 g 结尾的行,当中的字符可有可无
[root@www ~]# grep -n 'g.*g' regular_express.txt

限定连续 RE 字符范围 {}
我们可以利用 . 与 RE 字符及 * 来配置 0 个到无限多个重复字节, 那如果我想要限制一个范围区间内的重复字节数呢?
举例来说,我想要找出两个到五个 o 的连续字串,该如何作?这时候就得要使用到限定范围的字符 {} 了。 但因为 { 与 } 的符号在 shell 是有特殊意义的,因此, 我们必须要使用字符   \ 来让他失去特殊意义才行。 至於 {} 的语法是这样的,假设我要找到两个 o 的字串,可以是:
[root@www ~]# grep -n 'o\{2\}' regular_express.txt

假设我们要找出 g 后面接 2 到 5 个 o ,然后再接一个 g 的字串,他会是这样:
[root@www ~]# grep -n 'go\{2,5\}g' regular_express.txt

如果我想要的是 2 个 o 以上的 goooo....g 呢?除了可以是 gooo*g ,也可以是:
[root@www ~]# grep -n 'go\{2,\}g' regular_express.txt

扩展grep(grep -E 或者 egrep)

使用扩展grep的主要好处是增加了额外的正则表达式元字符集。

grep 同时满足多个关键字和满足任意关键字
① grep -E "word1|word2|word3"   file.txt
   满足任意条件(word1、word2和word3之一)将匹配。
② grep word1 file.txt | grep word2 |grep word3
   必须同时满足三个条件(word1、word2和word3)才匹配。

1、或操作
grep -E '123|abc' filename  // 找出文件(filename)中包含123或者包含abc的行
egrep '123|abc' filename    // 用egrep同样可以实现
awk '/123|abc/' filename   // awk 的实现方式
2、与操作
grep pattern1 files | grep pattern2 //显示既匹配 pattern1 又匹配 pattern2 的行。
3、其他操作
grep -i pattern files   //不区分大小写地搜索。默认情况区分大小写,
grep -l pattern files   //只列出匹配的文件名,
grep -L pattern files   //列出不匹配的文件名,
grep -w pattern files  //只匹配整个单词,而不是字符串的一部分(如匹配‘magic’,而不是‘magical’),
grep -C number pattern files //匹配的上下文分别显示[number]行,

打印所有包含NW或EA的行。如果不是使用egrep,而是grep,将不会有结果查出。
# egrep 'NW|EA' testfile     
对于标准grep,如果在扩展元字符前面加\,grep会自动启用扩展选项-E。
#grep 'NW\|EA' testfile

搜索所有包含0个或1个小数点字符的行。
# egrep '2\.?[0-9]' testfile 
# grep -E '2\.?[0-9]' testfile
# grep '2\.\?[0-9]' testfile 

搜索一个或者多个连续的no的行。
# egrep '(no)+' testfile
# grep -E '(no)+' testfile
# grep '\(no\)\+' testfile   #3个命令返回相同结果,

ngrep 命令

参考:http://man.linuxde.net/ngrep

        ngrep命令是grep(grep是在文本中搜索字符串的工具)命令的网络版,他力求更多的grep特征,用于搜寻指定的数据包。正由于安装ngrep需用到libpcap库, 所以支持大量的操作系统和网络协议。能识别TCP、UDP和ICMP包,理解 bpf 的过滤机制。

        分析网络数据包,有Wireshark,它有着上千种设定、过滤器以及配置选项。它还有一个命令行版本Tshark。如果只是针对简单的任务,Wireshark就太重量级了,所以除非需要更强大的功能,一般情况下就用ngrep来处理了。Ngrep可以让你像类似grep处理文件的方式来处理网络封包。

伯克利包过滤(Berkeley Packet Filter,BPF)语言:http://www.cnblogs.com/zhongxinWang/p/4303153.html

扫描二维码关注公众号,回复: 5328257 查看本文章

ngrep参数

root@kali:~# man ngrep

用法: ngrep <-hNXViwqpevxlDtTRM> <-IO pcap_dump> <-n num> <-d dev> <-A num>
             <-s snaplen> <-S limitlen> <-W normal|byline|single|none> <-c cols>
             <-P char> <-F file> <match expression> <bpf filter>
   -h  帮助
   -V  版本信息
   -q  静默模式,如果没有此开关,未匹配的数据包都以“#”显示
   -e  显示空数据包
   -i  忽略大小写
   -v  反转匹配。    ngrep -v '' port 23   // 显示除telnet的数据包,-v意为反转。
   -R  is don't do privilege revocation logic
   -x  以16进制格式显示
   -X  以16进制格式匹配
   -w  整字匹配(is word-regex)
   -p  不使用混杂模式
   -l  is make stdout line buffered
   -D  is replay pcap_dumps with their recorded time intervals
   -t  is print timestamp every time a packet is matched
   -T  is print delta timestamp every time a packet is matched
   -M              仅进行单行匹配
   -I pcap_dump    从捕获的数据包文件pcap_dump中读取数据进行匹配
   -O pcap_dump    将匹配的数据保存到pcap格式的文件pcap_dump中
   -n num          仅捕获指定数目的数据包,然后退出。
   -A num          匹配到数据包后,Dump指定数目的数据包
   -s snaplen      设置 bpf caplen(default 65536)
   -S limitlen     在匹配的包上设置 上限长度
   -W normal | byline | single | none    设置dump格式。byline是解析包中的换行符 (normal, byline, single, none) 。加个-W byline参数后,将解析包中的换行符
   -c cols    强制显示列的宽度
   -P char    将不可打印的显示字符设置为指定的字符
   -F file    从文件中读取 bpf filter
   -N         显示由IANA定义的子协议号
   -d dev     ngrep会选择一个默认的网络接口进行监听,使用 -d 选项可以指定接口进行监听。 -d any 捕获所有的包
   -K num     杀死匹配的 TCP 连接(类似 tcpkill)。数值参数控制发送了多少个RST段。

dst host host       // True if the IP destination field of the packet is host, which may be either an address or a name.

src host host        // True if the IP source field of the packet is host.

host host
True if either the IP source or destination of the packet is host. Any of the above host expressions can be prepended with the
keywords, ip, arp, or rarp as in:
ip host host
相当于:

ether dst ehost
True if the ethernet destination address is ehost. Ehost may be either a name from /etc/ethers or a number (see ethers(3N) for
numeric format).

ether src ehost
True if the ethernet source address is ehost.

ether host ehost
True if either the ethernet source or destination address is ehost.

gateway host
True if the packet used host as a gateway. I.e., the ethernet source or destination address was host but neither the IP source
nor the IP destination was host. Host must be a name and must be found in both /etc/hosts and /etc/ethers. (An equivalent
expression is ether host ehost and not host host which can be used with either names or numbers for host / ehost.)

dst net net
True if the IP destination address of the packet has a network number of net. Net may be either a name from /etc/networks or a
network number (see networks(4) for details).

src net net        // True if the IP source address of the packet has a network number of net.

net net              // True if either the IP source or destination address of the packet has a network number of net.

net net mask mask        // True if the IP address matches net with the specific netmask. May be qualified with src or dst.

net net/len                     // True if the IP address matches net a netmask len bits wide. May be qualified with src or dst.

dst port port
True if the packet is ip/tcp or ip/udp and has a destination port value of port. The port can be a number or a name used in
/etc/services (see tcp(4P) and udp(4P)). If a name is used, both the port number and protocol are checked. If a number or
ambiguous name is used, only the port number is checked (e.g., dst port 513 will print both tcp/login traffic and udp/who traf-
fic, and port domain will print both tcp/domain and udp/domain traffic).
src port port        // True if the packet has a source port value of port.

port port
True if either the source or destination port of the packet is port. Any of the above port expressions can be prepended with
the keywords, tcp or udp, as in:
tcp src port port        // which matches only tcp packets whose source port is port.

less length                  // True if the packet has a length less than or equal to length. This is equivalent to:
len <= length.

greater length            // True if the packet has a length greater than or equal to length. This is equivalent to:
len >= length.

ip proto protocol
True if the packet is an ip packet (see ip(4P)) of protocol type protocol. Protocol can be a number or one of the names tcp,
udp or icmp. Note that the identifiers tcp and udp are also keywords and must be escaped via backslash (\), which is \\ in the
C-shell.

ip broadcast
True if the packet is an IP broadcast packet. It checks for both the all-zeroes and all-ones broadcast conventions, and looks
up the local subnet mask.

ip multicast           // True if the packet is an IP multicast packet.

ip Abbreviation for:
ether proto ip

tcp, udp, icmp
Abbreviations for:
ip proto p
where p is one of the above protocols.

实例

ngrep -d eth0 -W byline host 192.168.1.9    // 抓本机eth0 与192.168.1.9的通信信息,并且以行来打印出来

ngrep -W byline host 192.168.1.8 and port 80    // 抓本机与192.168.1.8的通信端口为80(本机)的信息

ngrep -W byline host 192.168.1.8 or host 192.168.1.9 port 80    // 抓本机与192.168.1.8和192.168.1.9的通信,并且本地端口为80

ngrep host 192.168.1.8 udp       // 抓udp包

ngrep -W byline 'GET /' 'tcp and dst port 80' -d eth1 | awk -v RS="#+" -v FS="\n" '{ print length() }'    // 统计请求头长度

ngrep -W byline 'GET /' 'tcp and dst port 80' -d eth1 |  awk -v RS="#+" -v FS="\n" 'length() > 1000'      // 查询一下大于 1K 的请求头

捕获字符串.flv,比如要查看在Web Flash 视频中的.flv文件的下载地址: 
ngrep -d3 -N -q \.flv
然后打开一个视频页面

针对Web流量,几乎总是想要加上-W byline选项,这会保留换行符,而-q选项可以抑制某些非匹配数据包而产生的输出。

抓取所有包含有GET或POST请求数据包的例子:ngrep –q –W byline “^(GET|POST) .*”

可以传入附加的报文过滤选项,比如限制匹配的报文只针对某个特定的主机,IP或端口。这里我们把所有流经Google的流量做一个过滤,只针对80端口且报文中包含“search”。例子:ngrep –q –W byline “search” host www.google.com and port 80

ngrep '' udp            /*匹配udp包*/  
ngrep '' icmp           /*匹配icmp包*/  
ngrep '' port 53        /*显示所有的dns请求*/  
ngrep '../'             /*监听远程主机的'../'请求*/  
ngrep -d rl0 port 80    /*服务器端http数据*/  
ngrep -d rl0 'error' port syslog        /**/  
ngrep -wi -d rl0 'user|pass' port 21    /*关注端口21上的user和pass*/ 
ngrep -d eth0 ''        /* 显示所有的数据包,-d 指定硬件接口。 */

猜你喜欢

转载自blog.csdn.net/qq_24857309/article/details/87779646