본문 바로가기

Linux

[Linux] 의존성·네트워크·부팅보안 트러블슈팅

1. 패키지 관리 (RPM / DNF)

1.1 배포판별 방식

  • RHEL/Rocky: rpm, dnf(=yum), source compile
  • Debian/Ubuntu: dpkg, apt, source compile

1.2 RPM 핵심

  • 파일 확장자: *.rpm
  • 아키텍처: x86_64, aarch64, noarch(CPU 무관)
  • 의존성 무시 옵션: --nodeps (권장 X: 실제 운영에선 깨진 의존성 유발)

실습: mc 설치/확인/삭제

# 다운로드(예시)
wget https://dl.rockylinux.org/pub/rocky/9/AppStream/x86_64/os/Packages/m/mc-4.8.26-5.el9.x86_64.rpm

# 설치
rpm -Uvh /root/mc-4.8.26-5.el9.x86_64.rpm

# 설치 패키지 확인(필터)
rpm -qa | grep mc

# 실행
mc

# 삭제
rpm -e mc

# 패키지 정보 보기
rpm -qip /root/mc-4.8.26-5.el9.x86_64.rpm

# 특정 패키지 설치 이력
rpm -q --last mc

실습: httpd 의존성 해결 (수동 RPM)

 
# 개별 rpm들을 내려받아 순서대로 설치
rpm -Uvh httpd-filesystem-...noarch.rpm
rpm -Uvh apr-....x86_64.rpm
rpm -Uvh apr-util-....x86_64.rpm
rpm -Uvh apr-util-bdb-....x86_64.rpm
rpm -Uvh httpd-tools-....x86_64.rpm
rpm -Uvh httpd-core-....x86_64.rpm
rpm -Uvh httpd-....x86_64.rpm

참고: 이렇게 수동으로 풀 체인을 맞추는 대신 DNF 사용이 훨씬 안전/간편.

1.3 DNF(YUM) 핵심

  • 의존성 자동 해결, 온라인 저장소 사용
 
# 설치/시작/페이지 작성
dnf -y install httpd
systemctl start httpd.service
echo "hello" > /var/www/html/index.html

# 검색/설치확인
dnf search mc
dnf install mc
dnf list installed | grep mc

# 저장소 파일
ls /etc/yum.repos.d/
vi /etc/yum.repos.d/rocky.repo

# EPEL 추가 후 재시도
dnf -y install epel-release
dnf repolist

# 업데이트
dnf update            # 전체
dnf update httpd      # 개별(미설치면 업데이트 없음)

# 삭제
dnf remove mc

# 그룹
dnf grouplist
dnf groupinstall "Java Platform"

2. 묶음/압축 (tar, gzip/bzip2/xz)

2.1 개념

  • 묶음(tar): 여러 파일을 하나로 모음(용량 변화 X)
  • 압축(gz/bz2/xz): 용량 축소

2.2 tar 기본

# 절대경로로 묶기
tar cvf /root/123.tar /root/1 /root/2 /root/3
tar tf /root/123.tar

# 해제
tar xf /root/123.tar

# 상대경로로 묶기(풀면 현재 경로에 바로 떨어짐)
tar cvf /root/123.tar ./1 ./2 ./3
tar xvf /root/123.tar

# 상세 목록
tar tvf /root/123.tar

# 다른 디렉터리에 해제(-C)
tar xvf /root/123.tar -C /home/u01/

2.3 묶음+압축 한 번에

 
# gzip
tar zcvf /root/123.tar.gz ./1 ./2 ./3
tar zxvf /root/123.tar.gz

# bzip2
tar jcvf /root/123.tar.bz2 ./1 ./2 ./3
tar jxvf /root/123.tar.bz2

# xz
tar Jcvf /root/123.tar.xz ./1 ./2 ./3
tar Jxvf /root/123.tar.xz

