리눅스/실습

리눅스 실습(3) - 파일시스템 실습(RAID 및 파일시스템 복구)

dbswjdahr 2025. 10. 31. 18:42

이제 파티션이 끝났으니 파일시스템을 만들어보자. 파일시스템을 만들어야 하는 이유는 파티션하는 거랑 이유는 거의 같이 디스크를 실제 저장 공간으로 사용하기 위함 그래야 OS가 장치를 파일로 인식하고 저장할 수 있음. 기본적으로 리눅스 자체가 파일 시스템 구조로 작동해서 안 해주면 장치가 깡통에 불과함.  

mkfs 이라는 명령어로 파일 시스템을 만들 수 있다. 기본적으로 디스크가 있으면 파티션 -> 파일시스템 생성 -> 마운트 순으로 작업
파일시스템 목록에 어떤 것들이 있는지 보려면 아래와 같이 명령어를 입력하고 Tab을 치면 된다 ( bash-completion 패키지 필요 )

[root@Alma ~]# mkfs -t
cramfs  ext2    ext3    ext4    fat     minix   msdos   vfat    xfs

여기 중 기준이 되는 것은 ext4로, 리눅스 표준 파일시스템이다. 숫자를 보면 알겠지만 2랑 3은 옛날 방식이니 필요없음. 최근 redhat에선 xfs를 많이 사용하는 추세, minix랑 msdos도 여기서 쓸 일 없는 옛 구닥다리 파일시스템이라 안 쓴다. 현재 redhat 계열에서는 xfs를 표준으로 사용하므로 xfs로 생성을 하겠다 참고로 OS 설치 시 /boot는 xfs, /boot/efi는 vfat 파일시스템을 사용한다. 

[root@Alma ~]# mkfs.xfs /dev/sda1
meta-data=/dev/sda1              isize=512    agcount=4, agsize=327680 blks
         =                       sectsz=4096  attr=2, projid32bit=1
         =                       crc=1        finobt=1, sparse=1, rmapbt=1
         =                       reflink=1    bigtime=1 inobtcount=1 nrext64=1
         =                       exchange=0
data     =                       bsize=4096   blocks=1310720, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0, ftype=1, parent=0
log      =internal log           bsize=4096   blocks=16384, version=2
         =                       sectsz=4096  sunit=1 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
Discarding blocks...Done.
[root@Alma ~]# blkid /dev/sda1
/dev/sda1: UUID="803d6d5f-efdd-4dd1-8126-6451f42fabf6" BLOCK_SIZE="4096" TYPE="xfs" PARTUUID="267df565-933d-474e-aa05-f9f8cc393aa1"
[root@Alma ~]# blkid /dev/sda2
/dev/sda2: PARTUUID="d441b139-a08f-4089-a2d4-411890299a7f"

파일 시스템이 생성되면 blkid 명령어로 해당 장치(파티션)를 확인하면 된다. 그럼 실제 장치를 사용하기 위한 모든 사전 준비가 끝난 것이다. 이제 진짜 사용하기 위해선 장치를 디렉터리에 마운트를 시켜야 한다. 계속 말하지만 모든 게 리눅스가 파일 단위로 구성되고 관리되도록 설계돼서 이런 짓을 해야 함. 마운트는 이름에서 알 수 있듯이 장치가 디렉터리에 붙어 올라타는 것이고 사용자는 셸을 통해 장치를 직접 바라보지 못하지만 마운트된 디렉터리는 바라볼 수 있어서 보통 /mnt 밑에 각 디렉터리를 생성시키고 그 경로로 마운트해 사용한다. 

