AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / computer / Perguntas / 1508109
Accepted
ConductedForce
ConductedForce
Asked: 2019-12-07 15:08:14 +0800 CST2019-12-07 15:08:14 +0800 CST 2019-12-07 15:08:14 +0800 CST

Recuperação de tabela GPT

  • 772

Eu me incluo nas fileiras de usuários que não sabem ler e quebrar suas próprias coisas.

No domingo passado, ao tentar copiar uma partição NTFS do Windows 7 maior para uma menor, estraguei o que acredito ser a tabela de partições em um disco rígido de 3 TB. Para contexto:

sdb (3TB drive/partition)
sdh2 (1.57 TB partition)(2TB drive)

Eu estava executando o PartedMagic 2018 (e ainda estou) e digitei o seguinte:

sgdisk -R /dev/sdb /dev/sdh2

Percebi quando abri o Gparted que digitei o comando errado. Ele foi listado em uma pergunta do SE como uma resposta para corrigir um problema relacionado à mudança de uma partição maior para uma menor. A resposta foi digitada assim:

sgdisk -R /dev/sdY /dev/sdX
where:
sdX = Disk A
sdY = Disk B

Bonehead se move para o lado, agora estou no controle de danos. Comecei a seguir este guia dos Fóruns do Ubuntu e atualmente comecei a escanear a unidade em busca de cabeçalhos de partição para que eu possa recuperar a unidade inteira.

Eu digitei o seguinte comando até agora: gpart /dev/sdb. Ele está verificando a unidade há cerca de 4 dias e 20 horas.

Eu tenho algumas perguntas sobre o meu procedimento aqui:

  1. Quanto tempo isto irá levar? Minhas melhores estimativas foram olhar para a luz de atividade do HDD e contar no máximo uma piscada por segundo. Presumi que o piscar único era um setor lido e que cada setor era 4096 (está em uma unidade flash). 2.720.000 MB na unidade de 3 TB em um tempo de leitura de 4 MB por segundo me dá cerca de 7,87 dias. O tempo mais curto seria o dobro dessa velocidade, e já estaria feito. A última saída de "partição possível" foi há dois dias e deu um deslocamento de 1421742 mb, enquanto o primeiro possível foi um deslocamento de 1 mb. Eu vi em algum lugar que os tamanhos dos setores podem ser menores. Estou perto?

  2. Estou tomando um curso de ação adequado para resgatar meu impulso? O guia dos fóruns do Ubuntu parece sólido e muito relacionável. Eu só tenho uma partição que tinha na unidade, havia mais anteriormente, mas eu a limpei e comecei de novo com apenas uma. Era a única partição listada antes do acidente e usava toda a unidade, pelo que me lembro. Não tenho certeza se havia uma daquelas seções não utilizadas de vários MB nele ou não (esse estranho ponto não particionado em branco que às vezes é feito no GParted quando você faz uma partição, ele será precedido por 1mib não utilizado).

  3. Se eu restaurar a partição usando partede não adicionar todos os setores, ou adicionar muitos, os dados ainda serão exibidos nessa partição? O guia diz para usar as unidades de setores para reconstruir a tabela de partições. Se eu usar poucas ou muitas unidades, os dados ainda serão exibidos quando eu montar a unidade e lê-los?

  4. Eu li que há uma tabela de partições primária e secundária ou algo assim, elas existem, posso copiá-las, como as visualizaria para confirmar qual delas desejo para recuperação?

Preciso de uma segunda opção de controle de danos além de enviá-lo para um serviço profissional. Este não é um computador comercial, mas há algumas coisas importantes a serem recuperadas.

Objetivo final: recuperar a partição única na unidade de 3 TB.

Atualização: verificação pós-gpart

Conforme visto nas imagens de referência, a verificação falhou perto do final da unidade. Desde então, coloquei a unidade em um computador mais novo onde executei arquivos TestDisk. A varredura rápida encontrou parte do que gpartvi, mas não o que sei que está lá. Usei a opção Deeper Scan, onde em poucos minutos ele detectou a partição em questão, chamada Big Mongo. Foi assim que chamei a unidade no Windows.

Atualização 2: Varredura Post TestDisk

O TestDisk foi concluído (veja as fotos de referência adicionais) e identificou minha partição ausente. Eu sou capaz de listar arquivos dentro do programa. Observe o tamanho na parte inferior da digitalização concluída. A varredura foi concluída em 10 horas em vez de 8 dias de gpart.