2.4 과제 힌트

 
# 1) /etc/sysconfig → /home/u02/1.tar.gz
tar zcvf /home/u02/1.tar.gz /etc/sysconfig

# 2) /usr/share/doc → /root/3.tar.bz2
tar jcvf /root/3.tar.bz2 /usr/share/doc

# 3) 위 2개를 /d3에 해제
mkdir -p /d3
tar zxvf /home/u02/1.tar.gz -C /d3
tar jxvf /root/3.tar.bz2 -C /d3

 


3. 파일 찾기 (find / which / whereis / locate)

3.1 find 자주 쓰는 옵션

 
# 이름
find / -name shadow
find /etc -name passwd

# 유형
find /root -name test -type f   # 파일
find /dev -type b               # 블록
find / -name selinux -type l    # 심볼릭 링크

# 퍼미션
find /usr/bin -perm 4755
find /root/test -perm 770
find /root/test -perm -770      # 포함

# 소유자
find /home -user rocky

# 일괄 실행
find /ptest -name "*.swp" -exec rm {} \;

3.2 which / whereis / locate

 
which ping                 # PATH 내 실행파일 절대경로
whereis ls                 # 실행파일+소스+man 경로
updatedb && locate mc      # locate DB 갱신 후 검색

 

4. 스케줄링 (cron / at / rdate)

4.1 cron(반복 작업)

  • 패키지: cronie
  • /etc/crontab 형식:
  • 분 시 일 월 요일 사용자 명령
 
# 시스템 크론(사용자 지정 가능)
vi /etc/crontab
* * * * * root touch /data1/1.txt

# 사용자 크론
crontab -e
* * * * * touch /data1/1.txt

# 확인/삭제
crontab -l
crontab -r

실습 예시

 
# 매일 02:00 /home → /ptest/home.tar.gz (gz)
mkdir -p /ptest
echo '0 2 * * * root tar zcvf /ptest/home.tar.gz /home' >> /etc/crontab

과제 ① (표현식)

 
1-1) 10 5-8 * * *                 # 매일 5,6,7,8시 10분
1-2) 5 8,11,14,17,20 * * *        # 매일 8/11/14/17/20시 5분
1-3) 0,20,40 9-11 10-12 * *       # 매월 10~12일, 9~11시 매 0/20/40분

과제 ② (구체 라인)

 
# 2-1) 매주 월요일마다 /data1/hi.txt에 hi 추가 (root의 사용자 크론)
crontab -e
0 0 * * 1 echo hi >> /data1/hi.txt

# 2-2) /etc/crontab: 매일 5/6/7/8시 10분, u01로 /data1/2.txt에 hello
vi /etc/crontab
10 5-8 * * * u01 echo hello >> /data1/2.txt

# 2-3) /etc/crontab: 매일 8/11/14/17/20시 5분, hi 추가
5 8,11,14,17,20 * * * root echo hi >> /data1/2.txt

# 2-4) /etc/crontab: 매월 10~12일, 9~11시 매 0/20/40분, bye 추가
0,20,40 9-11 10-12 * * root echo bye >> /data1/3.txt

4.2 at(1회성)

 
at 3:00 am tomorrow
# (프롬프트에서)
touch /root/1.txt
<EOT>  # Ctrl+D
at -l
atrm <jobid>

4.3 rdate(시간 동기화)

 
# 설치(예시)
rpm -Uvh https://archives.fedoraproject.org/.../openrdate-1.2-14.fc30.x86_64.rpm

# 확인/동기화
rdate -p time.bora.net
rdate -s time.bora.net
date

 

5. 네트워크 설정 (nmtui / nmcli / ifup, ifdown)

5.1 TUI/GUI

  • nmtui로 연결 편집/활성화

 

5.2 CLI 예시

 
# 링크 비/활성화
ifdown ens160
ifup ens160

# 장치 상태
nmcli device status
nmcli device show ens160