[root@Alma ~]# mkdir -p /mnt/fileSystem
[root@Alma ~]# mount /dev/sda1 /mnt/fileSystem/
[root@Alma ~]# df
Filesystem                 1K-blocks    Used Available Use% Mounted on
/dev/mapper/almalinux-root  36077568 1952232  34125336   6% /
devtmpfs                        4096       0      4096   0% /dev
tmpfs                        1869728       0   1869728   0% /dev/shm
efivarfs                      131072      32    131036   1% /sys/firmware/efi/efivars
tmpfs                         747892    8708    739184   2% /run
tmpfs                           1024       0      1024   0% /run/credentials/systemd-journald.service
/dev/sdb2                     983040  309056    673984  32% /boot
/dev/sdb1                     613160    8600    604560   2% /boot/efi
tmpfs                           1024       0      1024   0% /run/credentials/getty@tty1.service
tmpfs                         373944       4    373940   1% /run/user/0
/dev/sda1                    5177344  132280   5045064   3% /mnt/fileSystem

마운트할 디렉터리를 만들고 마운트를 시킨 것. 마운트도 명령어 자체는 직관적으로 쉽게 가능하다. 마운트된 장치와 경로를 보기 위해서는 df, mount, lsblk 등 명령어로 확인이 가능함. 

mount 명령어로 마운트한 파일은 시스템 재부팅 시 풀리는데, 계속 되게 하려면 /etc/fstab에 장치를 등록해줘야 한다. 아래는 예시이다. 총 6개 값으로 필드가 구성되어 있다.

UUID, 장치명 마운트 대상 경로 파일시스템 유형 마운트 옵션 덤프 파일 시스템 검사 순서
UUID="...", /dev/sdb1 /mnt/fileSystem xfs defaults 0 0

 

이제 마운트 개념을 이해하기 위해 마운트된 디렉터리에 용량이 큰 /var/log 아래 아무 로그가 담긴 파일을 복붙함
그리고 마운트를 끊으면? 디렉터리에 있는 내용이 사라지는 걸 확인할 수 있다!

[root@Alma ~]# cd /mnt/fileSystem
[root@Alma fileSystem]# cp /var/log/messages .
[root@Alma fileSystem]# ls
-rw-------. 1 root root 278879 Oct 31 14:28 messages
[root@Alma mnt]# umount /dev/sda1
[root@Alma mnt]# ll /mnt/fileSystem/
total 0

이건 내용이 /mnt/fileSystem이라는 디렉터리가 아닌 실제 장치에 저장되는 거라 마운트 경로가 끊기면 일반 디렉터리나 다를 바가 없어 원래대로 돌아간 것. 반대로 마운트 전에 디렉터리에 파일을 두고 있다가 장치를 마운트하면 원래 디렉터리에 있던 파일이 뒤로 밀리고 장치 데이터가 보이게 된다. 마운트는 오버레이하는 특징이 있어서 원래 파일이 덮어지게 됨

[root@Alma fileSystem]# cp /var/log/dnf.log . ## 마운트 안 된 상태에서 디렉터리 상태
[root@Alma fileSystem]# cd ~
[root@Alma ~]# ll /mnt/fileSystem/ 
total 172
-rw-r--r--. 1 root root 175981 Oct 31 14:34 dnf.log

[root@Alma ~]# mount /dev/sda1 /mnt/fileSystem/ ## 마운트 후 디렉터리 상태
[root@Alma ~]# ll /mnt/fileSystem/
total 276
-rw-------. 1 root root 278879 Oct 31 14:28 messages

이제 물리 저장 장치(가상 디스크지만)인 디스크 파티션에 로그데이터가 들어가 있으니 깨트리고 복구하는 것을 해본다. ext4는 fsck를 사용해 진행하지만 여기선 xfs이므로 xfs_repair 명령어로 함

[root@Alma ~]# dd if=/dev/random of=/dev/sda1 bs=4K count=1
1+0 records in
1+0 records out
4096 bytes (4.1 kB, 4.0 KiB) copied, 0.00369304 s, 1.1 MB/s
[root@Alma ~]# mount /dev/sda1 /mnt/fileSystem/
mount: /mnt/fileSystem: wrong fs type, bad option, bad superblock on /dev/sda1, missing codepage or helper program, or other error.
       dmesg(1) may have more information after failed mount system call.
