Linux detect file type

Using the linux ‘file’ command to determine type (ie. image, audio, or video)

The word file here refers to the shell file command, and not actual files. I want to determine whether a file is a, for example, video file ( .mpg , .mkv , .avi ). file is pretty good at returning image for image files, video for video files, and audio for audio files (and application/x-empty for some reason for text). My question is how reliable this is for identifying types. If I did a simple

file -ib deliverance.avi | grep video 

3 Answers 3

The results from file are less than perfect, and it has more problems with some types of files than others. File basically just looks for particular pieces of binary data in predictable patterns to figure out filetypes.

Unfortunately, in particular, some of the filetypes often used for video fall into this «problematic» category. The newer container formats like .mp4 and .mkv usually have several different MIME types that should properly depend on what type of data is being contained. For example, an .mp4 could properly be identified as video/mp4 , audio/mp4 , or application/mp4 depending on the content.

In practice, file often makes guesses that simply conform with common usage, and it may work perfectly well for you. For example, while I mentioned some theoretical difficulties with identifying Matroska files correctly, file basically just assumes that any Matroska file is a video. On the other hand, the usage of the Ogg container is more evenly split between audio and video, and I believe the current version of file just splits the difference, and identifies Ogg files as application/ogg , which wouldn’t fall into any of your categories.

The one thing I can say with certainty is that you want the most up-to-date version of file you can get your hands on. The «magic» files that contain the patterns to match against and the MIME types that will result from a match are updated fairly often to include newer filetypes like WebM, or just to improve accuracy for older types.

Читайте также:  Изменить порядок загрузки операционных систем linux windows

Источник

HackWare.ru

Этичный хакинг и тестирование на проникновение, информационная безопасность

Как узнать тип файла без расширения (в Windows и Linux)

Если вы попали сюда из поиска и вам нужно просто быстро узнать расширение файла, то к ваших услугам онлайн сервис «Определение типа файла без расширения»: https://suip.biz/ru/?act=file-type. Благодаря ему вам не понадобится устанавливать какие-либо программы, онлайн сервис за секунду определит тип файла, который вы прислали, причём покажет результаты сканирования сразу четырьмя программами, рассмотренными в этой статье. Заодно выведет найденную в файле метаинформацию — часто там есть что-то интересное.

Если вы из тех, кто хочет узнать как работают инструменты указанного сервиса, а также как ими пользоваться на своём компьютере, то продолжайте читать.

Если вам кажется, что проблема с определением типов файлов без расширений надуманная, то это далеко не так! Во-первых, если подумать, это не такая уж простая задача. А с файлом без расширения вы можете столкнуть, например, при декодировании строки из Base64 кодировки.

Во-вторых, у этой статьи будет продолжение, в которой эти же самые инструменты, которые вы изучите на этой странице, будут использоваться для:

1) разбора прошивок (например, роутеров, IP камер) на составные части (первый этап обратной инженерии либо анализа работы устройств для поиска уязвимостей и бэкдоров)

2) поиска файловых систем на дисках и их образах (первый этап криминалистической IT экспертизы)

3) поиска удалённых файлов

Как определить тип данных, если у файла нет расширения

Если у файла нет расширения, то единственным вариантом определения его типа остаётся содержимое этого файла. Можно попробовать добавлять различные расширения к имени файла и пытаться открыть соответствующими для этого расширения программами — этот вариант медленные и неэффективный.

Определённые типы бинарных файлов могут иметь одинаковый набор байтов — по этим байтам можно сопоставить тип файлов. И именно данный метод и применяется программами, предназначенными для определения типа данных. Специфичные байты как правило располагаются не в самом начале файла, поэтому кроме самих байтов, нужно знать смещение от начала, где эти байты должны находиться. Некоторые программы в дополнении к байтам для идентификации ещё имеют список для проверки на ложное срабатывание.

Читайте также:  Linux узнать какие службы запущены

Такие паттерны на английском часто называют magic — это пошло от «magic number» в исполнимых файлах. Эти файлы имеют «магическое число», хранящееся в определённом месте рядом с началом файла, которое сообщает операционной системе UNIX, что файл является двоичным исполняемым файлом и каким именно из нескольких типов. Концепция «магического числа» была применена к другим бинарным файлам. То есть файлы одинакового типа имеют одинаковую последовательность байтов в определённом месте от начала файлов.

Файл с сигнатурами, описывающими какие именно байты, на каком расстоянии от начала файла характерны для файлов того или иного типа, обычно называют magic file.

Чтобы понять количество проделанного труда при поиске уникальных байтов, обязательно присутствующих в тех или иных файлах, посмотрите на магический файл для определения файловых систем https://github.com/file/file/blob/master/magic/Magdir/filesystems

Это только один файл из перечня различных типов файлов: https://github.com/file/file/tree/master/magic/Magdir

Кроме магических чисел могут применяться и другие техники, например, программа file для проведения тестов файловых систем также может использовать системный вызов stat. Тип текстовых файлов определяется по содержащимся в них строкам (например, это может быть PHP код, файл в XML или HTML разметке, JSON и так далее).

Команда file — мгновенное определение типа любого файла

В Linux есть команда file с огромной базой сигнатур, которая очень быстро определяет тип файла:

Чтобы узнать, что за файл без расширения, выполните команду вида:

Источник

How to Find Out File Types in Linux

The easiest way to determine the type of a file on any operating system is usually to look at its extension (for instance .xml, .sh, .c, .tar etc..). What if a file doesn’t have an extension, how can you determine its type?

Linux has a useful utility called file which carry out some tests on a specified file and prints the file type once a test is successful. In this short article, we will explain useful file command examples to determine a file type in Linux.

Читайте также:  Minecraft linux нет звука

Note: To have all the options described in this article, you should be running file version 5.25 (available in Ubuntu repositories) or newer. CentOS repositories have an older version of file command (file-5.11) which lacks some options.

You can run following command to verify the version of file utility as shown.

$ file -v file-5.33 magic file from /etc/magic:/usr/share/misc/magic

Linux file Command Examples

1. The simplest file command is as follows where you just provide a file whose type you want to find out.

Find File Type in Linux

2. You can also pass the names of the files to be examined from a file (one per line), which you can specify using the -f flag as shown.

Find Files Type in Filename List

3. To make file work faster you can exclude a test (valid tests include apptype, ascii, encoding, tokens, cdf, compress, elf, soft and tar) from the list of tests made to determine the file type, use the -e flag as shown.

$ file -e ascii -e compress -e elf etc

4. The -s option causes file to also read block or character special files, for example.

$ file -s /dev/sda /dev/sda: DOS/MBR boot sector, extended partition table (last)

5. Adding the -z options instructs file to look inside compressed files.

Determine Compressed Files

6. If you want to report information about the contents only not the compression, of a compressed file, use the -Z flag.

7. You can tell file command to output mime type strings instead of the more traditional human readable ones, using the -i option.

$ file -i -s /dev/sda /dev/sda: application/octet-stream; charset=binary

8. In addition, you can get a slash-separated list of valid extensions for the file type found by adding the –extension switch.

For more information and usage options, consult the file command man page.

That’s all! file command is a useful Linux utility to determine the type of a file without an extension. In this article, we shared some useful file command examples. If you have any questions or thoughts to share, use the feedback form below to reach us.

Источник

Оцените статью
Adblock
detector