Conclusão: Para mentes inquisitivas

Depois de executar o TestDisk, ele encontrou a partição, mas criou a tabela incorretamente, então executei gdiske reconstruí usando 2048o tamanho inicial e o tamanho máximo como final (consulte a resposta marcada). Teve em hibernação, inicializou sem problemas.

Imagens de referência
gdisk -l para comentários https://isstatic.askoverflow.dev/9znYj.jpg
gpart scan 1/2 https://isstatic.askoverflow.dev/rWxuC.jpg
gpart scan 2/2 https:/ /i.stack.imgur.com/HQYJ8.jpg

Verificação rápida do TestDisk

insira a descrição da imagem aqui

Verificação mais profunda do TestDisk preliminar

insira a descrição da imagem aqui

TestDisk Completo

insira a descrição da imagem aqui

partitioning gpt
  • 1 1 respostas
  • 6463 Views

1 respostas

  • Voted
  1. Best Answer
    Kamil Maciorowski
    2019-12-12T03:48:52+08:002019-12-12T03:48:52+08:00

    Análise

    O comando que você usou

    sgdisk -R /dev/sdb /dev/sdh2
    

    copiou a tabela de partição GUID (GPT) de /dev/sdh2para /dev/sdb.

    One problem is /dev/sdh2 is a partition. Any partition has no meaningful partition table. Or at least it shouldn't have one. I can imagine a meaningful partition table inside a partition (and even make it kinda work) but this is cumbersome, exotic, not really useful.

    The resulting copy is an empty GPT because apparently the relevant (yet not meaningful) values inside /dev/sdh2 resulted in such table. This doesn't really matter.

    What matters is you overwrote the original GPT on /dev/sdb. The command you used modified only the partition table, all other structures are expected to exist still. The filesystem itself should be fine (unless your later tries to recover happened to be unfortunate enough to corrupt it). You only lost a convenient way to get to the filesystem. Please read this answer of mine, its initial part summarizes the difference between partition and filesystem.

    Your goal now is to restore the original GPT somehow. Note your situation is as if you were in the middle of the procedure described in the mentioned answer: you have destroyed the partition table entry but not created a new one yet. The difference is you don't necessarily want to create a larger partition and you don't know the offset (starting sector) where the partition should begin.

    GPT consists of primary and secondary (backup) table. The secondary table cannot help you in restoring the old state because sgdisk -R modified both tables in order to leave the whole GPT in a consistent state.


    Finding offset

    There are tools able to scan a disk, find filesystem signature(s), read filesystem size from the signature and propose a partition table entry that will properly embed the filesystem into a newly defined partition, so it can be easily mounted. One such tool is testdisk. If only the old partition table was wiped out, testdisk should be able to find the filesystem and to create a sane GPT. Scanning may take a while.

    Alternatively you may try to guess the right offset. The fact you had just one partition is an advantage.

    Please read this another answer of mine. In your case (logical sector size of 512) the most probable starting sector is 2048 and the command that may work is:

    mount -o ro,offset=$((512*2048)) /dev/sdb /some/mountpoint/
    

    Mounting read-only will not affect data that survived so far, so it should be safe to try. If the command succeeds and you verify files and directories appear under /some/mountpoint/, then it means the offset is right.

    Note 512*2048 is exactly 1 MiB. In one of the screenshots you have:

    Possible partition … offset(1mb)
    

    I think this is the one. It would most likely be found by testdisk as well if you used this tool.


    Creating partition table entry manually

    If you chose not to use testdisk (or similar), found the offset that seems right, then you can create a partition table with sane entry manually (with gdisk, sgdisk or any tool able to do this). Follow these hints:

    • If the filesystem is mounted (e.g. mount -o ro,offset=… … from the previous paragraph), umount it.
    • Keep it GPT. If the logical sector size is right, it's very unlikely you originally had DOS partition table in MBR. Even if you had, it's impossible the partition starting at the sector 2048 reached the end of the disk. So it's safe to create a secondary GPT at the very end of the disk, even if originally there was none (besides sgdisk -R has already written one anyway, you cannot make it worse). But please see "possible problems" section later in this answer, just in case.
    • The starting sector should be 2048 because this is the offset you found.
    • The size should be equal or greater than the size of the filesystem. For now the only hint you have is size(764432mb), I'm not sure if mb here means MB or MiB, or if it's not totally wrong. The safest approach is to (temporarily) use the maximal value you can for the ending sector. By another screenshot I believe the maximal value for the ending sector is 5860533134.
    • The [partition type GUID] should be the right one for NTFS: EBD0A0A2-B9E5-4433-87C0-68B6B72699C7. Note in gdisk you can use a short code of 0700 for this.
    • The tool mustn't touch the filesystem, it shall only affect the partition table. If it tries to format (mkfs) the "new" partition or wipe it (wipefs), it's not the right tool. I believe gdisk is safe. I would be very careful with GUI all-in-one partitioning tools (including Windows native tool(s)). Frankly in this case "very careful" means I wouldn't use them at all.

    After you create a proper entry and write the new partition table to the device, /dev/sdb1 should appear. If it doesn't appear, invoke partprobe.

    Confirm you are able to mount /dev/sdb1.


    Adjusting size

    Now when there is /dev/sdb1 available, you can easily query the filesystem for its size. I mean what the filesystem knows its size is. In general this is different than the size of corresponding partition. There are at least two tools you can use:

    • file -s /dev/sdb1
      

      You are interested in where it says sectors NNNNNN. Do not worry about hidden sectors (compare similar doubt for FAT).

    • ntfsresize --info /dev/sdb1
      

      You are interested in "Current volume size". Express it in 512-byte sectors (i.e. divide by 512).

    The number calculated from the output of ntfsresize may be little different than what file says. I think this has something to do with cluster size. In my tests it seems after mkfs.ntfs is asked to use a whole partition, file reports one sector less than the number of sectors in the partition. So use rather file, not ntfsresize, identify sectors NNNNNN, add one. This is how big the partition needs to be. In case of any doubt add 2048 sectors. It's overkill, but only 1 MiB of wasted space, not a lot; it will keep you safe for sure.

    If the partition (created in the previous paragraph) is bigger, you may want to shrink it. I note your final goal was to copy the filesystem to a smaller disk; and there is this Possible partition … size(764432mb) … in one of the screenshots. This makes me believe the filesystem is indeed smaller than the new partition. This is not a problem by itself, but if you'd like to create another partition after where the filesystem ends, or if you still want to copy the setup to a smaller disk, shrinking the partition is a good idea.

    The procedure:

    1. umount the filesystem if mounted.
    2. Remove the entry from the partition table.
    3. Create a new entry like in the previous paragraph, but this time specify the number of sectors just calculated. Note we're talking about the size of the new partition, not the end sector. If you need to know the end sector, use this formula: start+size-1=end. The alignment of the end of any partition shouldn't matter (it matters for the beginning) but if the tool insists to move the end slightly towards the end of the disk, let it.
    4. Save the partition table, run partprobe just in case.
    5. Verify that /dev/sdb1 mounts without errors. At first mount read-only (mount -o ro …) just in case.

    If the filesystem mounts fine, you're basically done. The partition table is now sane.


    Possible problems

    • The new partition will have a new unique partition GUID. On the other hand the "UUID" stored in the filesystem remains. You may need to reconfigure any tool/OS that relies on the former (or retrieve the old value from some configuration and apply it to the new partition, this single move will make all such configs valid again). I don't know which ID Windows uses to tell if it has seen the partition/filesystem before.
    • I can see the disk reports logical/physical sector size as 512/4096. Please read this question and the explanation in my answer to it. If there is at least one USB enclosure involved and the disk used to be connected differently than it is now (i.e. in a different enclosure; or via SATA now, in enclosure earlier; or vice versa) and you haven't verified that /dev/sdb1 mounts before you invoked sgdisk -R, then maybe the original (lost) partition table was valid for logical size of 4096; and if you tried to mount the partition before the mishap then you would experience the same problem as in the linked question. My point is my answer helps you create a partition table valid for the current setup. If this problem was going to hit you, it will hit you when you connect the drive in the original setup. Then you would need to adjust the partition table again. My answer to the linked question will help.
    • If the above bullet applies and if size(764432mb) is wrong then it's possible you had (and overwrote) a DOS partition table in MBR (not GPT) that defined one large partition spanning to the very end of the disk, and the filesystem itself spanned to (almost) the very end of the disk. In such case sgdisk -R created the secondary (backup) GPT at the end where a part of the filesystem should be. If the filesystem mounts fine then this is probably not the case. In general it may be. This is a scenario where you actually may have lost data; and you may lose more unless you fix it (ask a separate question if needed).

      Note if you're sure you had GPT then you're safe (because the secondary table was "always" there). And if you're sure the previous bullet doesn't apply then you're safe (because with logical sector size of 512 and with DOS partition table in the MBR the partition starting at the sector 2048 couldn't span to the end of your large disk).

    After you fix the partition table you will probably want to continue with your original plan. Then:

    • The other disk may have a different logical sector size. I'm not sure if (properly used) sgdisk -R recalculates entries between different sizes. I expect it to. In case it doesn't, you know what to do.
    • But maybe you wanted to clone the only partition of /dev/sdb (i.e. /dev/sdb1 or so) to /dev/sdh2; and there is /dev/sdh1 you want to keep. If so, sgdisk -R is not what you want to do. Copying the partition table from /dev/sdb to /dev/sdh2 (which is a partition) will give you nothing. Copying it to /dev/sdh will replace the current partition table there and mess with the current /dev/sdh2 (and /dev/sdh1 if any). Use sgdisk -R only if the target disk contains no data you want to keep. In case of any doubt ask a separate question after you fix the partition table of /dev/sdb. The new question should contain the output of gdisk -l (or fdisk -l) para ambos os discos e você deve indicar claramente quais partições deseja clonar para onde, quais partições são dispensáveis ​​e quais partições devem ser deixadas intactas.
    • 1