# IP 변경 후 재연결
nmcli connection modify ens160 ipv4.addresses 10.10.100.201/8 ipv4.gateway 10.0.0.1 ipv4.dns 168.126.63.1
nmcli con down ens160 && nmcli con up ens160

5.3 인터넷 장애 체크 포인트

  • L1(케이블/VMnet) → GW 라우팅(ip route) → DNS(/etc/resolv.conf)

6. 파이프 | 필터 | 리다이렉션

 
# grep
grep root /etc/passwd
grep -n root /etc/passwd

# 파이프
ls /etc | grep sysconfig

# 출력 리다이렉션
ls /root > /root/1.txt
echo hi > /root/1.txt
ls -l >> /root/1.txt

# 입력 리다이렉션
sort < /root/sort.txt

# 글자수
wc -c /root/w.txt

 

7. 프로세스

7.1 개념/종류

  • 프로그램이 메모리에 올라와 동작 중인 것
  • Foreground(UI 상호작용), Background(&)

7.2 관리 기본기

 
# 목록
ps -f
ps -ef | grep httpd

# 포/백 전환
(포그라운드 실행 중) Ctrl+Z  # 일시정지
bg %1                        # 백그라운드
jobs
fg %1

# 종료
kill -9 <PID>
pkill httpd

7.3 tty / pstree

  • tty로 현재 터미널 식별 (/dev/tty1, /dev/pts/N)
  • pstree로 부모-자식 구조 확인

8. 응급복구: Single User Mode

  1. GRUB 화면에서 [e]
  2. 커널 라인 끝에 init=/bin/bash 추가
  3. Ctrl+X 부팅 → 루트 쉘 진입
  4. 루트가 읽기 전용이면 쓰기 재마운트:
 
mount -o remount,rw /
  1. 비밀번호 변경:
passwd

 

9. GRUB(부트로더) 설정/보안

9.1 대기시간/비밀번호

 
# 대기시간 5 → 20초
vi /etc/default/grub
GRUB_TIMEOUT=20

# 편집 보호(메뉴 Edit 시 인증)
vi /etc/grub.d/00_header
# 하단에 추가
cat << 'EOF'
set superusers="thisislinux"
password thisislinux 1234
EOF

# 적용
grub2-mkconfig -o /boot/grub2/grub.cfg
  • 재부팅 후 GRUB에서 편집하려면 thisislinux / 1234 필요.

참고 스니펫 모음

 
# PATH 확인
echo $PATH

# dnf 저장소 확인
dnf repolist

# tar 내용 보기
tar tvf <archive>

# find 고급 -exec
find <path> -name "*.log" -exec gzip {} \;

# cron 필드 기억법
# m h dom mon dow user cmd

 

A. RPM / DNF 심화

  • RPM 탐색 필수기
 
rpm -qf /usr/bin/ls            # 이 파일을 제공한 패키지 찾기
rpm -ql httpd                  # 패키지가 설치한 파일 목록
rpm -qc httpd                  # 설정파일만
rpm -qd httpd                  # 문서/라이선스만
rpm -V httpd                   # 무결성 검증(해시/퍼미션 등)
  • DNF 실무 팁
 
dnf history                    # 설치/삭제 이력
dnf history undo <ID>          # 특정 트랜잭션 롤백
dnf clean all && dnf makecache # 메타데이터 정리/미리받기
dnf provides */sshd_config     # 파일명을 제공하는 패키지 찾기
dnf module list                # 모듈 스트림(언어런타임 등)
dnf module enable php:8.2
dnf versionlock add httpd-*    # 의도치 않은 업데이트 잠금(plug-in)
  • 의존성 지옥 피하기
    • 가능하면 DNF로 설치·업데이트 → 의존성 자동 해결.
    • RPM 단독 설치 시엔 rpm -Uvh *.rpm로 한 디렉터리에 다 모아 한 번에 처리.

 


B. tar/압축 실무 노하우

  • 자주 쓰는 옵션
 