[root@Alma ~]# xfs_info /dev/sda1
xfs_info: /dev/sda1 is not a valid XFS filesystem (unexpected SB magic number 0x86af398c)
Use -F to force a read attempt.
[root@Alma ~]# xfs_db -r /dev/sda1
xfs_db: /dev/sda1 is not a valid XFS filesystem (unexpected SB magic number 0x86af398c)
Use -F to force a read attempt.

dd 명령어로 메타데이터가 있는 부분을 손상시킴(i-node, 수퍼블록 등 존재하는 영역). 그랬더니 마운트랑 xfs의 정보 조회 명령어가 수퍼블록의 매직 넘버 이상으로 유효하지 않다고 거부됨. dd 명령어로 랜덤한 값으로 파일의 시작부터 4kb까지의 용량을 덮어버렸기 때문에 메타데이터 부분이 지워진 것 xfs_repair 명령어도 고치기 전 상태 확인이 가능한데

Phase 1 - find and verify superblock...
bad primary superblock - bad magic number !!!

attempting to find secondary superblock...
.found candidate secondary superblock...
verified secondary superblock...
would write modified primary superblock
Primary superblock would have been modified.
Cannot proceed further in no_modify mode.
Exiting now.

보시다시피 xfs_info, xfs_db 등과 같은 내용의 에러가 나옴. 이제 다시 xfs_repair로 복구를 해보면

[root@Alma ~]# mount /dev/sda1 /mnt/fileSystem/
[root@Alma ~]# ls -il /mnt/fileSystem/
total 376
131 -rw-------. 1 root root 383792 Oct 31 16:30 messages
[root@Alma ~]# xfs_info /dev/sda1
meta-data=/dev/sda1              isize=512    agcount=4, agsize=327680 blks
         =                       sectsz=4096  attr=2, projid32bit=1
         =                       crc=1        finobt=1, sparse=1, rmapbt=1
         =                       reflink=1    bigtime=1 inobtcount=1 nrext64=1
         =                       exchange=0
data     =                       bsize=4096   blocks=1310720, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0, ftype=1, parent=0
log      =internal log           bsize=4096   blocks=16384, version=2
         =                       sectsz=4096  sunit=1 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0

다시 정상적으로 모든 작업이 수행 가능해졌다! ls -i 명령어로 파일의 inode 번호도 정상적으로 붙어있는 걸 확인할 수 있다.
이젠 메타데이터 말고 데이터블록 부분을 손상시키고 확인해보도록 하겠다. 일단 원래 상태로 되돌리기 위해 파티션을 초기화 시키고 깨끗한 환경에서 시작하겠음.

[root@Alma ~]# wipefs -a /dev/sda1
/dev/sda1: 4 bytes were erased at offset 0x00000000 (xfs): 58 46 53 42
[root@Alma ~]# mkfs.xfs /dev/sda1
meta-data=/dev/sda1              isize=512    agcount=4, agsize=327680 blks
         =                       sectsz=4096  attr=2, projid32bit=1
         =                       crc=1        finobt=1, sparse=1, rmapbt=1
         =                       reflink=1    bigtime=1 inobtcount=1 nrext64=1
         =                       exchange=0
data     =                       bsize=4096   blocks=1310720, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0, ftype=1, parent=0
log      =internal log           bsize=4096   blocks=16384, version=2
         =                       sectsz=4096  sunit=1 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