relate perguntas

  • Alterar o GUID da partição (tipo)?

  • Instalando o Ubuntu em um disco rígido de backup em espaço não alocado

  • Como limpar completamente o disco do laptop para uma nova instalação do Ubuntu?

  • Tamanho da partição 128 GB, mas apenas 64 GB detectados [duplicado]

  • Devo particionar um SSD secundário (sem sistema operacional) usado para armazenamento? [fechado]

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    O visualizador de fotos do Windows não pode ser executado porque não há memória suficiente?

    • 5 respostas
  • Marko Smith

    Como faço para ativar o WindowsXP agora que o suporte acabou?

    • 6 respostas
  • Marko Smith

    Área de trabalho remota congelando intermitentemente

    • 7 respostas
  • Marko Smith

    Serviço do Windows 10 chamado AarSvc_70f961. O que é e como posso desativá-lo?

    • 2 respostas
  • Marko Smith

    O que significa ter uma máscara de sub-rede /32?

    • 6 respostas
  • Marko Smith

    Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows?

    • 1 respostas
  • Marko Smith

    O VirtualBox falha ao iniciar com VERR_NEM_VM_CREATE_FAILED

    • 8 respostas
  • Marko Smith

    Os aplicativos não aparecem nas configurações de privacidade da câmera e do microfone no MacBook

    • 5 respostas
  • Marko Smith

    ssl.SSLCertVerificationError: falha na verificação do certificado [SSL: CERTIFICATE_VERIFY_FAILED]: não foi possível obter o certificado do emissor local (_ssl.c:1056)

    • 4 respostas
  • Marko Smith

    Como posso saber em qual unidade o Windows está instalado?

    • 6 respostas
  • Martin Hope
    Albin Como faço para ativar o WindowsXP agora que o suporte acabou? 2019-11-18 03:50:17 +0800 CST
  • Martin Hope
    fixer1234 O "HTTPS Everywhere" ainda é relevante? 2019-10-27 18:06:25 +0800 CST
  • Martin Hope
    Kagaratsch O Windows 10 exclui muitos arquivos minúsculos muito lentamente. Algo pode ser feito para agilizar? 2019-09-23 06:05:43 +0800 CST
  • Martin Hope
    andre_ss6 Área de trabalho remota congelando intermitentemente 2019-09-11 12:56:40 +0800 CST
  • Martin Hope
    Riley Carney Por que colocar um ponto após o URL remove as informações de login? 2019-08-06 10:59:24 +0800 CST
  • Martin Hope
    zdimension Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows? 2019-08-04 06:39:57 +0800 CST
  • Martin Hope
    Inter Sys Como Ctrl+C e Ctrl+V funcionam? 2019-05-15 02:51:21 +0800 CST
  • Martin Hope
    jonsca Todos os meus complementos do Firefox foram desativados repentinamente, como posso reativá-los? 2019-05-04 17:58:52 +0800 CST
  • Martin Hope
    MCK É possível criar um código QR usando texto? 2019-04-02 06:32:14 +0800 CST
  • Martin Hope
    SoniEx2 Altere o nome da ramificação padrão do git init 2019-04-01 06:16:56 +0800 CST

Hot tag

windows-10 linux windows microsoft-excel networking ubuntu worksheet-function bash command-line hard-drive

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve