🖥️
인프라 운영 & SRE 명령어 치트시트
이 트랙 52개 모듈의 핵심 명령어·단축키 643개를 한 곳에 모았습니다. 실무 중 “그 명령어 뭐였지?” 할 때 검색해 바로 꺼내 쓰세요. 각 모듈 제목을 누르면 해당 강의로 이동합니다.
643개 명령 · 52개 모듈
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
hostname / hostnamectl | 서버 환경·역할 식별(prd/stg/dev) | hostname -f(FQDN), hostnamectl(OS·커널까지) |
cat /etc/os-release | 배포판·버전 확인 | cat /etc/os-release | grep -E 'NAME|VERSION' |
ip addr show | IP·네트워크 인터페이스 확인 | ip addr show | grep 'inet ' |
ss -tlnp | LISTEN 포트로 서비스 구성 파악 | ss -tlnp | grep LISTEN(80/443=Web, 8080=WAS, 3306=DB) |
systemctl list-units | 실행 중 서비스 목록 | systemctl list-units --type=service --state=running |
df -h / free -m | 디스크·메모리 빠른 점검 | df -h | grep '/$'(루트 사용률), free -m |
echo $APP_ENV | 환경변수로 운영/개발 구분 | echo $APP_ENV → production/staging/development |
cp … .bak.$(date …) | 변경 전 설정 백업 습관 | cp nginx.conf nginx.conf.bak.$(date +%Y%m%d%H%M) |
rpm -qa / dpkg -l | 설치 패키지 확인(인계 시) | rpm -qa | grep -E 'nginx|tomcat', dpkg -l | grep nginx |
last / crontab -l | 로그인 이력·예약 작업 파악 | last | head -20, crontab -l |
curl -s <노드>:8080/health | LB 우회로 개별 노드 헬스체크 | curl -s http://10.0.1.11:8080/health(반반 장애 노드 특정) |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
hostnamectl set-hostname | 호스트명 영구 설정(재부팅 유지) | hostnamectl set-hostname web-prd-01 |
timedatectl set-timezone | 타임존 설정(로그 시각 통일) | timedatectl set-timezone Asia/Seoul |
localectl set-locale | 로케일 설정(한글 인코딩) | localectl set-locale LANG=ko_KR.UTF-8 |
chronyc tracking | NTP 시간 동기화 확인 | chronyc tracking | grep -E 'Source|Offset' |
dnf / apt-get install | 필수 패키지 설치 | dnf install -y java-17-openjdk, apt-get install -y wget curl unzip |
useradd -r -s /sbin/nologin | 로그인 불가 서비스 계정 생성 | useradd -r -s /sbin/nologin -d /opt/tomcat -m tomcat |
id / getent passwd | 계정 UID·셸 확인 | id tomcat, getent passwd tomcat |
firewall-cmd --permanent | 방화벽 포트·서비스 영구 허용 | firewall-cmd --permanent --add-service=http && firewall-cmd --reload |
firewall-cmd --list-all | 허용 서비스·포트 확인 | firewall-cmd --list-all(ssh 포함 여부 먼저) |
getenforce / setenforce | SELinux 모드 확인·임시 전환 | setenforce 0(Permissive 진단) → setenforce 1 |
semanage port | SELinux 포트 정책 추가 | semanage port -a -t http_port_t -p tcp 8081 |
sshd -t | sshd_config 문법 검증(재시작 전 필수) | sshd -t && systemctl restart sshd |
ssh-keygen / ssh-copy-id | 키 생성·서버 등록 | ssh-keygen -t ed25519 -C ops@co, ssh-copy-id -p 2222 deploy@IP |
systemctl --failed | 재부팅 후 실패 유닛 확인 | systemctl --failed, systemctl is-enabled <svc> |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
du -sh | 디렉터리 용량 확인(디스크 풀 원인) | du -sh /var/log/* | sort -rh | head |
find | 조건별 파일 탐색(로그·임시파일) | find /var/log -mmin -30 -name '*.log', find /tmp -mtime +7 |
ls -la / stat | 권한·소유자 확인 | stat -c '%n: %a (%A)' file, ls -la /opt/ |
chmod | 권한 설정(숫자 모드) | chmod 640 config.yml, chmod -R 755 /opt/tomcat/bin |
chown / chgrp | 소유자·그룹 변경(배포 후 필수) | chown -R tomcat:tomcat /opt/tomcat/webapps |
visudo | sudoers 안전 편집(문법 검증 포함) | visudo -f /etc/sudoers.d/deploy |
sudo -l / sudo -u | sudo 권한 점검·다른 계정 실행 | sudo -l, sudo -u tomcat /opt/tomcat/bin/startup.sh |
usermod -aG | 그룹 추가(sudo/wheel) | usermod -aG wheel username → 재로그인 또는 newgrp |
systemctl status | 서비스 상태·enabled 여부 | systemctl status nginx(Loaded·Active 줄 확인) |
systemctl start/stop/restart/reload | 서비스 제어 | systemctl reload nginx(무중단 재적용) |
systemctl enable --now | 부팅 자동시작+즉시 시작 | systemctl enable --now nginx |
systemctl list-units --state=failed | 실패 서비스 확인(장애 1순위) | systemctl list-units --type=service --state=failed |
journalctl -u | 서비스 로그 조회 | journalctl -u tomcat -n 100 --no-pager, -f(실시간) |
systemctl daemon-reload | unit 파일 변경 반영 | daemon-reload && systemctl enable --now myapp |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
ps aux | 프로세스 스냅샷(CPU/MEM/STAT) | ps aux --sort=-%cpu | head, --sort=-%mem |
pgrep / pidof | 이름으로 PID 추출 | pgrep -f tomcat, pidof nginx |
top | 실시간 부하·%Cpu·load average | top -bn1 | head -15, 키: M(메모리) P(CPU) 1(코어별) |
uptime / nproc | load average를 코어 수와 비교 | uptime && nproc |
ss -tlnp | LISTEN 포트·프로세스 확인 | ss -tlnp | grep ':8080'(DB는 127.0.0.1 바인딩 확인) |
lsof | 포트·FD 점유 프로세스 확인 | lsof -i:8080, lsof -nP +L1(삭제됐지만 열린 파일) |
df -h | 디스크 사용률 | df -h(Use% 85%↑ 주의) |
df -i | inode 소진 확인(공간 남아도 생성 실패) | df -i(IUse% 100%면 소진) |
du -sh | 큰 디렉터리·파일 찾기 | du -sh /var/log/* | sort -rh | head |
free -m | 메모리·스왑 상태 | free -m(available·Swap used), watch -n 2 free -m |
journalctl -u | 서비스 로그 시간·레벨 필터 | journalctl -u tomcat --since '30 min ago' -p err |
journalctl -k / dmesg | 커널·OOM 로그 확인 | journalctl -k --since today | grep -i oom |
kill -9 | 잔존 프로세스 강제 종료 | kill -9 <PID>(포트 충돌 시 마지막 수단) |
: > /proc/<PID>/fd/<n> | 삭제 안 된 열린 로그 즉시 비우기 | : > /proc/5678/fd/3(rm 후 df가 안 빠질 때) |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
set -euo pipefail | 안전 3종(실패 즉시 종료·파이프·미정의 변수) | 모든 스크립트 2번째 줄에 배치 |
trap … EXIT | 종료 시 정리 작업 보장 | trap cleanup EXIT |
logger -t | 실행 기록을 syslog에 남김 | logger -t deploy "started", 확인 journalctl -t deploy |
[[ … ]] | 조건 검사(파일·변수·비교) | [[ -f "$f" ]], [[ -z "$v" ]], [[ "$n" -ge 85 ]] |
${VAR:-기본값} | 미정의 변수 기본값(set -u 안전) | THRESHOLD=${1:-80} |
for / while read | 서버·파일 목록 반복 | for s in web01 web02; do …, while IFS= read -r s; do … done < list |
local VAR; VAR=$(…) | 명령 치환 실패 감지(한 줄 결합 금지) | local OUT; OUT=$(curl -f …) |
systemctl is-active --quiet | 서비스 상태로 분기 | systemctl is-active --quiet nginx && echo up |
curl -sf | 헬스체크(실패 시 비정상 종료) | curl -sf http://localhost:8080/health || error 실패 |
ssh -o … | 원격 일괄 점검 옵션 | ssh -o ConnectTimeout=5 -o BatchMode=yes "$s" uptime |
awk / tr -d | 출력 파싱(사용률 추출) | df -h / | awk 'NR==2{print $5}' | tr -d '%' |
bash -x | 스크립트 실행 추적 디버깅 | bash -x deploy.sh |
chmod +x | 스크립트 실행 권한 부여 | chmod +x ~/scripts/disk-check.sh |
crontab */N * * * * | 스크립트 정기 실행 등록 | */10 * * * * /opt/scripts/disk-check.sh >> log 2>&1 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
useradd | 일반·서비스 계정 생성 | useradd -r -s /sbin/nologin -d /opt/app -m appuser |
usermod | 계정 수정(그룹·잠금·셸) | usermod -aG appgroup appuser, usermod -L devuser |
groupadd / gpasswd | 그룹 생성·멤버 관리 | groupadd appgroup, gpasswd -a appuser appgroup |
id / getent | 계정 UID·GID·그룹 확인 | id appuser, getent passwd appuser |
/etc/passwd·/etc/shadow | 계정·패스워드 상태 확인 | grep appuser /etc/passwd, sudo grep appuser /etc/shadow(!=잠금) |
chmod(숫자) | 파일 권한 설정 | chmod 640 config.yml, chmod 600 secret.key |
chmod 2775 / g+s | 디렉터리 setgid(그룹 상속) | chmod 2775 /opt/deploy |
chown / chgrp | 소유자·그룹 변경 | chown -R appuser:appgroup /opt/app, chgrp -R deploy dir |
stat -c | 권한 숫자·rwx 동시 확인 | stat -c '%n: %a (%A)' file |
find / -perm -4000 | SUID 파일 감사 | find / -perm -4000 -type f 2>/dev/null |
visudo -f | sudoers 안전 편집(전용 파일) | visudo -f /etc/sudoers.d/appuser |
sudo -l | 계정 sudo 권한 점검 | sudo -l, sudo -l -U appuser |
newgrp | 새 그룹 즉시 적용(재로그인 대체) | newgrp deploy |
journalctl _COMM=sudo | sudo 실행 감사 로그 | journalctl _COMM=sudo --since today | grep appuser |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
ssh-keygen | 키 쌍 생성(ed25519 권장) | ssh-keygen -t ed25519 -C "admin@co" -f ~/.ssh/id_ed25519 |
ssh-copy-id | 공개키를 서버에 등록 | ssh-copy-id -i ~/.ssh/id_ed25519.pub -p 22 user@IP |
chmod(SSH 권한) | 키·디렉터리 권한(틀리면 인증 거부) | chmod 700 ~/.ssh, chmod 600 ~/.ssh/authorized_keys |
sshd -t | sshd_config 문법 검증(reload 전 필수) | sshd -t && systemctl reload sshd |
systemctl reload sshd | 무중단 설정 재적용(restart 아님) | systemctl reload sshd(기존 세션 유지) |
ssh -J(ProxyJump) | 배스천 경유 내부 서버 접속 | ssh -J infra-admin@bastion admin@10.0.1.50 |
ssh -vvv | 인증 실패 지점 디버깅 | ssh -vvv -i key user@server | grep -E 'Offering|denied' |
grep … sshd_config | 강화 항목 확인 | grep -E 'PermitRootLogin|PasswordAuthentication' /etc/ssh/sshd_config |
tail /var/log/secure | SSH 접속 시도 로그 확인 | grep "Failed password" /var/log/secure | tail |
last / lastb / lastlog | 성공·실패·계정별 로그인 이력 | last -20, lastb | head, lastlog |
fail2ban-client status | 무차별 대입 차단 현황·해제 | fail2ban-client status sshd, set sshd unbanip <IP> |
ssh-add -c / -t | Agent Forwarding 위험 축소 | ssh-add -c(서명마다 확인), ssh-add -t 3600(만료) |
echo $SSH_AUTH_SOCK | 배스천에 에이전트 노출 점검 | 배스천에서 값이 있으면 Agent Forwarding 켜진 위험 상태 |
grep … | sort | uniq -c | 실패 로그에서 공격 IP 상위 집계 | grep "Failed password" /var/log/secure | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
yum check-update --security | 보안 패치만 목록 확인(설치 안 함) | Debian: apt list --upgradable | grep -i security |
yum update --security | 보안 패치만 선택 적용 | dry-run --assumeno, 실제 적용 -y |
yum update kernel -y | 커널 업데이트(재부팅 필요) | 적용 후 reboot → uname -r 재확인 |
rpm -qa --last | head | 최근 설치·업데이트 이력 | 현재 버전: rpm -qa | grep openssl |
yum history list / info N | 패치 트랜잭션 이력 조회 | 롤백용 트랜잭션 ID 확인 |
yum history undo N | 트랜잭션 통째로 롤백 | 특정 패키지만: yum downgrade openssl |
uname -r | 실행 중 커널 버전 | 설치 커널과 다르면 재부팅 미반영 |
grubby --default-kernel | 다음 부팅 기본 커널 확인 | 롤백 grubby --set-default /boot/vmlinuz-… |
needs-restarting -r | 재부팅 필요 여부 | 서비스만 재시작 대상은 needs-restarting -s |
lsof +c0 | grep -i deleted | 옛 라이브러리 물고 있는 프로세스 | 패치 후 스캐너 재검출 원인 추적 |
systemctl restart nginx | 패치된 .so 반영 위해 서비스 재시작 | 라이브러리 패치의 실제 '적용' 단계 |
nginx -t | 미들웨어 버전 업 후 설정 문법 검사 | JDK 전환은 alternatives --config java |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
nginx -t | 설정 문법 검사(반영 전 필수) | nginx -t && systemctl reload nginx |
systemctl reload nginx | 무중단 설정 반영 | 프로세스 끊김 없이 새 설정 적용 |
proxy_pass | 요청을 백엔드 WAS로 중계 | proxy_pass http://127.0.0.1:8080; (localhost 대신 IP) |
proxy_set_header | 클라이언트 정보 헤더 전달 | X-Real-IP $remote_addr, X-Forwarded-For $proxy_add_x_forwarded_for |
proxy_read_timeout | WAS 응답 대기 시간 | 초과 시 504 — proxy_read_timeout 60s; |
worker_processes / worker_connections | 최대 동시 접속(둘의 곱) | worker_processes auto;, ulimit -n보다 작게 |
ss -tlnp | grep 8080 | WAS가 8080에 바인딩됐는지 | 502 시 백엔드 생존 1차 확인 |
curl -I http://localhost | 프록시 응답·Server 헤더 확인 | 백엔드 직접: curl -v http://127.0.0.1:8080/ |
ps -ef | grep tomcat | WAS 프로세스 생존 확인 | PID만: pgrep -f tomcat |
jstack <PID> | 스레드 덤프(포화 진단) | jstack $(pgrep -f tomcat) > dump.txt |
tail -f /var/log/nginx/error.log | 프록시 오류 실시간 확인 | Connection refused 대상 파악 |
ln -sf …sites-available …sites-enabled/ | 가상호스트 활성화 | 활성화 후 nginx -t |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
nc -zv 10.10.3.100 3306 | WAS→DB 포트 도달(방화벽) 확인 | succeeded=열림, 타임아웃=차단, refused=DB 미기동 |
telnet DB_IP 3306 | nc 없을 때 포트 확인 대안 | 연결되면 방화벽 통과 |
ss -tlnp | grep -E ':3306|:5432' | DB 포트 바인딩 IP 확인 | 0.0.0.0=전체 노출(위험), 내부망 IP=정상 |
ip addr show | 서버 IP·VIP 보유 확인 | VIP는 secondary/:vip로 표시 |
ip route show | 타 구간 라우팅 경로 확인 | 경로 없으면 통신 자체 불가 |
curl -o /dev/null -s -w "%{http_code}" | Web→WAS Health Check | http://10.10.2.11:8080/health 200 확인 |
systemctl status keepalived | VIP 관리 데몬 상태 | 자동기동: systemctl enable nginx tomcat |
journalctl -u keepalived | grep -i state | Master/Backup 전환 이력 | 양쪽 다 MASTER면 Split-Brain |
tcpdump -ni eth0 proto 112 | VRRP 광고 도달 확인 | 자기 것만 보이면 하트비트 단절 |
mysql -h DB_IP -u appuser -p | DB 직접 연결 테스트 | Access denied=계정·권한 문제 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
curl -v https://… | DNS→TCP→TLS→응답 단계별 추적 | Trying/Connected to/< HTTP 로 멈춘 지점 파악 |
nslookup example.com | 도메인→IP 해석 확인 | 공인 DNS 직접: nslookup example.com 8.8.8.8 |
dig +trace example.com | 루트→권한 DNS 위임 경로·TTL | 짧은 조회는 dig +short |
tail -f /var/log/nginx/access.log | 요청·상태코드·upstream 실시간 | 5xx만: grep ' 5[0-9][0-9] ' access.log |
awk '{print $NF,$7}' access.log | sort -rn | 응답 느린 요청 상위 추출 | $upstream_response_time 기준 지연 구간 파악 |
ss -tlnp | grep 8080 | Tomcat 리스닝 확인 | 프로세스는 ss -tlnp | grep java |
grep -r proxy_pass /etc/nginx/ | 프록시 대상 설정 확인 | 경로별 upstream 오지정 여부 |
curl -v http://WAS_IP:8080/health | Nginx 우회 백엔드 직접 테스트 | 성공=Nginx 설정 문제, 실패=WAS 이하 |
firewall-cmd --list-all | 내부 방화벽 규칙 확인 | iptables는 iptables -L -n | grep 8080 |
systemd-resolve --flush-caches | Linux DNS 캐시 초기화 | Win ipconfig /flushdns, mac dscacheutil -flushcache |
grep example.com /etc/hosts | 로컬 강제 해석 항목 확인 | 잘못된 항목이 엉뚱한 서버로 보냄 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
nginx -t | 설정 문법 검사(무중단) | 운영 표준 nginx -t && systemctl reload nginx |
nginx -T | include까지 합친 전체 설정 덤프 | 중복 확인 nginx -T | grep server_name |
systemctl reload nginx | 무중단 설정 재적용 | 기존 요청 유지, 일반 설정 변경에 사용 |
systemctl restart nginx | 완전 재시작(순간 끊김) | 바이너리 업그레이드·상태 초기화 시 |
systemctl enable --now nginx | 기동+부팅 자동시작 등록 | enable 누락 시 재부팅 후 미기동 |
nginx -s reload / -s quit | 시그널로 재적용/우아한 종료 | 중복 프로세스 정리 nginx -s quit |
ss -tlnp | grep ':80' | 80 포트 점유 프로세스 확인 | 대안 lsof -i:80, 충돌원(Apache) 파악 |
tail -f /var/log/nginx/access.log | 요청 실시간 확인 | 에러는 /var/log/nginx/error.log |
awk '$9==404{print $7}' access.log | sort | uniq -c | sort -rn | 404 많은 URI 집계 | 상태코드별 grep ' 500 ' access.log |
journalctl -u nginx -n 30 --no-pager | 기동 실패 상세 원인 | systemctl status nginx 와 함께 |
location / try_files | URL 매칭·SPA fallback | try_files $uri $uri/ /index.html; |
ss -s | 소켓 요약(연결 상한 근접 확인) | fd 한도 cat /proc/<worker>/limits |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
proxy_pass | 요청을 백엔드/upstream으로 전달 | proxy_pass http://app_servers; |
upstream 블록 | 백엔드 서버 그룹 정의 | 안에 server 10.0.0.1:8080; 나열 |
least_conn / ip_hash | 로드밸런싱 알고리즘 | 기본 round-robin, 세션고정 ip_hash |
server … weight=3 | 서버별 가중치 | 성능 좋은 서버에 더 많은 요청 |
server … max_fails=3 fail_timeout=30s | 수동 헬스체크(자동 격리) | 예비 서버는 server …:8082 backup; |
keepalive 32 | 백엔드 연결 재사용 풀 | proxy_http_version 1.1+Connection "" 필수 |
proxy_http_version 1.1 | HTTP/1.1 강제(기본 1.0) | WebSocket·keepalive 재사용에 필수 |
proxy_set_header | 클라이언트 정보 전달 | X-Real-IP $remote_addr, Host $host |
proxy_set_header Upgrade $http_upgrade | WebSocket 프로토콜 전환 | Connection "upgrade" 와 세트 |
nginx -t && systemctl reload nginx | 검증 후 무중단 반영 | upstream 문법 오류 시 재시작 실패 방지 |
nginx -T | grep -A10 upstream | upstream 반영 여부 확인 | 헤더는 grep -E 'X-Real-IP|X-Forwarded' |
ss -tlnp | grep ':8080' | 백엔드 리스닝 확인(502 진단) | 직접 테스트 curl -v http://127.0.0.1:8080/health |
ss -tan state time-wait | wc -l | TIME_WAIT 폭증 확인 | keepalive 미동작 시 포트 고갈 신호 |
setsebool -P httpd_can_network_connect 1 | SELinux 프록시 연결 허용 | CentOS 502 원인 조회 ausearch -m avc |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
certbot --nginx -d yourdomain.com | 발급+Nginx 자동설정 | 여러 도메인은 -d 반복(SAN) |
certbot certonly --standalone -d … | Nginx 없이 단독 발급 | 발급 중 80 필요, 임시 systemctl stop nginx |
certbot certificates | 발급 인증서 만료일·경로 확인 | VALID: N days 로 잔여일 |
certbot renew --dry-run | 갱신 시뮬레이션(실제 안 함) | 강제 갱신 certbot renew --force-renewal |
systemctl status certbot.timer | 자동 갱신 타이머 확인 | cron certbot renew --post-hook "systemctl reload nginx" |
openssl s_client -connect host:443 | 원격 인증서·체인 점검 | -servername host, | openssl x509 -noout -dates |
openssl x509 -noout -dates -in fullchain.pem | 로컬 인증서 만료일 | notBefore/notAfter 출력 |
nginx -t && systemctl reload nginx | 검증 후 무중단 반영 | restart 아닌 reload 원칙 |
nginx -T | grep ssl_certificate | 적용 중 인증서 경로 확인 | 만료 오류 시 경로 불일치 대조 |
ssl_certificate / ssl_certificate_key | 인증서·개인키 경로 | 반드시 fullchain.pem(체인 완결) |
ssl_protocols TLSv1.2 TLSv1.3 | 허용 TLS 버전 | 1.0/1.1 비활성(취약) |
ssl_session_cache shared:SSL:10m | 재연결 핸드셰이크 생략 | ssl_session_timeout 10m 과 세트 |
return 301 https://$host$request_uri | HTTP→HTTPS 강제 리다이렉트 | 강화 HSTS add_header Strict-Transport-Security … |
ss -tlnp | grep ':443' | 443 SSL 리스닝 확인 | 방화벽 ufw allow 443/tcp |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
apachectl configtest | 설정 문법 검사(=apachectl -t) | apachectl configtest && apachectl graceful |
apachectl graceful | 무중단 재기동(처리 중 요청 유지) | 마지막 요청 후 종료는 apachectl graceful-stop |
apachectl -S | VirtualHost 매핑 요약 | 어느 도메인이 어느 .conf로 가는지 한눈에 |
httpd -M | 로드된 모듈 목록 | httpd -M | grep proxy (프록시 모듈 확인) |
httpd -V | 버전·MPM·컴파일 옵션 | httpd -V | grep -i mpm (event/prefork 확인) |
a2enmod / a2ensite | (Ubuntu) 모듈·사이트 활성화 | a2enmod proxy proxy_http headers |
systemctl reload apache2 | (Ubuntu) 무중단 반영 | reload=graceful, restart=순단 발생 |
curl -H "Host: ..." | VirtualHost 라우팅 테스트 | curl -H "Host: www.example.com" http://localhost/ |
tail error/access_log | 에러·접근 로그 추적 | tail -30 /var/log/httpd/error_log |
awk … | sort -rn | 슬로우 리퀘스트 추출 | awk '{print $NF,$7}' access.log | sort -rn | head (%D 마지막) |
ss -tan | 동시 연결 수 집계 | ss -tan | grep -c ESTAB |
grep '^User' httpd.conf | Apache 실행 계정 확인 | 403 시 DocumentRoot 소유자와 대조 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
pgrep -a -f catalina | Tomcat 프로세스·인자 확인 | ps aux | grep catalina 로 CATALINA_HOME도 확인 |
ss -tlnp | grep 8080 | 포트 리스닝·accept 큐 확인 | ss -tlnp 'sport = :8080' 로 Recv-Q 적체 관찰 |
tail -f catalina.out | 배포 로그 실시간 추적 | tail -f catalina.out | grep -E "INFO|ERROR|SEVERE" |
grep "Server startup in" | 기동 완료 확인 | grep "Server startup in" catalina.out | tail -3 |
grep OutOfMemoryError | OOM 발생 확인 | grep java.lang.OutOfMemoryError catalina.out | tail -20 |
jstat -gc <pid> | GC·힙 사용량 확인 | jstat -gc $(pgrep -f catalina) 5000 3 |
kill -3 <pid> | 스레드 덤프(→catalina.out) | 응답 느릴 때 워커가 어디서 막혔는지 |
curl -w "%{http_code}" | 헬스체크 상태코드 | curl -s -o /dev/null -w "%{http_code}" .../myapp/health |
jar -tf myapp.war | WAR 내부 목록 확인 | jar -tf myapp.war | grep WEB-INF/lib (JAR 충돌 추적) |
awk '$NF > 5000' | 슬로우 요청 추출 | awk '$NF>5000' localhost_access_log.*.txt | tail |
curl .../manager/status?XML=true | 스레드 상태 확인 | currentThreadsBusy vs maxThreads 비교 |
rm -rf work/Catalina/localhost/<app> | JSP·클래스 캐시 삭제 | 배포 충돌 해소(중지 후 삭제) |
systemctl restart tomcat | 재시작(lib·URIEncoding 변경 시) | systemctl status tomcat 로 상태 확인 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
grep -i member catalina.out | 클러스터 멤버십 로그 확인 | Member added 나오면 멀티캐스트 성공 |
ss -ulnp | grep 45564 | 멀티캐스트 UDP 포트 확인 | 복제 TCP는 ss -tlnp | grep 4000 |
redis-cli ping | Redis 생존 확인 | PONG 이어야 세션 외부화 동작 |
redis-cli keys 'spring:session:sessions:*' | 저장된 세션 조회 | redis-cli keys '...' | wc -l 로 세션 수 |
redis-cli ttl <key> | 세션 만료까지 남은 초 | -1(무기한 누적 위험)·-2(없음) 구분 |
redis-cli hgetall <key> | 세션 내용 확인 | Hash 필드로 저장됨 |
redis-cli info replication | Redis 역할·복제 상태 | role, connected_slaves |
nginx -T | grep -A5 upstream | upstream·ip_hash 반영 확인 | sticky 설정 적용 여부 |
nginx -t && systemctl reload nginx | 문법검사 후 무중단 반영 | 두 줄 OK 확인 후 reload |
curl -c/-b <cookiefile> | 쿠키 유지 반복 요청 | JSESSIONID .tomcat1 접미사 sticky 확인 |
ip link show | grep MULTICAST | 멀티캐스트 지원 인터페이스 | address="auto" 오선택 진단 |
find webapps -name web.xml | <distributable/> 확인 | -exec grep -l distributable {} \; 없으면 복제 안 됨 |
firewall-cmd --add-port=45564/udp | 클러스터 포트 개방 | --permanent 후 --reload |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
jps -l | 실행 중 Java 프로세스·PID | 대상 Tomcat PID 특정 |
jstat -gcutil <pid> 1000 | GC 통계 실시간 | jstat -gcutil <pid> 2000 5 (Old Gen·FGC 추이) |
jstack <pid> | 스레드 덤프 | jstack <pid> | grep -A5 BLOCKED (락 경합) |
jmap -dump:format=b,file=… | 힙 덤프 생성 | jmap -dump:format=b,file=/tmp/heap.hprof <pid> |
jcmd <pid> GC.run | 수동 Full GC 유도 | jcmd <pid> VM.native_memory (off-heap 내역) |
kill -3 <pid> | 스레드 덤프(→catalina.out) | jstack 못 쓸 때 대체 |
top -H -p <pid> | 스레드별 CPU 확인 | GC 스레드가 CPU 점유 중인지 |
which jps jstat jstack jmap | JDK 진단 도구 존재 확인 | JRE만 있으면 도구 없음 |
grep 'Pause Full' gc.log | Full GC 정지시간 확인 | pause 길면 응답 지연 원인 |
grep 'Thread.State:' | uniq -c | 상태별 스레드 집계 | ... | awk '{print $NF}' | sort | uniq -c |
kubectl describe pod / dmesg | 커널 OOMKill 판별 | exit 137이면 OOMKilled·dmesg의 Killed process java |
grep HeapDumpOnOutOfMemoryError setenv.sh | 자동 덤프 옵션 확인 | 없으면 추가 후 다음 재시작에 적용 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
openssl x509 -in cert.pem -noout -text | 인증서 상세(CN·Issuer) | openssl x509 -in cert.pem -noout -text | grep -E 'Subject:|Not After' |
openssl x509 -in cert.pem -noout -dates | 만료일 확인 | -enddate 로 notAfter만 출력 |
openssl s_client -connect host:443 | 원격 인증서 조회 | openssl s_client -connect host:443 -showcerts (전체 체인) |
openssl s_client … -status | OCSP stapling 확인 | 출력에 OCSP Response Status: successful |
openssl pkcs12 -in cert.pfx -nokeys … | PFX→PEM(인증서) | 개인키는 openssl pkcs12 -nocerts -nodes |
openssl pkcs12 -export … | PEM→PFX(Tomcat용) | -in fullchain.pem -inkey privkey.pem -out cert.pfx |
keytool -list -v -keystore <ks> | keystore 내용 확인 | keytool -list -v -keystore keystore.jks |
keytool -importkeystore … | PFX→JKS 변환 | -srcstoretype PKCS12 -deststoretype JKS |
openssl … -modulus | md5sum | 인증서·개인키 페어 일치 | x509와 rsa의 modulus 해시 비교 |
grep -c 'BEGIN CERTIFICATE' cert.pem | 체인 포함 개수 확인 | 1=단독 cert, 2+=fullchain |
cat cert.pem chain.pem > fullchain.pem | 체인 파일 합성 | 중간 CA 누락 오류 해결 |
nginx -t && systemctl reload nginx | 무중단 교체 반영 | Nginx는 reload, Tomcat은 재시작 필요 |
ss -tlnp | grep ':443' | 443 SSL 리스닝 확인 | 응답 없으면 listen 443 ssl 누락 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
dig <도메인> <타입> | 레코드 조회 | dig A example.com, dig MX example.com |
dig +trace <도메인> | 루트→권한 위임 경로 추적 | 위임이 어디서 끊기는지 확인 |
dig @<서버> <도메인> | 특정 DNS에 직접 질의 | dig @8.8.8.8 example.com (전파 확인) |
dig SOA <도메인> | 존 SOA·네거티브 TTL 확인 | NXDOMAIN 캐시 시간 = SOA minimum |
nslookup <도메인> | 간단 조회 | 응답의 Server(어느 DNS로 조회됐는지) |
getent hosts <도메인> | OS 최종 이름 해석 | hosts+DNS 우선순위 반영 결과 |
grep hosts /etc/nsswitch.conf | 해석 우선순위 확인 | files dns 순서여야 hosts 우선 |
resolvectl status | 현재 DNS 서버·도메인 | systemd-resolved 환경 |
systemd-resolve --flush-caches | DNS 캐시 비우기 | 변경 후 새 IP 즉시 확인 |
nscd --invalidate=hosts | nscd hosts 캐시 무효화 | systemctl restart nscd 로도 |
curl -v http://<도메인>/ | 실제 연결 IP 확인 | Trying <ip> 로 hosts 적용 검증 |
host <도메인> | 짧은 레코드 조회 | 빠른 확인용 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
nginx -T | grep -A20 upstream | upstream 풀·알고리즘 확인 | max_fails·weight·fail_timeout 검토 |
nginx -t && systemctl reload nginx | 문법검사 후 무중단 반영 | Failover 시 연결 큐 초기화 |
curl -v http://<VIP>/health | LB 경유 헬스 확인 | 502=백엔드 전체 장애, 504=응답 초과 |
curl http://<백엔드>:8080/actuator/health | 백엔드 직접 확인(LB 우회) | UP/DOWN JSON 확인 |
ip addr show | VIP 보유 여부 확인 | ip addr show | grep secondary (VIP=secondary) |
systemctl status keepalived | keepalived 역할·상태 | MASTER/BACKUP 확인 |
journalctl -u keepalived | MASTER/BACKUP 전환 이력 | journalctl -u keepalived | grep -E "MASTER|BACKUP" |
tcpdump -i eth0 vrrp | VRRP 광고 수신 확인 | 스플릿브레인(proto 112 차단) 진단 |
ss -tlnp | grep :80 | Nginx 리스닝 주소 확인 | 0.0.0.0 또는 VIP에서 listen하는지 |
ss -s | 현재 연결 수 집계 | netstat -an | grep ESTABLISHED | wc -l 로도 |
curl http://localhost:8404/stats | HAProxy 통계 페이지 | 백엔드 UP/DOWN 상태(설정 필요) |
grep upstream error.log | Nginx upstream 에러 | grep upstream /var/log/nginx/error.log | tail |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
nc -zv | TCP 포트 오픈 여부(방화벽 통과) 확인 | nc -zv 10.10.3.10 3306 (succeeded/refused/timeout 구분) |
telnet | 구형 서버에서 포트 연결 테스트 | telnet 10.10.3.10 3306 (Connected=통과) |
curl -m | HTTP 서비스까지 응답 확인(타임아웃 지정) | curl -m 5 http://was:8080/health |
firewall-cmd --list-all | firewalld 현재 존·포트 상태 확인 | sudo firewall-cmd --list-all |
firewall-cmd --add-port | 포트 영구 오픈 후 리로드 | --add-port=8080/tcp --permanent 뒤 --reload |
firewall-cmd --query-port | 특정 포트 오픈 여부 조회 | sudo firewall-cmd --query-port=3306/tcp |
iptables -L -n | iptables 규칙 확인(번호 포함) | sudo iptables -L INPUT -n --line-numbers | grep 3306 |
ufw | Ubuntu 방화벽 상태·허용·차단 | ufw status verbose / ufw allow 8080/tcp |
ss -tlnp | 서비스 바인딩 주소 확인(127.0.0.1 vs 0.0.0.0) | sudo ss -tlnp | grep 3306 |
ausearch / sestatus | SELinux 차단 여부 진단 | sudo ausearch -m avc -ts recent | grep 3306 |
semanage port -a | SELinux 포트 허용 등록 | semanage port -a -t mysqld_port_t -p tcp 3306 |
sysctl net.netfilter.nf_conntrack_* | conntrack 사용량·상한 비교(table full 진단) | sysctl net.netfilter.nf_conntrack_count net.netfilter.nf_conntrack_max |
mysql -h | 방화벽 통과 후 DB 앱 연결 검증 | mysql -h db-server -u appuser -p -e "SELECT 1" |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
export http_proxy / no_proxy | 셸·curl·wget·Python용 프록시 지정과 우회 대상 설정 | export http_proxy=http://10.10.1.100:3128 / export no_proxy=10.0.0.0/8,localhost |
curl -x | 환경변수와 무관하게 프록시 명시해 접속 | curl -x http://10.10.1.100:3128 -v https://api/health |
-Dhttp.proxyHost (JVM) | Java는 env 무시 → 시스템 프로퍼티로 프록시 지정 | java -Dhttp.proxyHost=10.10.1.100 -Dhttp.proxyPort=3128 -jar app.jar |
squid -k parse / reconfigure | Squid 설정 문법검증·무중단 재적용 | sudo squid -k parse 뒤 sudo squid -k reconfigure |
tail -f access.log | Squid 요청 실시간 추적 | tail -f /var/log/squid/access.log |
grep TCP_DENIED | ACL에 막힌 요청만 필터 | grep TCP_DENIED /var/log/squid/access.log |
iptables -t nat -A POSTROUTING | SNAT·마스커레이드(내부→외부 출발지 변환) | -s 192.168.10.0/24 -o eth0 -j MASQUERADE |
iptables -t nat -A PREROUTING | DNAT 포트포워딩(외부→내부 목적지 변환) | --dport 8080 -j DNAT --to-destination 192.168.10.11:8080 |
iptables -t nat -L -n -v | 현재 NAT 규칙·패킷 카운터 확인 | sudo iptables -t nat -L -n -v |
sysctl net.ipv4.ip_forward | 라우터·NAT 서버 IP 포워딩 활성화 | echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward |
env | grep -i proxy | 현재 프록시 관련 환경변수 점검 | env | grep -iE "proxy|no_proxy" |
ps aux | grep java | 앱 JVM에 프록시 옵션이 실렸는지 확인 | ps aux | grep java | tr ' ' '\n' | grep proxy |
sysctl net.ipv4.ip_local_port_range | SNAT 임시포트 고갈 진단(포트 범위 확인) | ss -s로 time-wait 수와 함께 비교 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
curl -X | HTTP 메서드 지정 호출 | curl -X DELETE https://api.example.com/users/123 |
curl -H | 인증·형식 헤더 추가 | -H "Authorization: Bearer $TOKEN" / -H "Content-Type: application/json" |
curl -d | 요청 바디 전송(자동 POST) | -d @body.json 또는 -d '{"name":"a"}' |
curl -w "%{http_code}" | 응답 상태코드만 추출 | curl -o /dev/null -s -w "%{http_code}\n" URL |
curl -w "%{time_total}" | 응답 시간 측정(성능 이상) | curl -o /dev/null -s -w "%{time_connect} %{time_total}\n" URL |
curl -i / -v | 응답 헤더 포함 / 요청·응답 전체 디버그 | curl -i URL / curl -v URL 2>&1 | head -40 |
jq | JSON 응답 파싱·필터 | jq '.[] | select(.userId==1)' / jq length |
jq -r | 따옴표 없는 원시 값 추출(변수 대입용) | TOKEN=$(curl -s ... | jq -r .access_token) |
cut -d. -f2 + base64 -d | JWT payload 디코드 | echo $TOKEN | cut -d. -f2 | base64 -d | jq .exp |
date -d @ | epoch(exp) → 사람이 읽는 시각 변환 | date -d @1730000000 |
timedatectl status | 서버 시간 확인(토큰 만료 오판 방지) | timedatectl status | grep "Local time" |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
nginx -T | 실행 중 Nginx 전체 설정 덤프 | nginx -T | grep -E "limit_req_zone|limit_req " |
curl -o /dev/null -w "%{http_code}" (반복) | Rate Limiting 동작 테스트(429 유발) | for i in $(seq 1 15); do curl -s -o /dev/null -w "%{http_code}\n" URL; done |
nc -l | 임시 수신 서버로 Webhook 원문 확인 | nc -l -p 8888 (다른 창에서 curl POST) |
curl -X POST -d | Webhook 발송 시뮬레이션 | curl -X POST -H "X-Event-ID: evt-001" -d '{"event":"payment.done"}' URL |
curl -w "%{time_total}" | 수신 서버 2초 응답 초과 여부 측정 | curl -w "%{time_total}s\n" -X POST -d '{}' URL/webhook |
nc -zv | Gateway→백엔드 TCP 연결 확인 | nc -zv 192.168.10.11 8080 |
curl -v (백엔드 직결) | Gateway 우회로 502 원인 격리 | curl -v http://192.168.10.11:8080/actuator/health |
grep upstream error.log | 502/504 업스트림 오류 추적 | grep "upstream" /var/log/nginx/error.log | tail -20 |
redis-cli SET ... NX EX | 멱등키로 중복 이벤트 차단 | redis-cli SET webhook:evt-001 1 NX EX 86400 ((nil)=이미 처리됨) |
curl -vI | Webhook URL의 HTTPS·TLS 확인 | curl -vI https://our-server.com/webhook 2>&1 | grep -E "SSL|TLS" |
systemctl status | Gateway 프로세스 상태 확인 | systemctl status nginx kong |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
nc -zv | 1단계 — L4 포트·방화벽 도달 확인 | nc -zv external-api.example.com 443 |
openssl s_client -connect | 2단계 — TLS 핸드셰이크·인증서 체인 검증 | openssl s_client -connect host:443 2>/dev/null | grep "Verify return code" |
openssl x509 -noout -dates | 서버 인증서 만료일 확인 | openssl s_client -connect host:443 2>/dev/null | openssl x509 -noout -dates |
openssl s_client -showcerts | 중간 CA 포함 인증서 체인 추출 | openssl s_client -connect host:443 -showcerts |
curl -m -w "%{http_code}" | 3단계 — HTTP 응답코드·시간 확인 | curl -m 10 -s -o /dev/null -w "%{http_code} (%{time_total}s)\n" URL |
keytool -list -v | JKS·TrustStore 내용·만료·alias 확인 | keytool -list -v -keystore client.jks -storepass PW | grep -E "Alias|until" |
keytool -importcert | TrustStore에 외부·중간 CA 추가(PKIX 해결) | keytool -importcert -keystore truststore.jks -alias ca -file ca.crt |
openssl pkcs12 -export | PEM+개인키 → PKCS12로 묶기 | openssl pkcs12 -export -in client.crt -inkey client.key -out client.p12 |
keytool -importkeystore | PKCS12 → JKS 변환 | -srckeystore client.p12 -srcstoretype PKCS12 -destkeystore client.jks |
dig +short | 방화벽 등록용 목적지 IP 조회 | dig +short external-api.example.com |
traceroute | 어느 홉에서 막히는지 경로 확인 | traceroute external-api.example.com |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
base64 -d + xmllint --format | SAMLResponse 디코드·XML 정렬 출력 | echo "$SAML" | base64 -d | xmllint --format - |
grep -E "NameID|NotOnOrAfter" | 어설션 핵심 필드·유효시간 확인 | ... | grep -E "NameID|Attribute|InResponseTo|NotOnOrAfter" |
timedatectl status / date -u | 어설션 만료 오판용 서버 시간 확인 | timedatectl status | grep synchronized / date -u |
curl -X POST .../token | OAuth code→access_token 교환 | -d "grant_type=authorization_code" -d "code=..." -d "client_secret=..." |
cut -d. -f2 + base64 -d | access_token(JWT) payload 디코드 | echo $TOKEN | cut -d. -f2 | base64 -d | python3 -m json.tool |
curl -H "Authorization: Bearer" | 발급 토큰으로 userinfo 조회 | curl -H "Authorization: Bearer $TOKEN" .../userinfo |
curl .../saml/descriptor | IdP SAML 메타데이터 조회 | curl -s URL | xmllint --format - | grep -E "EntityID|X509Certificate" |
curl .../.well-known/openid-configuration | OIDC 엔드포인트 자동 확인 | curl -s URL | python3 -m json.tool | grep endpoint |
curl -vI | ACS URL의 HTTPS·외부 접근성 확인 | curl -vI https://our-app.com/saml/acs 2>&1 | grep -E "HTTP/|SSL" |
grep -r InResponseTo | SP 로그에서 SSO 거부 원인 추적 | grep -r "InResponseTo|unsolicited" /var/log/app/ |
docker run keycloak | 로컬 테스트용 IdP 기동 | docker run -p 8080:8080 -e KEYCLOAK_ADMIN=admin quay.io/keycloak/keycloak start-dev |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
telnet <서버> 25 | SMTP 포트 열림·응답 확인 | 220 ESMTP 나오면 정상, EHLO로 기능 확인 |
openssl s_client ... -starttls smtp | 587 STARTTLS·인증서 검증 | openssl s_client -connect smtp:587 -starttls smtp |
swaks | 실제 메일 발송 테스트 | swaks --to a@x.com --server smtp --port 587 --auth LOGIN --tls |
dig TXT | SPF/DKIM/DMARC 레코드 조회 | dig TXT _dmarc.example.com +short |
mailq / postqueue -p | Postfix 발송 큐 확인 | postqueue -f로 큐 강제 재시도 |
postcat -q <큐ID> | 큐에 걸린 메일 내용 열람 | postcat -q 3A1B2C4D |
postsuper -d ALL | 미발송 큐 전체 삭제(주의) | 특정만: postsuper -d <큐ID> |
postconf -e | main.cf 설정 항목 변경 | postconf -e "relayhost = [smtp]:587" |
postmap | sasl_passwd 해시 DB 생성 | postmap /etc/postfix/sasl_passwd |
tail -f /var/log/maillog | 발송 결과 실시간 추적 | status=sent·bounced·deferred 확인 |
nc -zv <서버> 587 | 릴레이 포트 도달 확인 | nc -zv smtp-server 587 |
curl -X POST | SMS 게이트웨이 API 호출 | -H "Authorization: Bearer <API_KEY>" -d '{...}' |
systemctl reload postfix | 설정 변경 반영(무중단) | reload는 큐 유지, 재시작 불필요 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
sftp -i <키> user@host | 키 기반 대화형 접속 | 접속 후 put/get/ls/cd |
sftp -b <명령파일> | 배치(비대화) 자동 전송 | sftp -o BatchMode=yes -b cmds.txt user@host |
put / get | 업로드 / 다운로드 | put data.csv → ls -la data.csv로 크기 확인 |
ssh-keygen -t ed25519 | 배치 전용 키 쌍 생성 | ssh-keygen -t ed25519 -f ~/.ssh/sftp_key -N "" |
chmod 600 <개인키> | 개인키 권한 잠금(필수) | 644면 "Permissions too open"으로 거부 |
ssh ... stat -c%s | 원격 파일 크기 비교 | 로컬 stat -c%s와 대조해 전송 완료 확인 |
md5sum | 체크섬 무결성 대조 | 로컬·원격 해시가 같아야 정상 |
ssh-keygen -F <host> | known_hosts의 옛 지문 조회 | 호스트 키 변경 여부 확인 |
ssh-keygen -R <host> | 바뀐 호스트 키 항목 제거 | 대역 외 지문 검증 후에만 실행 |
ssh-keyscan | 호스트 키 수집(주의) | 무작정 덮으면 MITM 노출 — 지문 검증 병행 |
sftp -vvv | 접속 실패 디버깅 | 인증·호스트키 단계 로그 확인 |
rsync -avP | 대용량 증분·이어받기 동기화 | rsync -avP dir/ user@host:/dir/ |
restorecon -Rv | SELinux 컨텍스트 복구(RHEL) | .ssh 키 인증 거부 시 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
nc -zv <host> <port> | DB 포트 도달·방화벽 확인(첫 단계) | nc -zv db-server 3306 |
mysql -h -u -p -e | MySQL 접속·쿼리 테스트 | mysql -h db -u appuser -p -e "SELECT 1" |
psql -h -U -d -c | PostgreSQL 접속 테스트 | psql -h db -U appuser -d mydb -c "SELECT 1" |
sqlplus | Oracle 접속 테스트 | sqlplus appuser/pw@//db:1521/ORCL |
SHOW GRANTS | 계정 권한 최소화 확인 | SHOW GRANTS FOR 'appuser'@'%' (DDL 있으면 위험) |
SHOW PROCESSLIST | 실행 중 느린 쿼리 식별 | Time 큰 쿼리가 커넥션 점유 원인 |
grep HikariPool | Pool 소진 여부 로그 판독 | active=max, waiting>0이면 소진 |
grep -r socketTimeout | 타임아웃 파라미터 누락 점검 | grep -r 'socketTimeout' /opt/app/config/ |
jstack <PID> | WAS 스레드 블로킹 덤프 | jstack <PID> | grep -A10 BLOCKED |
kill -3 <PID> | JVM 스레드 덤프(로그로 출력) | 스레드가 socketRead0에 묶였는지 확인 |
SHOW STATUS LIKE 'Threads_connected' | DB 측 연결 수 포화 확인 | max_connections 근접 시 DB 포화 |
SHOW VARIABLES LIKE 'wait_timeout' | max-lifetime 기준값 확인 | max-lifetime을 이 값보다 짧게 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
redis-cli ping | 연결 확인(첫 단계) | PONG이면 정상, -h <host> -p 6379로 원격 |
redis-cli info memory | 메모리·단편화 확인 | used_memory_human·mem_fragmentation_ratio |
redis-cli dbsize | 전체 키 수 확인 | 급증이면 TTL 누락·키 폭증 의심 |
redis-cli info keyspace | DB별 keys·expires·ttl | expires가 0이면 TTL 미설정 |
redis-cli slowlog get 10 | 느린 명령어 추적 | KEYS·대형 SORT 보이면 위험 |
redis-cli --scan --pattern | 운영 안전 키 조회(KEYS 대체) | redis-cli --scan --pattern "session:*" |
redis-cli config set | 무중단 정책 변경 | config set maxmemory-policy allkeys-lru |
redis-cli monitor | 실시간 명령 확인(짧게만) | 운영 트래픽에선 성능 영향 |
curl _cluster/health | ES 클러스터 상태 확인 | curl <es>:9200/_cluster/health?pretty |
curl _cat/health?v | 상태 한 줄 요약 | status가 green/yellow/red |
curl _cat/nodes?v | 노드 heap·disk 확인 | disk.used_percent 95% 넘으면 쓰기 차단 |
curl _cat/shards | 미할당 샤드 식별 | | grep UNASSIGNED로 Yellow/Red 원인 추적 |
curl _cluster/allocation/explain | 샤드 미할당 원인 상세 | ?pretty로 이유 확인 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
crontab -l | 등록된 스케줄 확인 | crontab -l -u appuser (특정 사용자) |
crontab -e | 스케줄 편집 | 0 2 * * * = 매일 새벽 2시 |
grep CRON /var/log/syslog | cron 실행 여부 추적 | RHEL은 /var/log/cron |
journalctl -u cron | systemd cron 실행 로그 | journalctl -u cron --since today |
systemctl status crond | cron 데몬 기동 확인 | 기록 없으면 데몬·시각부터 확인 |
ps aux | grep batch | 실행 중 배치 프로세스 확인 | 없으면 완료·비정상 종료 |
timedatectl | 서버 타임존 확인 | 새 서버 스케줄 어긋남의 첫 점검 |
java -jar ... run.id= | Spring Batch 재실행(고유 파라미터) | run.id=$(date +%s%N) 또는 $(uuidgen) |
SELECT * FROM QRTZ_LOCKS | Quartz Lock 상태 확인 | QRTZ_SCHEDULER_STATE로 죽은 노드 탐지 |
DELETE FROM QRTZ_SCHEDULER_STATE | 죽은 노드 Lock 수동 해제(신중) | INSTANCE_NAME='dead-node' 지정 |
SELECT ... BATCH_JOB_EXECUTION | 배치 실행 이력·결과 조회 | STATUS/EXIT_CODE로 성공·실패 판정 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
env | grep | 주입된 설정 환경변수 확인 | env | grep -E "SPRING|DB" |
printenv | 특정 환경변수 값 재확인 | printenv | grep DB |
cat /proc/<PID>/environ | 실행 중 프로세스의 실제 환경변수 | cat /proc/<PID>/environ | tr '\0' '\n' |
pgrep -f <앱> | 앱 PID 찾기 | pgrep -f myapp.jar |
ps aux | grep profiles.active | 활성 프로파일 확인 | -Dspring.profiles.active=prod 있는지 |
jps -v | JVM 기동 옵션 전체 확인 | jps -v | grep Catalina |
curl actuator/env | 최종 채택된 설정값 소스 확인 | curl localhost:8080/actuator/env |
git ls-files .env | 비밀 파일 커밋 여부 점검 | 한 줄이라도 나오면 즉시 조치 |
git rm --cached .env | 추적 제거(파일은 유지) | 이후 .gitignore에 추가 |
git log --all --full-history | 비밀 파일 커밋 이력 감사 | git log --all --full-history -- .env |
chmod 750 setenv.sh | setenv.sh 권한 잠금 | 644면 다른 계정이 비밀 열람 |
systemctl restart tomcat | 설정 반영 재기동 | 무중단은 LB Drain 후 재기동 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
git tag -a | 릴리즈 기준점(annotated) 생성 | git tag -a v1.2.0 -m "Release v1.2.0" |
git push origin <태그> | 태그 원격 반영 | 브랜치 먼저 push 후 태그 push |
git describe --tags | 현재 커밋의 최근 태그 확인 | git describe --tags --abbrev=0 |
git log --oneline v0.9.0..v1.0.0 | 릴리즈 간 변경·롤백 범위 | git diff --name-only로 파일까지 |
git revert <SHA> | 공유 브랜치 안전 롤백(이력 보존) | main/develop은 항상 revert |
git reset --hard <SHA> | 로컬 브랜치 되돌리기(주의) | 혼자 쓰는 feature 브랜치만 |
git merge | 브랜치 통합 | 충돌 시 git mergetool·마커 편집 |
git status | grep "both modified" | 충돌 파일 식별 | 이후 git add로 해결 표시 |
git commit -m "<type>: 요약 (#N)" | 컨벤션 커밋·이슈 연결 | fix: 세션 쿠키 누락 (#78) |
git log --author --since | 작성자·기간별 이력 추적 | git log --oneline --author="minjun" |
git submodule update --init --recursive | 빈 서브모듈 폴더 채우기 | 클론 후 라이브러리 비면 실행 |
git submodule status | 부모가 가리키는 SHA 대조 | 옛 SHA면 부모에서 add·커밋 |
git log --follow -- <파일> | 설정 파일 변경 이력 조회 | git show <SHA>:config/application-prod.yml |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
mvn clean package | Maven 빌드(compile→test→package) | mvn -o clean package -DskipTests -Pprod (오프라인·테스트생략·prod 프로파일) |
mvn -B | CI 배치 모드(프롬프트 없음) | mvn clean package -DskipTests -B |
mvn -U | 원격 최신 의존성 강제 갱신 | 캐시 오염 의심 시 mvn clean package -U |
mvn dependency:tree | 의존성 트리·충돌 확인 | mvn dependency:tree | grep "omitted for conflict" |
mvn dependency:analyze | 미사용·누락 의존성 점검 | 런타임 ClassNotFound 추적 |
./gradlew clean build | Gradle Wrapper 빌드(버전 고정) | ./gradlew clean build -x test (테스트 제외) |
./gradlew dependencies | Gradle 의존성 트리 | ./gradlew bootJar / bootWar (산출물 생성) |
npm ci | lock 기준 재현 설치(CI) | node_modules 삭제 후 package-lock.json 그대로 설치 |
npm run build | 프론트엔드 운영 빌드 | 산출물 dist/·build/에 정적 파일 생성 |
pnpm install --frozen-lockfile | pnpm CI 설치(lock 고정) | 이어서 pnpm run build |
ls -lh target/ | 빌드 산출물 크기 확인 | ls -lh target/*.war target/*.jar |
unzip -p … MANIFEST.MF | WAR/JAR 내부 버전 추적 | unzip -p target/myapp.war META-INF/MANIFEST.MF |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
mysqldump | DDL 전 논리 백업(필수) | mysqldump mydb users > users_$(date +%F).sql |
SHOW TABLE STATUS | 행수·크기로 Lock 시간 예측 | information_schema.tables에서 size_mb 조회 |
SHOW FULL PROCESSLIST | 실행 중 세션·장시간 쿼리 확인 | Time 60초 이상 쿼리 있으면 DDL 보류 |
time mysql < file.sql | 스테이징에서 DDL 시간 측정 | 운영 반영 전 Lock 시간 산정 |
ALTER TABLE | 소용량 직접 스키마 변경 | ALTER TABLE users ADD COLUMN phone VARCHAR(20) NULL |
pt-online-schema-change | 대용량 무중단 ALTER(1000만 건↑) | --alter "ADD COLUMN ..." --execute --max-lag=1 |
pt-osc --dry-run | 실행 전 계획·외래키 처리 확인 | --alter-foreign-keys-method 사전 점검 |
mvn flyway:migrate | Flyway 마이그레이션 반영 | mvn flyway:info (Pending/Success 확인) |
mvn flyway:repair | 실패·체크섬 불일치 이력 복구 | 실패 마이그레이션 정리 후 재적용 |
SELECT … flyway_schema_history | 환경별 반영 버전 추적 | ORDER BY installed_rank DESC LIMIT 5 |
KILL <세션ID> | metadata lock 유발 세션 종료 | 블로킹 세션 확인 후 KILL 12345 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
cp (백업) | 배포 전 현재 산출물 백업 | cp myapp.war /opt/backup/myapp_$(date +%F).war |
systemctl stop/start | WAS·서비스 재기동 | systemctl stop tomcat → 배포 → systemctl start tomcat |
systemctl status | 프로세스 active·PID 확인 | systemctl status tomcat --no-pager | head |
find ... -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + | 승인한 exploded WAR 캐시 항목 정리 | 대상 목록·경로·백업 확인 후에만 실행 |
rsync -avz --delete | 정적파일 변경분만 전송 | rsync -avz --delete dist/ /var/www/myapp/ |
nginx -t && reload | 설정 검증 후 무중단 반영 | nginx -t && systemctl reload nginx |
curl -w '%{http_code}' | 배포 후 헬스체크 | curl -s -o /dev/null -w '%{http_code}' http://localhost:8080/myapp/health |
tail -f catalina.out | 기동 로그 실시간 확인 | tail -f catalina.out | grep -m1 "Server startup" |
ss -tlnp | 포트 점유 프로세스 확인 | ss -tlnp | grep :8080 (BindException 진단) |
unzip -p … MANIFEST.MF | 배포된 버전 확인 | unzip -p myapp.war META-INF/MANIFEST.MF | grep Version |
ln -sfn + mv -T | current 링크 원자적 교체 | ln -sfn releases/20260706 current_tmp && mv -T current_tmp current |
journalctl -u | JAR 서비스 기동 로그 | journalctl -u myapp -n 30 --no-pager |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
docker pull | 이미지 내려받기 | docker pull myregistry/myapp:1.4.2 (명시 버전 태그) |
docker ps | 실행 중 컨테이너·상태 확인 | docker ps --format 'table {{.Names}}\t{{.Status}}' |
docker logs | 컨테이너 로그(=tail -f) | docker logs --tail 100 -f myapp |
docker stats | 실시간 리소스(MEM/CPU) | docker stats --no-stream |
docker exec -it | 컨테이너 내부 진입·디버깅 | docker exec -it myapp /bin/sh |
docker inspect --format | 상태·헬스 필드 추출 | docker inspect --format '{{.State.Health.Status}}' myapp |
docker-compose up -d | 서비스 백그라운드 기동 | docker-compose up -d --force-recreate |
docker-compose pull && up -d | 이미지 교체 배포 | docker-compose pull && docker-compose up -d |
docker-compose ps | 서비스 State 확인 | Up / Exited(1) / Restarting 판별 |
docker-compose logs | 서비스 로그 | docker-compose logs --tail 30 -f app |
--restart unless-stopped | 재부팅·크래시 자동 재시작 | docker run --restart unless-stopped ... |
docker image prune -f | 미사용 이전 이미지 정리 | 배포 후 디스크 확보 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
systemctl daemon-reload | unit 파일 변경 반영(필수) | 파일 수정 후 daemon-reload → start |
systemctl enable --now | 부팅 자동시작 등록 + 즉시 기동 | systemctl enable --now myapp |
systemctl start/stop/restart | 서비스 기동·중지·재시작 | systemctl restart myapp |
systemctl status | 상태·최근 로그 확인 | systemctl status myapp --no-pager | head -20 |
systemctl is-enabled | 부팅 자동시작 여부 확인 | 결과가 enabled여야 재부팅 후 생존 |
systemctl reset-failed | StartLimit 초과 카운터 리셋 | reset-failed myapp → start |
systemctl show -p After | 의존·순서 설정 점검 | systemctl show myapp -p After (network-online 누락 확인) |
systemctl cat | 등록된 unit 내용 확인 | systemctl cat myapp |
journalctl -u | 서비스 상세 로그 | journalctl -u myapp -n 50 --no-pager |
journalctl -u -b | 이번 부팅 로그만 | journalctl -u myapp -b (부팅 시점 경합 진단) |
systemd-analyze critical-chain | 기동 순서·시점 분석 | systemd-analyze critical-chain myapp.service |
ss -tlnp | 포트 충돌 확인 | ss -tlnp | grep :8080 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
mkdir -p + cp | 날짜별 사전 백업 | BACKUP_DIR=/opt/backup/$(date +%F_%H%M); mkdir -p $BACKUP_DIR |
ps aux | grep | 작업 전 프로세스 스냅샷 | ps aux | grep -E 'tomcat|nginx|java' > ps.txt |
df -h | 배포 여유 디스크 확인 | 산출물 크기의 3배 이상 여유 확인 |
free -m | 메모리 기준선 기록 | 작업 전후 비교용 스냅샷 |
ss -tlnp | 포트 사용 현황 기록 | ss -tlnp > ports.txt |
systemctl status | 서비스 상태 스냅샷 | systemctl status tomcat nginx |
awk (access.log) | 시간대별 트래픽·피크 분석 | awk '{print substr($4,14,2)}' access.log | sort | uniq -c | sort -rn |
grep proxy_pass | 연관 서비스(프록시) 파악 | grep proxy_pass /etc/nginx/conf.d/*.conf |
curl -w '%{http_code}' | 작업 후 헬스체크 | curl -s -o /dev/null -w '%{http_code}' http://localhost:8080/myapp/health |
grep " 500 " access.log | 배포 후 5xx 에러 확인 | grep " 500 " /var/log/nginx/access.log | tail |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
systemctl stop/start | 롤백 위한 WAS 재기동 | systemctl stop tomcat → WAR 교체 → start |
ps aux | grep tomcat | 완전 종료 확인 | sleep 3 && ps aux | grep tomcat | grep -v grep (없어야 정상) |
cp (백업 복원) | 이전 WAR·설정 되돌리기 | cp /opt/backup/20260530/myapp_current.war …/myapp.war |
rm -rf webapps/앱* | 실패한 배포물 제거 | rm -rf /opt/tomcat/webapps/myapp* |
mysql < undo.sql | 스키마 변경 UNDO(역마이그레이션) | mysql myapp_db < /opt/backup/undo_v1.2.0.sql |
SHOW COLUMNS | 현재 스키마 불일치 확인 | SHOW COLUMNS FROM orders; (Unknown column 진단) |
nginx -t && reload | 설정 롤백 검증 후 반영 | nginx -t && systemctl reload nginx |
openssl x509 -noout -dates | 복원 인증서 유효기간 확인 | openssl x509 -noout -dates -in server.crt |
curl -sk -w '%{http_code}' | 롤백 후 HTTPS 헬스체크 | curl -sk https://localhost -o /dev/null -w '%{http_code}' |
md5sum | 백업 WAR 무결성·버전 대조 | 복원 파일과 원본 체크섬 비교 |
git show / scp | 백업 없을 때 이전 산출물 확보 | scp staging:/opt/tomcat/webapps/myapp.war . |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
tail -f | 로그 실시간 추적 | tail -f /var/log/nginx/error.log (502·504 실시간) |
grep -A N | 매칭 줄 + 이후 N줄(스택 트레이스 전체) | grep -A 10 "NullPointerException" catalina.out |
grep -c | 매칭 줄 수(예외 유무 신호용) | grep -c "Exception" catalina.out — 건수 지표론 부정확 |
grep -i | 대소문자 무시 패턴 | grep -i "OutOfMemoryError|GC overhead" catalina.out |
grep -oP | 예외명만 뽑아 집계 | grep -oP '\w+Exception' catalina.out | sort | uniq -c |
awk '$9>=500' | 상태코드 필드로 에러 필터 | awk '$9>=500 {print $9,$7}' access.log | tail |
awk '{print $9}' | sort | uniq -c | 상태코드 분포 집계 | 200·404·500·502 건수 한눈에 |
awk '{print $NF,$7}' | sort -rn | 응답시간 TOP(upstream_response_time) | 느린 요청·URI 상위 10 |
substr($4,…) | 시간대별 분포 | awk '$9==500{print substr($4,14,5)}' access.log | sort | uniq -c |
ss -tlnp | 리슨 포트·PID 확인 | ss -tlnp | grep 8080 (502 포트 불일치) |
systemctl status | 서비스 생사 확인 | systemctl status nginx tomcat |
nginx -t && systemctl reload nginx | 설정 검증 후 무중단 반영 | 413·403·502 설정 수정 후 |
openssl x509 -noout -enddate | 인증서 만료일 확인 | openssl x509 -noout -enddate -in server.crt |
docker exec <c> date | 컨테이너 타임존 확인(로그 시각 대조) | Nginx(KST) vs Tomcat(UTC) 9시간 오차 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
*.* @@host:514 | rsyslog 시스템 로그 TCP 원격 전송(신뢰성) | @host는 UDP(빠르나 유실) |
rsyslogd -N1 -f | rsyslog 설정 문법 검증 | rsyslogd -N1 -f /etc/rsyslog.d/forward.conf |
logger | 전송 테스트용 로그 발생 | logger "test from $(hostname)" 후 수신 확인 |
filebeat test config | Filebeat 설정 문법 검증 | 기동 전 필수 |
filebeat test output | ES/Logstash 연결 확인 | talk to server... OK면 정상 |
systemctl enable --now filebeat | 부팅 등록 + 즉시 기동 | 상태는 systemctl status filebeat |
curl _cat/indices | ES 인덱스 수신 확인 | curl -s 'es:9200/_cat/indices?v' | grep filebeat |
curl _cat/thread_pool/write | ES 색인 큐·거절(rejected) 확인 | 폭주·백프레셔 진단 |
curl _search | 최근 수집 문서 조회 | curl -s 'es:9200/filebeat-*/_search?pretty&size=1' |
grep -iE "429|backoff" | Filebeat 백프레셔·전송 지연 확인 | … /var/log/filebeat/filebeat | tail |
ls -la / chmod o+r | 로그 파일 읽기 권한 진단·부여 | chmod o+r /opt/tomcat/logs/catalina.out |
find /var/lib/filebeat -name '*.json' | registry(읽은 위치) 파일 찾기 | 중복 수집 시 확인 |
rm -rf …/registry | registry 리셋(처음부터 재수집) | 중복 감수, stop 후 실행 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
df -h | 파일시스템 용량(바이트) | 80% 경고·90% 긴급 |
df -i | inode(파일 수 한도) 사용률 | 바이트 남아도 IUse% 100%면 생성 불가 |
du -sh * | sort -rh | 디렉터리별 용량 상위 | du -sh /var/log/* | sort -rh | head |
free -m | 메모리 가용량 | available 컬럼이 핵심 |
top -bn1 / uptime | CPU·load average | uptime으로 1·5·15분 부하 |
ps aux --sort=-%mem | 메모리 상위 프로세스 | ps aux --sort=-%mem | head -6 |
lsof | grep deleted | 삭제됐지만 열린 파일(공간 미회수) | df/du 불일치 원인 |
truncate -s 0 / > | 로그 파일 비우기(삭제 아님) | truncate -s 0 catalina.out — 즉시 회수 |
logrotate -d | 로테이션 시뮬레이션(dry-run) | 설정 검증, 실제 미실행 |
logrotate -f | 강제 로테이션(테스트) | logrotate -f /etc/logrotate.d/nginx |
jstat -gcutil <PID> | JVM Heap·GC 통계 | jstat -gcutil <PID> 1000 5 (O 85%↑ 주의) |
jmap -dump | Heap 덤프(누수 분석) | jmap -dump:format=b,file=/tmp/heap.hprof <PID> |
nginx -s reopen | 로테이션 후 로그 파일 재오픈 | postrotate의 핵심 |
watch -n 5 | 값 변화 주기 관찰 | watch -n 5 "du -sh catalina.out" (재증가 감시) |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
curl …/metrics | JMX Exporter 노출 메트릭 확인 | curl -s host:9090/metrics | grep jvm_memory |
curl …/api/v1/targets | Prometheus 수집 대상 상태 | health:up이면 정상, down이면 lastError |
curl …/api/v1/query?query= | PromQL 즉석 실행 | ?query=up(대상 생사), query=jvm_memory_bytes_used |
promtool check config | prometheus.yml 문법 검증 | 재시작 전 필수 |
systemctl reload prometheus | 설정 무중단 반영 | scrape_config 변경 후 |
ss -tlnp | exporter 포트 리슨 확인 | ss -tlnp | grep 9090 |
ps aux | grep javaagent | -javaagent 반영 여부 | JMX Exporter 미부착 진단 |
firewall-cmd / iptables | 9090을 Prometheus IP만 허용 | 외부 노출 차단 |
up == 0 | 대상 다운 감지 규칙 | up == 0 for 1m |
histogram_quantile(0.99, …) | p99 지연 계산(백분위수는 avg 금지) | histogram_quantile(0.99, sum by(le,instance)(rate(..._bucket[5m]))) |
rate(…_count[5m]) | 초당 증가율(GC·요청) | rate(jvm_gc_collection_seconds_count[5m])*60 |
prometheus_tsdb_head_series | 시계열 수(카디널리티) 감시 | .* 라벨 폭발 조기 감지 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
grep -E "ERROR|WARN|Exception" | 장애 시각대 에러·경고 추출(타임라인 재료) | … catalina.out | grep "2026-05-30 14:" |
grep "2026-05-30 14:" | 특정 시간창만 필터 | 여러 로그를 같은 창으로 맞춰 대조 |
journalctl -u <svc> --since --until | 서비스 로그를 시간창으로 자르기 | journalctl -u tomcat --since "14:00" --until "15:00" |
awk '$9 ~ /^5/' | 5xx만 골라 분당 분포 | awk '$9~/^5/{print substr($4,14,5)}' access.log | sort | uniq -c |
sort | uniq -c | 분·코드별 건수 집계 | 5xx가 0으로 수렴하는 분 = 고객영향 종료 |
grep -A2 "Query_time" | slow query 로그에서 지연 쿼리 | grep -A2 Query_time /var/log/mysql/slow.log |
EXPLAIN <query> | 인덱스 없는 full scan 입증 | 근본원인(인덱스 누락) 확인 |
grep -E "ORA-|SQLException|Connection" | DB 연결·SQL 예외 추출(5-Why 시작점) | … catalina.out | tail -5 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
grep PermitRootLogin + sed -i | root 직접 로그인 차단 | sshd_config를 no로 후 systemctl reload sshd |
awk -F: '$3>=1000' | 일반 사용자 계정 목록 | awk -F: '$3>=1000{print $1,$3,$7}' /etc/passwd |
usermod -L / passwd -S | 계정 잠금·상태 확인 | passwd -S user (L=Locked) |
lastb / last -F | 로그인 실패·성공 이력 | lastb | head -20 |
curl -I | 응답 보안 헤더 확인 | curl -sI https://host | grep -E 'X-Frame|Strict-Transport|Content-Security' |
curl -sI /api | 경로별 헤더 실재 검증 | add_header 치환 상속으로 /api엔 사라졌는지 |
openssl s_client -connect … -tls1 | 구버전 TLS 비활성 확인 | handshake failure면 정상(TLS 1.0 차단) |
openssl s_client -tls1_2 | grep Cipher | 협상 프로토콜·cipher 확인 | ECDHE 있으면 순방향 암호화(PFS) |
openssl dhparam | DH 파라미터 생성 | openssl dhparam -out dhparam.pem 2048 |
grep "Failed password" | grep -oE "from …" | sort | uniq -c | IP별 실패 스프레이 집계 | 무차별 대입 IP 탐지 |
grep "Accepted" | 스프레이 뒤 성공 로그인 확인 | grep Accepted auth.log | grep <IP> — 진짜 위험 신호 |
grep -E "sudo:.*COMMAND=" | 성공 직후 권한 상승 추적 | 계정별 감사 추적 |
server_tokens off | nginx 버전 정보 숨김 | curl -I | grep Server로 Server: nginx만 확인 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
curl -I | CDN 캐시 상태를 응답 헤더로 확인 | curl -sI https://cdn/app.js | grep -iE 'age|cf-cache-status|x-cache' |
curl -v -X POST | WAF에 차단된 요청 재현·검증 | curl -v -X POST https://ex.com/api -d '{"code":"SELECT ..."}' → 403 확인 |
grep ModSecurity | 차단 로그에서 규칙 ID 찾기 | grep 403 /var/log/nginx/error.log | grep ModSecurity | tail |
SecRule … ctl:ruleRemoveById | ModSecurity 예외를 최소 범위로 | ctl:ruleRemoveTargetById=942100;ARGS:code (파라미터만) |
aws wafv2 | AWS WAF 규칙·규칙그룹 관리 | aws wafv2 create-rule-group --scope CLOUDFRONT … |
aws cloudfront create-invalidation | CloudFront 캐시 무효화 | --distribution-id ID --paths "/static/*" |
aws cloudfront list-invalidations | 무효화 진행 상태 확인 | --query 'InvalidationList.Items[0].Status' (InProgress→Completed) |
aws cloudfront wait invalidation-completed | 무효화 완료까지 대기 | 배포 스크립트에서 --id <INVALIDATION_ID> |
curl … /purge_cache | Cloudflare 캐시 무효화 | --data '{"files":["https://ex.com/app.js"]}' (전체는 purge_everything) |
aws s3 sync | 정적 파일 오리진(S3) 업로드 | aws s3 sync ./dist s3://bucket/static/ --delete |
set_real_ip_from / real_ip_header | CDN 뒤 실제 클라이언트 IP 복원 | Nginx real_ip_header CF-Connecting-IP; (신뢰 대역만) |
nginx -t && systemctl reload nginx | 예외·설정 문법 검증 후 무중단 반영 | 예외 규칙 추가 뒤 필수 |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
nmap -sT | 열린 포트 외부 시점 스캔 | nmap -sT -p 1-1024 localhost (불필요 포트 발견) |
ss -tlnp | 리스닝 포트·프로세스 내부 확인 | ss -tlnp | grep 631 (차단 후 빈 줄이면 정상) |
systemctl stop/disable | 불필요 서비스 중지+자동시작 해제 | systemctl disable cups → systemctl is-enabled cups |
yum update --security | OS 보안 패치만 적용 | RHEL/CentOS, Ubuntu는 apt-get upgrade |
rpm -q / openssl version | 실제 설치 버전으로 오탐 판별 | rpm -q openssl (backport면 버전 유지·패치됨) |
nginx -v / java -version | 미들웨어 버전 확인·전후 증적 | nginx -v > before.txt → 패치 → > after.txt |
grep PermitRootLogin | SSH root 직접 로그인 점검 | grep PermitRootLogin /etc/ssh/sshd_config → no |
chage -l / chage -M | 비밀번호 만료 정책 확인·설정 | chage -M 90 <계정> (90일 만료) |
usermod -s /sbin/nologin | 미사용 계정 로그인 차단 | usermod -s /sbin/nologin <계정> |
chattr +a / lsattr | 로컬 로그를 append-only로 잠금 | chattr +a /var/log/secure (덮어쓰기·삭제 차단) |
ausearch | auditd에서 로그 삭제·truncate 추적 | ausearch -f /var/log/secure -k log_tamper |
cat /etc/logrotate.d/nginx | 로그 보존 기간 증적 확인 | rotate 26 = 6개월(ISMS-P 기준) |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
tar -czf / -tzf / -xzf | 설정 파일 묶기·목록 확인·복원 | tar -czf config_$(date +%F).tar.gz /etc/nginx/ |
rsync -avz --delete | 원격 서버로 증분 동기화 백업 | rsync -avz /opt/app/ backup-host:/backup/app/ |
mysqldump --single-transaction | InnoDB 무중단 일관 백업 | mysqldump --single-transaction --all-databases | gzip > db.sql.gz |
mysql < | SQL 덤프에서 DB 복구 | gunzip -c db.sql.gz | mysql -u root -p test_restore |
pg_dump / pg_dumpall | PostgreSQL DB·클러스터 백업 | pg_dump -U postgres mydb > mydb.sql |
gunzip -t | 백업 gzip 무결성 검증 | gunzip -t db.sql.gz (에러 없으면 정상) |
mysqldump --ignore-table | 대용량 로그 테이블 제외 백업 | --ignore-table=mydb.access_log |
lvcreate -s | LVM 스냅샷(작업 전 시점 동결) | lvcreate -L 10G -s -n data_snap /dev/vg0/data |
aws ec2 create-snapshot | EBS 볼륨 스냅샷 생성 | --volume-id vol-123 --description "$(date +%F)" |
crontab -e / -l | 백업 자동화 등록·확인 | 0 2 * * * /opt/scripts/backup.sh |
find … -mtime +7 -delete | 오래된 백업 정리 | find /backup/ -name 'config_*.tar.gz' -mtime +7 -delete |
df -h | 백업 전 디스크 여유 확인 | df -h /backup (Use% 80%↑면 정리) |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
aws ec2 describe-instances | 인스턴스 목록·상태 조회 | --query "Reservations[].Instances[].[InstanceId,State.Name]" --output table |
aws ssm start-session | SSH 포트 없이 EC2 접속 | aws ssm start-session --target i-0abc… |
aws ec2 start/stop/reboot-instances | 인스턴스 전원 제어 | aws ec2 stop-instances --instance-ids i-0abc… |
aws ec2 authorize-security-group-ingress | SG 인바운드 규칙 추가 | --group-id sg-… --protocol tcp --port 443 --cidr 0.0.0.0/0 |
aws ec2 describe-security-groups | SG 인·아웃바운드 규칙 확인 | --query "SecurityGroups[].IpPermissions" |
aws rds describe-db-instances | RDS 상태·엔드포인트 조회 | --query "DBInstances[0].Endpoint.Address" --output text |
aws s3 cp / sync | S3 업·다운로드, 정적 배포 | aws s3 sync ./dist s3://bucket/static/ --delete |
aws cloudwatch get-metric-statistics | EC2/RDS 메트릭 조회 | --namespace AWS/EC2 --metric-name CPUUtilization --period 300 |
aws cloudwatch put-metric-alarm | 임계치 경보 설정 | --threshold 80 --alarm-actions arn:aws:sns:… |
aws logs get-log-events | CloudWatch 로그 조회 | --log-group-name /aws/ec2/myapp --limit 50 |
aws elbv2 describe-target-health | ALB 타겟 헬스 확인 | --target-group-arn arn:…:targetgroup/my-tg/… |
aws ce get-cost-and-usage | 이번 달 비용 확인 | --granularity MONTHLY --metrics BlendedCost |
nc -zv | RDS 등 포트 연결 테스트 | nc -zv my-db….rds.amazonaws.com 3306 |
curl 169.254.169.254 | EC2 인스턴스 메타데이터 조회 | curl -s http://169.254.169.254/latest/meta-data/instance-id |
| 명령어/단축키 | 용도 | 자주 쓰는 예 |
|---|---|---|
systemctl status/restart | 서비스 상태 확인·재기동 | systemctl restart tomcat (덤프 확보 후) |
tail -f … catalina.out | WAS 기동·에러 로그 실시간 | grep -E "ERROR|Exception|OutOfMemory" 조합 |
awk '{print $9}' access.log | 상태코드 분포 집계 | awk '{print $9}' access.log | sort | uniq -c | sort -rn |
curl -o /dev/null -w '%{http_code}' | 헬스체크 상태코드만 확인 | curl -o /dev/null -s -w '%{http_code}' localhost/health |
openssl s_client + x509 -noout -dates | SSL 인증서 만료일 확인 | echo | openssl s_client -connect ex.com:443 | openssl x509 -noout -dates |
certbot renew | Let's Encrypt 인증서 갱신 | certbot renew --dry-run(테스트) → certbot renew |
nginx -t && systemctl reload nginx | 설정 문법 검증 후 무중단 반영 | 인증서·프록시·WAF 예외 변경 후 |
SHOW FULL PROCESSLIST | 실행 중 쿼리·커넥션 확인 | information_schema.processlist WHERE time>60 |
KILL / KILL QUERY | 느린 쿼리·연결 강제 종료 | KILL QUERY 1234;(쿼리만) / KILL 1234;(연결) |
EXPLAIN / ALTER TABLE … ADD INDEX | 풀스캔 진단·인덱스 추가 | ALTER TABLE orders ADD INDEX idx_email (email) |
nc -zv | 외부 API 포트 연결 테스트 | nc -zv api.payment.com 443 |
curl -v --connect-timeout | HTTP 레벨 연결·차단 확인 | curl -v --connect-timeout 10 https://api.payment.com/ |
iptables -L OUTPUT -n | 아웃바운드 방화벽 규칙 확인 | iptables -L OUTPUT -n | grep 443 |
jstack / jmap | 재시작 전 스레드·힙 덤프 확보 | 증거가 지워지기 전에 먼저 실행 |
SHOW STATUS LIKE 'Threads_connected' | 커넥션 소진 임박 확인 | max_connections 대비 80%↑면 위험 |