Discarding blocks...Done.
[root@Alma ~]# mount /dev/sda1 /mnt/fileSystem/
[root@Alma ~]# lscpu > lscpu
[root@Alma ~]# mv lscpu  /mnt/fileSystem/
[root@Alma ~]# cat /mnt/fileSystem/lscpu
Architecture:                         x86_64
CPU op-mode(s):                       32-bit, 64-bit
Address sizes:                        39 bits physical, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               6
On-line CPU(s) list:                  0-5
Vendor ID:                            GenuineIntel
BIOS Vendor ID:                       Intel(R) Corporation
Model name:                           13th Gen Intel(R) Core(TM) i7-1355U
BIOS Model name:                      13th Gen Intel(R) Core(TM) i7-1355U None CPU @ 4.3GHz
BIOS CPU family:                      198
CPU family:                           6
Model:                                186
Thread(s) per core:                   2
Core(s) per socket:                   3
Socket(s):                            1
Stepping:                             3
BogoMIPS:                             5222.40
Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology tsc_reliable nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch ssbd ibrs ibpb stibp ibrs_enhanced fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves user_shstk avx_vnni umip waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize flush_l1d arch_capabilities
Hypervisor vendor:                    Microsoft
Virtualization type:                  full
L1d cache:                            144 KiB (3 instances)
L1i cache:                            96 KiB (3 instances)
L2 cache:                             3.8 MiB (3 instances)
L3 cache:                             12 MiB (1 instance)
NUMA node(s):                         1
NUMA node0 CPU(s):                    0-5
Vulnerability Gather data sampling:   Not affected
Vulnerability Itlb multihit:          Not affected
Vulnerability L1tf:                   Not affected
Vulnerability Mds:                    Not affected
Vulnerability Meltdown:               Not affected
Vulnerability Mmio stale data:        Not affected
Vulnerability Reg file data sampling: Mitigation; Clear Register File
Vulnerability Retbleed:               Mitigation; Enhanced IBRS
Vulnerability Spec rstack overflow:   Not affected
Vulnerability Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:             Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:             Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

wipefs -a로 파일시스템을 깨끗하게 닦아낸 다음 다시 만들어 마운트 한 뒤, 더미 파일 하나를 넣어놓고 데이터를 손상시키기 전에 현재 상태를 출력해본다. 임의로 lscpu 결과를 더미 데이터로 꼽아둠.

[root@Alma ~]# dd if=/dev/random of=/dev/sda1 bs=1 count=4096 seek=98304
4096+0 records in
4096+0 records out
4096 bytes (4.1 kB, 4.0 KiB) copied, 0.0142796 s, 287 kB/s
[root@Alma ~]# xfs_info /dev/sda1
meta-data=/dev/sda1              isize=512    agcount=4, agsize=327680 blks
         =                       sectsz=4096  attr=2, projid32bit=1
         =                       crc=1        finobt=1, sparse=1, rmapbt=1
         =                       reflink=1    bigtime=1 inobtcount=1 nrext64=1
         =                       exchange=0
data     =                       bsize=4096   blocks=1310720, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0, ftype=1, parent=0
log      =internal log           bsize=4096   blocks=16384, version=2
         =                       sectsz=4096  sunit=1 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
[root@Alma ~]# mount /dev/sda1 /mnt/fileSystem/
[root@Alma ~]# cat /mnt/fileSystem/lscpu
7Kڧu��
e��FM<sC�B~��^jh�UG��U^
                       Џ���V�K-C�Fƍ��*�-Y�1w�N�~��sg�����a�H���q
                                                                Ӂiz�̱������w�C3���LbVT�T�\����4�*�K�J��ڱ
�Y�
�Ģ������鈒:�)�d�Ix� �R�UV�rB��x9������Ә�D�i���I*�`��ui"K�9��9��R�݋�␦�m
��}�q9J9�{����ت�3�.sϟ��kZh�Fɸ[�
�0{15��>�ǧn�X��]�G�_���0�pg�h��h�
��.����Q1�T��9�*�
ɶ�  <YY��걵􄥛B�S�Pv��;�e���!_'�"�p%�>繍�m��_�l��q�5�*��q!�SG�v�u!}rm�.U˴]�̂�����Zw�)*�eA������^y��K�}���z���B@V
�R�
��@�CeǏB�1�c�ޞu�y�OɫN�����^N�p��\ԭ�+В����2���C�0�Xt
�w��t3�������s���6�=b��{���$���Ø٥��o8�␦h����    =e0�h*`몿R�M��eO]\�r�)�GW3G^
                                                                            .2���3��i�V싊�pW�@8
