/
Linux grep 사용법
Linux grep 사용법
출력 옵션
찾으려는 내용이 있는 파일명 출력
-H, --with-filename 옵션 사용 (기본이므로 추가 필요 없음)
grep -H pattern *
찾은 파일명은 출력하지 않음
-h, --no-filename 옵션 사용
grep -h pattern *
Context Line Control
-A NUM, --after-context=NUM 옵션을 사용하면 찾은 부분 이후의 NUM 번째 라인까지 출력합니다. 다음 옵션은 pattern 을 찾은 후에 pattern 이 있는 부분부터 4번째 line 까지 출력합니다.
grep -A 4 pattern *
반대로 -B NUM, --before-context=NUM 옵션을 사용하면 찾은 부분 이전의 NUM 번째 라인까지 출력합니다. 다음 옵션은 pattern 을 찾은 후에 pattern 이 있는 부분부터 위로 4번째 line 까지 출력합니다.
grep -B 4 pattern *
파일명만 출력하고 일치하는 내용은 출력하지 않음
-l, --files-with-matches 옵션 사용, 결과가 많을 경우 유용
grep -l pattern *
일치하는 부분만 출력
-o, --only-matching 를 사용하면 일치하는 문자만 출력
grep -o pattern *
검색 제어
or 연산
grep 'pattern1\|pattern2' filename
정규식 사용
-E 옵션을 사용하면 Extended regex 문법 사용 가능(기본은 POSIX)
abc 뒤에 3자리 숫자 찾기
echo "abc-123 test" | grep -E abc-[0-9]{3}
사용 예
ssh 접속 시도 IP 추출
ssh 가 열려 있을 경우 취약점을 통해 접속하려는 로그가 secure 에 남게 됨
Bad protocol version identification '\003' from 141.98.81.34 port 59559
아래의 명령어로 접속 시도하는 IP 를 추출한 후에 firewall-cmd 를 사용하여 IP 를 drop 할 수 있음.
grep "Bad pro" /var/log/secure*|grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"|grep -v '\\'|uniq > drop-ip.txt
IP 목록 차단
$ sudo bash firewallcmd-drop-client.sh -i 1.2.3.4,11.22.33.44
파일에서 IP 목록 읽어서 차단
$ sudo bash firewallcmd-drop-client.sh -f drop-ip-list
같이 보기
- 여러 조건으로 파일을 찾는 Linux find 명령어 사용법
- firewallcmd-drop-client.sh
- 배시 셸 스크팁트 프로그래밍(bash shell script programming)
Ref
- http://www.thegeekstuff.com/2011/10/grep-or-and-not-operators
- https://unix.stackexchange.com/questions/37313/how-do-i-grep-for-multiple-patterns
, multiple selections available,
Related content
linux cut 명령어 사용법
linux cut 명령어 사용법
More like this
파일 유형(file type)을 알려주는 linux file 명령어 사용법
파일 유형(file type)을 알려주는 linux file 명령어 사용법
More like this
ls 로 디렉토리만 출력하기
ls 로 디렉토리만 출력하기
More like this
파일의 앞 부분을 보는 linux head 명령어 사용법
파일의 앞 부분을 보는 linux head 명령어 사용법
More like this
Linux sed 사용법
Linux sed 사용법
More like this
linux cat 명령어 사용법
linux cat 명령어 사용법
More like this