# 제외 규칙
tar zcvf backup.tgz /var/www --exclude='*/node_modules' --exclude='*.log'

# 퍼미션/소유권 보존(복원 시)
tar zxpf backup.tgz -C /restore     # -p 중요(권한 보존)

# 증분 백업(스냅샷 파일로 변경점만)
tar zcvf full.tgz --listed-incremental=snap.file /data
tar zcvf inc-1.tgz --listed-incremental=snap.file /data
  • 압축 포맷 선택 가이드
    • gz: 빠름 / 적당한 압축
    • bz2: 느림 / 더 잘 압축
    • xz: 가장 잘 압축 / 느림
    • zstd: 매우 빠른 압축·해제(신규 추세)
 
tar -I 'zstd -19' -cvf backup.tar.zst /data
tar --use-compress-program=unzstd -xvf backup.tar.zst

 


C. find / which / whereis / locate 고급

  • 성능과 안전
 
# 공백/특수문자 안전 처리(-print0 / -0)
find /data -name "*.log" -print0 | xargs -0 gzip

# 깊이 제한
find /var -maxdepth 2 -type f -name "*.conf"
  • 시간/크기/조건 결합
 
find /var/log -type f -mtime +7 -size +50M -delete
find /tmp -type f -mmin +60 -name "*.tmp" -exec rm -f {} +
  • which vs type
 
which ls    # PATH에서 찾기
type ls     # 셸 내장/별칭 여부까지
  • locate 주의
    • updatedb로 DB 갱신 전엔 최신 파일이 안 잡힘(보안상 일부 경로 제외).

 


D. 스케줄링 확장 (cron ↔ systemd timer / at ↔ atd / 시간 동기화)

  • cron 환경 변수
 
# /etc/crontab 맨 위에 명시
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
  • 로그 확인
 
tail -f /var/log/cron
journalctl -u crond -f
  • systemd timer(현대적 대안)
     
# /etc/systemd/system/backup.service
[Unit]
Description=Home backup

[Service]
Type=oneshot
ExecStart=/usr/bin/tar zcvf /backup/home.tgz /home

# /etc/systemd/system/backup.timer
[Unit]
Description=Run home backup daily 02:00