��be�P���
�-�cDq�z"�Ld�)B��z���&�d8#t5�����Ym}���<et,�>�)aQ��Q�/JL�ǧR
                                                           h����
EV>9���@Cc�{|����G��������_�[���碹'��                           ���Uƽ�V�*f>���Φ��A=.n�R'��g�PvϘmWP{��>�*<��q����        Nf�
                                     !f��-�=���Ȅ��%�bݪ׻*����Ʋ��/��oFT�C�^�Z��O; =>�$|s�n��� u�F�e����T��]��׭͞f2}5�F#P�q%�lqͧ�a��;i��#��x�����m��*���[B����ET���o�(�[���[ׅ��O��tT��Pa|ie��s�y�~9뷦���   �tw��ǔ�:U�,��q
                                                      ��U��#�\���C;G    *j��%�Q�G/�8

ͧ���A2����m:���Xs�˧=Y;� ���[hM�"1~��ϛ�s��z�wV��υSGCp
                                                    2�k�4^�>���)w�:���I��}�%����d�T
                                                                                   ��&��[݁�6c␦������&��gzpYWO��1�̮o�9��uz�Nw��nL���Ҏ��q��%���\����|(
� \<��NoX�}�������{���
��[���rы�1�`�����O2"������RX�$R���%��6����\`Y/��{o������2Xc�#mi�ڀAŰ8u��*��BT�p���.5ص����өu�vQ��@
                                                                                                g�zY�
                                                                                                     c�N�O�[����NPڲ��=,����p�t��k��G/p�s>�TZ����b�/��␦h����xa␦��x?V��;���lDW�L�����۹i:���E%!O�ȃ�����        ͇�p�Cu��7j�\����,Q�+��
                                                                     �R�݌�ژZ]7љ�|����hY�7�KNP���u��t�"�z��z�!�!~2

�ٜ�
d�E������!7�����`/[��@��B�1��]�UO�����6J@�y��ӌ;�}�2y��;!���u8�w7��)�,-ɫ�(�`�h�["���Of�?Fj@��l?�*�uD{Ocw��~8?�t��?(x.i"���1�>��c"�_J\�4��^�z���j�l�␦��
���uv��n=�؉C���"mnߡ�S����%1"B�"�!�OQ��� |x�js>}�@9k�Y��_�>N��4��(�CN���g�K?� D1���b���e�C�-�X�j��=��C":��M�
�D��� �DDA�����Y�gL��͵5e�
                         j�-�{ն���u��"��q_��v�Y��.xp��̋�k�       �Xn�]K��3���
huA�H;��q�¦�q֩���U���ʴ���P��P���[�hB�o�7��       3(9���/��������Z�
���z�K�#1�N�4���@M�N�d�x\:���'�_S�՟�\L�@��
                                          ��F���)m����jd�
�/Bq}EG����ɏ"���WuQ     e�j�
���yh�g�E���g��_{�}D
�␦,��I��L           ^��%�O��).S3��,����=Z��a|�el␦��q²��Yk��tB�W
  ��K��1�"�#p�m�h�X���r�C�4�s1����:�}����4%�\��?�1�a7�% g�8�fP`�ZiR������,a+�"&���Q�\�o���P^���␦x��afT�<���OL�0&�g��}D�V�*v��ô�$�/y�����B�X��   �@+����:q��<m�}�U�
g*��҆��8��2��ԙӤ��!$����F�h�CO��]_�-ȟ*��x!o_�c���ʊ4�4�B����

이번엔 데이터 영역을 날린 결과다. 98304는 블록 크기가 4kb 단위로 24블럭 뒤부터 시작하기 때문에 96kb의 위치이고, 거기서부터 한 블럭을 랜덤한 값으로 채웠다. 하지만 메타데이터는 살아있기 때문에 문제가 없이 마운트도 되고 정보도 조회가 된다. 
그러나 안의 내용은 손상되어 있는데, 데이터 부분은 복구할 때 쓰이지 못하므로 복구명령어를 시도해도 소용이 없음. 이 부분은 다른 조치를 취해야 한다.