Is there a way to fsck/chkdsk an NTFS drive from Linux?
asked Jan 15, 2011 at 21:33
Yes. This was handled by fsck on some releases. If the partition is not listed in /etc/fstab, then you will likely need to tell it the partition type. I’ve used this from a Linux CD to recover a partition Windows wouldn’t boot from.
Based on the comments below, the actual fixing is done by the ntfsfix program. It should be available, even if there is no program to run a fsck on an NTFS file system.
answered Jan 15, 2011 at 21:44
BillThorBillThor
10.7k2 gold badges24 silver badges23 bronze badges
2
Unfortunately the ntfsfix tool is very limited compared to Microsoft’s chkdsk. Try to get a Windows install going — preferably with the newest version of Windows as Microsoft is presumably constantly improving chkdsk (I hope..) New versions of Windows are often available for free as trials. If the problem is in a USB disk you can try installing Windows in something like VirtualBox and give the VM control of the USB device.
answered Jan 1, 2012 at 5:27
eugeug
8348 silver badges12 bronze badges
5
ln -s /bin/ntfsfix /sbin/fsck.ntfs
fsck /dev/sdg1
fsck from util-linux 2.21.2
Mounting volume... OK
Processing of $MFT and $MFTMirr completed successfully.
Checking the alternate boot sector... FIXED
NTFS volume version is 3.1.
NTFS partition /dev/sdg1 was processed successfully.
On fedora 22, there is another binary :
lrwxrwxrwx. 1 root root 13 May 22 22:13 /usr/sbin/fsck.ntfs -> ../bin/ntfsck
answered Jun 9, 2015 at 18:15
TanguyTanguy
1791 silver badge1 bronze badge
In my case, none of fsck & ntfsfix could fix the issue of my external NTFS mobile disk.
I end up to boot into windows os, and use follow steps to fix the disk issue.
Steps:
- Check the identifier of the bad disk. e.g
g - Open the «cmd» terminal of windows.
- Input
chkdsk <disk>: /fto fix it.
Where<disk>is the identifier, e.gchkdsk d: /f - Then it would be fixed within seconds (For a disk of size 1Tb).
After years, finally I found something that windows can do easily, but linux can’t 😉
@Update — vm solution
You can also create a windows vm (e.g win 7), then mount the mobile disk to windows vm, then you can also use chkdsk to fix the disk, it’s similar as boot into a windows machine.
answered Mar 30, 2018 at 10:15
![]()
EricEric
2734 silver badges10 bronze badges
2
If you have NTFSProgs installed, you should be able to run fsck.ntfs or fsck -t ntfs to fsck an NTFS drive.
answered Jan 15, 2011 at 21:45
squirclesquircle
6,6715 gold badges36 silver badges68 bronze badges
5
Столкнулся с проблемой подключения винта разбитого под Windows (ntfs) к машине с бубунту. При попытке монтирования выдавал ошибку —
An error occurred while accessing 'Домашняя папка', the system responded: Не удалось выполнить запрошенную операцию.: Error mounting: mount exited with exit code 13: $MFTMirr does not match $MFT (record 0). Failed to mount '/dev/sda1': Input/output error NTFS is either inconsistent, or there is a hardware fault, or it's a SoftRAID/FakeRAID hardware. In the first case run chkdsk /f on Windows then reboot into Windows twice. The usage of the /f parameter is very important! If the device is a SoftRAID/FakeRAID then first activate it and mount a different device under the /dev/mapper/ directory, (e.g. /dev/mapper/nvidia_eahaabcc1). Please see the 'dmraid' documentation for more details.
Следовать данному совету как-то не очень хотелось, то бишь перетыкать винт в машину с вендой и запускать chkdisk, а потом обратно переподключать …. брр, как-то слишком много действий.
Гугл подсказал прекрасную утилиту — ntfsfix, входящая в состав ntfsprogs, которая прекрасно справилась с данной ошибкой.
Из описания пакета —
ntfsfix — утилита которая исправляет некоторые основные ошибки NTFS. ntfsfix не является линукс-версией chkdsk. Она только исправляет некоторые базовые проблемы NTFS, сбрасывает файлы журнала NTFS, назначает проверку целостности файловой системы штатными утилитами Windows при ее следующей загрузке.
Устанавливаем —
sudo apt-get install ntfsprogs
И проверяем наш раздел —
$ sudo ntfsfix /dev/sda1 Mounting volume... $MFTMirr does not match $MFT (record 0). FAILED Attempting to correct errors... Processing $MFT and $MFTMirr... Reading $MFT... OK Reading $MFTMirr... OK Comparing $MFTMirr to $MFT... FAILED Correcting differences in $MFTMirr record 0...OK Correcting differences in $MFTMirr record 1...OK Correcting differences in $MFTMirr record 2...OK Correcting differences in $MFTMirr record 3...OK Processing of $MFT and $MFTMirr completed successfully. Setting required flags on partition... OK Going to empty the journal ($LogFile)... OK NTFS volume version is 3.1. NTFS partition /dev/sda1 was processed successfully.
где sda1 наш раздел с ntfs.
После данных нехитрых манипуляций диск легко примонтировался.
Scroll to navigation
| NTFSFIX(8) | System Manager’s Manual | NTFSFIX(8) |
NAME¶
ntfsfix — fix common errors and force Windows to check NTFS
SYNOPSIS¶
ntfsfix [options] device
DESCRIPTION¶
ntfsfix is a utility that fixes some common NTFS problems.
ntfsfix is NOT a Linux version of chkdsk. It only repairs some
fundamental NTFS inconsistencies, resets the NTFS journal file and schedules
an NTFS consistency check for the first boot into Windows.
You may run ntfsfix on an NTFS volume if you think it was
damaged by Windows or some other way and it cannot be mounted.
OPTIONS¶
Below is a summary of all the options that ntfsfix accepts.
Nearly all options have two equivalent names. The short name is preceded by
— and the long name is preceded by —. Any single letter
options, that don’t take an argument, can be combined into a single command,
e.g. -fv is equivalent to -f -v. Long named options can be
abbreviated to any unique prefix of their name.
- -b,
—clear-bad-sectors - Clear the list of bad sectors. This is useful after cloning an old disk
with bad sectors to a new disk. - -d,
—clear-dirty - Clear the volume dirty flag if the volume can be fixed and mounted. If the
option is not present or the volume cannot be fixed, the dirty volume flag
is set to request a volume checking at next mount. - -h, —help
- Show a list of options with a brief description of each one.
- -n,
—no-action - Do not write anything, just show what would have been done.
- -V, —version
- Show the version number, copyright and license
BUGS¶
There are no known problems with ntfsfix. If you find a bug
please send an email describing the problem to the development team:
ntfs-3g-devel@lists.sf.net
ntfsfix was written by Anton Altaparmakov, with
contributions from Szabolcs Szakacsits. It was ported to ntfs-3g by Erik
Larsson and Jean-Pierre Andre.
AVAILABILITY¶
ntfsfix is part of the ntfs-3g package and is
available from:
https://github.com/tuxera/ntfs-3g/wiki/
SEE ALSO¶
mkntfs(8), ntfsprogs(8)
Когда, при загрузке, операционная система сообщает о наличии ошибок в файловой системе на одном из разделов, то заслуживает незамедлительно сделать в linux проверку диска на ошибки. Любой уважающий себя user не должен забывать, что периодическая проверка жестких дисков на битые сектора и проверка атриторен на ошибки является примером здравого смысла. Для проверки разделов жесткого диска советуем использовать утилиту FSCK (file system consistency check), поскольку утилита FSCK предустановленна на основной массе операционных систем семейства Linux.
Примером хорошего тона и здравого резона является периодическая проверка диска на битые сектора (бэд-сектора, badblocks) и обычная испытание диска на ошибки записи и т.п. Разберёмся что такое битые сектора. Бэд-сектор, Повреждённый сектор — сбойный (не читающийся) или не внушающий доверие сектор диска; кластер, содержащий сбойные сектора, или кластер помеченный таковым в текстурах файловой системы операционной системой. Следовательно, если в битом секторе были этые, то их ещё возможно восстановить, пока битых секторов не стало слишком много для конкретного файла. Собрать список битых секторов можно с помощью команды badblocks.
Содержание статьи
- 1 Проверка диска на колоченные секторы в linux с помощью badblocks
- 2 Исправление ошибок файловой системы fsck
- 3 Проверка диска на битые секторы в linux с поддержкою smartmontools
Проверка диска на колоченные секторы в linux с помощью badblocks
Badblocks — стандартная утилита Linuх для проверки (Тестирование Инвентаризация Допинг-контроль Проверка подлинности Служебная проверка Проверка орфографии Проверка на дорогах Камеральная налоговая проверка Выездная налоговая проверка Проверка) на колоченные секторы. Она устанавливается по-умолчанию практически в любой дистрибутив и с ее помощью можно проверить как твердый диск, так и внешний накопитель. Для начала давайте посмотрим, какие накопители подключены к ушей системе и какие на них имеются разделы. Для этого нам нужна еще одна стандартная утилита Linux — fdisk.
Собрать список битых секторов можно с помощью команды badblocks.
Делается это так:
sudo badblocks -v /dev/hda1 > ~/badblocks.list
Где /dev/hda1 — это разоблачил диска, что вы хотите проверить.
Желательно делать проверку в однопользовательском режиме, когда это не внешний диск. Тогда его просто стоит отмонтировать. После этого мы можем швырнуть утилиту fsck, явно указав ей список битых секторов для того, чтобы она их подметить как «битые» и попыталась восстановить с них данные. Делается это так:
sudo fsck -t ext4 -l ~/badblocks.list /dev/hda1
Где ext4 — это тип файловой системы нашего разоблачила диска, а /dev/hda1 — сам раздел диска.
Естественно, что выполнять команды нужно с правами суперпользователя.
sudo fdisk -l
Метеопараметром -l мы говорим утилите fdisk, что нам нужно показать список разделов и выйти. Теперь, когда мы знаем, какие разделы у нас есть, мы можем проверить их на битые секторы. Для этого мы станем использовать утилиту badblocks следующим образом:
sudo badblocks -v /dev/sda1 > badsectors.txt
Если же в итоге были найдены битые секторы, то нам надо дать указание операционной системе не вписывать в них информацию в будущем. Для этого нам понадобятся утилиты Linux для работы с файловыми системами:
e2fsck. Когда мы будем исправлять раздел с файловыми система Linux ( ext2,ext3,ext4).
fsck. Если мы станем исправлять файловую систему, отличную от ext.
Исправление ошибок файловой системы fsck
В моей а не твоей статье «Проверка файловой системы на ошибки с помощью fsck на Linux» я расскажу как возможно проверить файловую систему на вашей ОС в Linux. Некоторым системам необходим пароль root дабы запустить fsck или других аналогичных утилит, когда не могут загрузить полностью ОС. В данном случае стоит выполнить проверку диска загрузившись в single-user mode , либо – загрузившись с иного диска. Fsck расшифровывается как «файловая система Проверка целостности» (file system consistency check).
На основной массе систем, Fsck запускается во время загрузки, если определенные условия. Код выхода ворачивается, когда несколько файловых систем которая проверяется побитовое ИЛИ (OR) для каждой файловой системы, какая проверяется. В действительности, Fsck — это просто фронт-энд для различных проверочных утилит для файловых систем (fsck.fstype), какие доступны на Linux. Файловая система (множество элементов, находящихся в отношениях и связях друг с другом, которое образует определённую целостность, единство) для конкретных проверок ищет сначала в /sbin, а потом в /etc/fs и /etc/, и, наконец в директориях, перечисленных в переменной PATH (среда переменного кружения).
Запуск и исполнение FSCK на смонтированной файловой системе может привести к повреждению данных, поэтому применяйте данный материал на свой страх и риск.
Автор не несет ответственности за любой вред, который вы можете причинить. Fsck расшифровывается как «File System ChecK», то есть «испытание файловой системы» и используется для проверки и исправления файловых систем в Linux. В качестве верифицируемой ФС может быть задан раздел (например, /dev/sda1 или /dev/sda8), точка монтирования (/, /home, /usr), или же точна тома или UUID (например, UUID=8868abf6-88c5-4a83-98b8-bfc24057f7bd или LABEL=root).
Как обычно fsck пытается параллельно проверять файловые системы на нескольких разделах для уменьшения времени, нужного для проверки всех файловых систем. Arch Linux при загрузке автоматически будет бросать fsck для проверки систем, если выполняется одно из требований (например, 180 суток работы системы без проверки разделов или 30 монтирований оных). Обычно нет необходимости переопределять проем между проверками.
Для того, чтобы проверить диск в Linux на наличие опечаток файловой системы нам необходимо сначала выяснить имена файловых систем командой:
df -h
Дальше нам необходимо размонтировать файловую систему, которую мы будем проверять командой:
umount /dev/hda1
И сейчас запускаем утилиту проверки файловой системы и исправления ошибок на ней командой
fsck /dev/hda1
В том варианте, когда не представляется возможным размонтировать файловую систему, к примеру, когда нужно испробовать корневую файловую систему (/). Перезагрузиться в однопользовательском режиме (команда reboot, и при загрузке необходимо передать ядру параметр single). Перемонтировать корневую файловую систему в режиме «лишь чтение» командой.
mount -о remount rо -t ext3 /
Здесь параметр -о команды mount указывает на присутствие дополнительных опций. Опция remount rо означает перемонтировать в режиме «только чтение». Метеопараметр -t указывает тип файловой системы – ext3, а последний параметр – указывает что это корневая файловая система (/).
И сейчас проверить файловую систему
fsck -y -f -c /dev/hda1
Проверка диска на битые секторы в linux с поддержкою smartmontools
Теперь давайте рассмотрим более современный и надежный способ проверить диск на колоченные секторы linux. Современные накопители ATA/SATA ,SCSI/SAS,SSD имеют встроенную систему самодисциплины S.M.A.R.T (Self-Monitoring, Analysis and Reporting Technology, Технология самоконтроля, анализа и отчетности), которая изготовляет мониторинг параметров накопителя и поможет определить ухудшение параметров работы накопителя на ранешних стадиях. Для работы со S.M.A.R.T в Linux есть утилита smartmontools. Давайте перейдем к работе с утилитой. Включим следующую команду с параметром -H,чтобы утилита показала нам информацию о состоянии накопителя:
sudo smartctl -H /dev/sda1
Как видим, проверка диска («круглое блюдо») — круг (низкий цилиндр) или предмет в виде круга) на битые секторы linux завершена и утилита говорит нам, что с накопителем все в распорядке! Дополнительно, можно указать следующие параметры -a или —all, чтобы получить еще больше информации о накопителе, или -x и —xall, дабы просмотреть информацию в том числе и об остальных параметрах накопителя.
Is there a way to fsck/chkdsk an NTFS drive from Linux?
asked Jan 15, 2011 at 21:33
Yes. This was handled by fsck on some releases. If the partition is not listed in /etc/fstab, then you will likely need to tell it the partition type. I’ve used this from a Linux CD to recover a partition Windows wouldn’t boot from.
Based on the comments below, the actual fixing is done by the ntfsfix program. It should be available, even if there is no program to run a fsck on an NTFS file system.
answered Jan 15, 2011 at 21:44
BillThorBillThor
10.7k2 gold badges24 silver badges23 bronze badges
2
Unfortunately the ntfsfix tool is very limited compared to Microsoft’s chkdsk. Try to get a Windows install going — preferably with the newest version of Windows as Microsoft is presumably constantly improving chkdsk (I hope..) New versions of Windows are often available for free as trials. If the problem is in a USB disk you can try installing Windows in something like VirtualBox and give the VM control of the USB device.
answered Jan 1, 2012 at 5:27
eugeug
8348 silver badges12 bronze badges
5
ln -s /bin/ntfsfix /sbin/fsck.ntfs
fsck /dev/sdg1
fsck from util-linux 2.21.2
Mounting volume... OK
Processing of $MFT and $MFTMirr completed successfully.
Checking the alternate boot sector... FIXED
NTFS volume version is 3.1.
NTFS partition /dev/sdg1 was processed successfully.
On fedora 22, there is another binary :
lrwxrwxrwx. 1 root root 13 May 22 22:13 /usr/sbin/fsck.ntfs -> ../bin/ntfsck
answered Jun 9, 2015 at 18:15
TanguyTanguy
1791 silver badge1 bronze badge
In my case, none of fsck & ntfsfix could fix the issue of my external NTFS mobile disk.
I end up to boot into windows os, and use follow steps to fix the disk issue.
Steps:
- Check the identifier of the bad disk. e.g
g - Open the «cmd» terminal of windows.
- Input
chkdsk <disk>: /fto fix it.
Where<disk>is the identifier, e.gchkdsk d: /f - Then it would be fixed within seconds (For a disk of size 1Tb).
After years, finally I found something that windows can do easily, but linux can’t 😉
@Update — vm solution
You can also create a windows vm (e.g win 7), then mount the mobile disk to windows vm, then you can also use chkdsk to fix the disk, it’s similar as boot into a windows machine.
answered Mar 30, 2018 at 10:15
![]()
EricEric
2734 silver badges10 bronze badges
2
If you have NTFSProgs installed, you should be able to run fsck.ntfs or fsck -t ntfs to fsck an NTFS drive.
answered Jan 15, 2011 at 21:45
squirclesquircle
6,6715 gold badges36 silver badges68 bronze badges
5
Is there a way to fsck/chkdsk an NTFS drive from Linux?
asked Jan 15, 2011 at 21:33
Yes. This was handled by fsck on some releases. If the partition is not listed in /etc/fstab, then you will likely need to tell it the partition type. I’ve used this from a Linux CD to recover a partition Windows wouldn’t boot from.
Based on the comments below, the actual fixing is done by the ntfsfix program. It should be available, even if there is no program to run a fsck on an NTFS file system.
answered Jan 15, 2011 at 21:44
BillThorBillThor
10.7k2 gold badges24 silver badges23 bronze badges
2
Unfortunately the ntfsfix tool is very limited compared to Microsoft’s chkdsk. Try to get a Windows install going — preferably with the newest version of Windows as Microsoft is presumably constantly improving chkdsk (I hope..) New versions of Windows are often available for free as trials. If the problem is in a USB disk you can try installing Windows in something like VirtualBox and give the VM control of the USB device.
answered Jan 1, 2012 at 5:27
eugeug
8348 silver badges12 bronze badges
5
ln -s /bin/ntfsfix /sbin/fsck.ntfs
fsck /dev/sdg1
fsck from util-linux 2.21.2
Mounting volume... OK
Processing of $MFT and $MFTMirr completed successfully.
Checking the alternate boot sector... FIXED
NTFS volume version is 3.1.
NTFS partition /dev/sdg1 was processed successfully.
On fedora 22, there is another binary :
lrwxrwxrwx. 1 root root 13 May 22 22:13 /usr/sbin/fsck.ntfs -> ../bin/ntfsck
answered Jun 9, 2015 at 18:15
TanguyTanguy
1791 silver badge1 bronze badge
In my case, none of fsck & ntfsfix could fix the issue of my external NTFS mobile disk.
I end up to boot into windows os, and use follow steps to fix the disk issue.
Steps:
- Check the identifier of the bad disk. e.g
g - Open the «cmd» terminal of windows.
- Input
chkdsk <disk>: /fto fix it.
Where<disk>is the identifier, e.gchkdsk d: /f - Then it would be fixed within seconds (For a disk of size 1Tb).
After years, finally I found something that windows can do easily, but linux can’t 😉
@Update — vm solution
You can also create a windows vm (e.g win 7), then mount the mobile disk to windows vm, then you can also use chkdsk to fix the disk, it’s similar as boot into a windows machine.
answered Mar 30, 2018 at 10:15
![]()
EricEric
2734 silver badges10 bronze badges
2
If you have NTFSProgs installed, you should be able to run fsck.ntfs or fsck -t ntfs to fsck an NTFS drive.
answered Jan 15, 2011 at 21:45
squirclesquircle
6,6715 gold badges36 silver badges68 bronze badges
5