[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true

[Install]
WantedBy=timers.target

systemctl daemon-reload
systemctl enable --now backup.timer
systemctl list-timers --all
  • at 사용 전
 
systemctl enable --now atd      # 예약 데몬
at now + 2 minutes
atq                              # 목록
atrm <jobid>                     # 취소
  • 시간 동기화는 rdate보다 chrony 권장
 
dnf -y install chrony
systemctl enable --now chronyd
chronyc sources -v

 


E. 네트워크 & 서비스 운영(SELinux/Firewall 포함)

  • nmcli로 새 연결(정적 IP) 만들기
 
nmcli con add type ethernet ifname ens160 con-name ens160 \
  ipv4.addresses 10.10.100.201/8 ipv4.gateway 10.0.0.1 ipv4.dns 168.126.63.1 ipv4.method manual
nmcli con up ens160
  • 진단 단골
 
ip addr; ip route
ss -tulpn                       # 리스닝 포트
curl -I http://127.0.0.1/
dig A google.com @8.8.8.8       # DNS 확인
  • httpd 통신 막힘? → 방화벽/SELinux 확인
 
# 방화벽 허용
firewall-cmd --add-service=http --permanent
firewall-cmd --reload

# 웹 루트 커스텀 경로 쓰면 SELinux 컨텍스트 주의
semanage fcontext -a -t httpd_sys_content_t "/srv/www(/.*)?"
restorecon -Rv /srv/www

# 프록시/외부연결 필요 시
setsebool -P httpd_can_network_connect on

 


F. 파이프 | 필터 | 리다이렉션 “무기고”

  • 필터 콤보
 
journalctl -u sshd | grep Failed | cut -d' ' -f1-4 | sort | uniq -c | sort -nr | head
awk -F: '{print $1,$3,$6}' /etc/passwd | column -t
sed -n 's/^#//'p /etc/ssh/sshd_config   # 주석 제거
  • xargs/tee/tr
 
printf "a b c\n" | xargs -n1 -I{} echo file:{}   # 공백 구분해 1개씩
ls -l | tee list.txt | grep '^d'                 # 출력 + 파일 동시저장
tr '[:lower:]' '[:upper:]' < words.txt
  • 리다이렉션 응용
 
cmd  >out.txt 2>err.txt     # 표준출력/에러 분리
cmd &>all.txt               # 둘 다 한곳으로
cmd 2>&1 | tee run.log      # 에러를 표준에 합쳐 파이프
cat <<'EOF' > script.sh     # here-document
echo "hello"
EOF
bash -c 'echo "$VAR"' <<< "$VALUE"  # here-string

 


G. 프로세스/리소스 운영

  • 관측 도구
 
top, htop, vmstat 1, iostat -xz 1, free -h, sar -q 1 5
pstree -ap | less
  • 신호/우선순위/백그라운드
 
kill -15 <PID>        # 정상 종료 시도 → 안되면 -9
nice -n 10 cmd        # 낮은 우선순위
renice -n -5 -p <PID> # 우선순위 조정
nohup long-task &     # 로그아웃 후에도 계속
disown %1             # 셸 job에서 분리
  • 서비스형 프로세스는 systemd가 정석
 
systemctl status httpd
systemctl restart httpd
systemctl enable httpd

 


H. 단일 사용자 모드 실전 주의사항

  • init=/bin/bash 진입 후 쓰기 재마운트:
mount -o remount,rw /
  • SELinux Enforcing 환경에서 암호 바꿨으면:
touch /.autorelabel    # 다음 부팅 시 전체 relabel
exec /sbin/reboot -f
  • LVM/암호화 등 복잡한 루트면 dracut 쉘/rd.break 루트 패스워드 리셋 절차가 더 안전한 경우도 있음.

 


I. GRUB 보안 베스트 프랙티스

  • 평문 대신 해시 비밀번호 사용
grub2-mkpasswd-pbkdf2           # 해시 생성
# 출력된 해시를 00_header에
set superusers="thisislinux"
password_pbkdf2 thisislinux grub.pbkdf2.sha512.10000.XXXXXXXX

# BIOS
grub2-mkconfig -o /boot/grub2/grub.cfg
# UEFI
grub2-mkconfig -o /boot/efi/EFI/rocky/grub.cfg
  • 편집 잠금 확인: 재부팅 후 GRUB 편집 시 thisislinux / (설정한 비번)
  • 커널 파라미터 보호: 멀웨어가 커널 인자 수정 못 하게 권한 및 EFI 보호도 병행.

 

J. 자주 쓰는 치트시트 (복붙용)

 
# 패키지
rpm -qf <file> ; rpm -ql <pkg> ; rpm -V <pkg>
dnf search <kw> ; dnf provides '*/<file>' ; dnf history

# 백업
tar zcvf backup.tgz /data --exclude='*.tmp'
tar zxpf backup.tgz -C /restore

# 탐색
find /var/log -type f -mtime +7 -size +100M -delete
find / -name "*.conf" -print0 | xargs -0 grep -n "Listen"

# 스케줄
echo '0 2 * * * root tar zcvf /backup/home.tgz /home' >> /etc/crontab
systemctl list-timers --all

# 네트워크/서비스
nmcli con mod ens160 ipv4.addresses 10.10.100.201/8 ipv4.gateway 10.0.0.1 ipv4.dns 168.126.63.1
ss -lntp ; firewall-cmd --add-service=http --permanent && firewall-cmd --reload

# 로그/파이프
journalctl -u httpd | tail -100 | grep -i error | tee httpd.err