Как открыть бинарный файл в linux

от admin

Как запустить бинарный файл?

Господа специалисты как запустить бинарный файл?И можно ли с диска Ubuntu 7.10 взять дрова для установленной Mandriva.

Re: Как запустить бинарный файл?

>И можно ли с диска Ubuntu 7.10 взять дрова для установленной Mandriva.

можно, но не человеку который не знает:

>как запустить бинарный файл

chmod +x file && ./file

Re: Как запустить бинарный файл?

>chmod +x file && ./file Спасибо попробую.Учится не когда не поздно.

Лучшие HEX редакторы Linux

HEX-редактор — это приложение, с помощью которого можно просмотреть и отредактировать файл, содержащий двоичные данные (записанные при помощи комбинаций из цифр 0 и 1), перекодировав его в 16-ричный формат.

А поскольку все без исключения файлы хранятся в памяти компьютера именно в таком виде, использование программ, позволяющих работу с HEX, открывает широкие возможности для различных манипуляций с данными (например, для восстановления поврежденных текстовых и графических документов). Некоторые HEX редакторы предназначены для анализа и редактирования данных с HDD и съемных накопителей — их называют редакторами дисков или редакторами секторов.

Рабочее окно стандартного HEX-редактора разделено на три области. Справа расположена так называемая область символов, в центральной части — область 16-ричного кода и слева — область адресов. В наше время пользователям Linux доступно множество таких программ — каждый может выбрать ту, которая окажется максимально полезной в конкретной ситуации. В этой статье мы собрали лучшие hex редакторы linux.

Лучшие HEX редакторы для Linux

Порой информация, которая хранится на каких-либо носителях, повреждается из-за ошибок в работе системы. В таком случае нет смысла изобретать велосипед и придумывать специальную программу для извлечения данных. Гораздо эффективнее будет использование HEX-редактора. Мы отобрали 20 лучших программ и подготовили их обзор.

1. Vim

Vim служит для редактирования текстовых файлов в шестнадцатеричной системе. В работе он задействует внешний инструмент «xxd», который входит в базовый набор некоторых дистрибутивов Linux. Такое «сотрудничество» иногда становится причиной ошибок в работе редактора.

Преобразование файлов происходит после применения команд:

  • :%! xxd — для конвертирования файла в 16-ричный формат;
  • %! xxd -r — для возвращения к исходному варианту.

2. Hexedit Hex Editor

Hexedit — простой и надежный HEX editor linux. Среди прочих выделяется наличием большого количества опций (быстрый поиск и/или сравнение, подсветка символов, EBCDIC, применение цветовых схем, режимы INS/OVR, закладки. отслеживание изменений.

  • Hexedit используется в работе таких функций ПК как макросы, нажатия клавиш, фоновый поиск, редактор дисков и другие.
  • Настройка подсказок, калькулятор, шаблоны. Поддержка файлов, размер которых превышает 4 Гб.
  • Наличие инструментов Auto-hide tool windows (для быстрого скрытия окон) и Docking tool windows (для закрепления окон).
  • По команде пользователя Hexedit может получать доступ к памяти компьютера, всем дискам и файлам.

3. Ghex – GNOME Hex Editor

Ghex — это бесплатный редактор, который кроме 16-ричного формата поддерживает и ASCII. Спектр использования этой программы очень широк, в частности, она позволяет обманывать систему к компьютерных играх и получать дополнительные очки либо жизни для персонажей.

  • Многошаговые команды Undo (отмена) и Redo (повтор).
  • Поиск функций в файлах и их замена.
  • Отслеживание взаимодействий между восьмеричным, двоичным, шестнадцатеричным и десятичным кодами.
  • Настраиваемый MDI.

4. Bless Hex editor

Bless — редактор с открытым исходным кодом, быстрый в работе и простой в настройке. Его интерфейс собран на GTK. Обеспечивает удобную работу с большими файлами, позволяет отменять и повторять действия.

  • Управление при помощи клавиатуры.
  • Функция поиска и замены файлов.
  • Возможность копировать и вставлять текст.
  • Блокировка устройств и редактирование большого количества файлов.

5. Okteta Editor

Изначально это приложение было разработано для программистов, однако, пригодится и обычным пользователям, у которых возникла потребность работать с файлами на уровне байтов и редактировать hex linux.

6. wxHexEditor

Мощный инструмент, поддерживающий различные типы файлов, аксессуары и тэги, размер которых может исчисляться в Эксабайтах (1 Эб = 10 18 байт). В большей степени его использование имеет смысл для программистов.

7. HexCurse

Написан на языке C на основе ncurses. Нравится пользователям из-за наличия большого числа функций. Среди прочего, он позволяет изменять сочетания клавиш, использующиеся для управления программой.

8. Hexer

Бесплатный HEX редактор Linux, который умеет только загружать весь файл целиком, что не позволяет редактировать отдельные блоки. Впрочем, есть у него и преимущества — например, функция редактирования в командной строке, многоуровневая команда отмены (Undo) и множественные буферы.

9. Dhex Hex Editor

Эта программа работает на базе ncurses, а в качестве дополнения разработчики снабдили ее функцией сравнения файлов. При желании можно активировать и режим визуализации. Зачастую используется для преобразования дискретных байтов в файлы большого размера.

10. Jeex Hex Editor

Jeex может похвастаться открытым исходным кодом, который был написан на языке Gtk + и опубликован под публичной лицензией GNU. Позволяет выполнять операции в двоичном, восьмеричном, десятичном и шестнадцатеричном форматах. На данный момент является одним из лучших HEX-редакторов.

11. Binary Ninja

Платная программа, написанная на Python и опубликованная под лицензией GPLv2. Особенность этой программы — она рассчитана в первую очередь на реверс-инжиниринг. Все желающие могут скачать демо-версию и в течение 25 минут протестировать Binary Ninja с урезанным количеством опций.

Особенности программы:

  • Графики с синопсисами, позволяющими просмотреть и проанализировать информацию о заданной в данный момент функции.
  • Благодаря подменю, выбранные плагины можно объединять в отдельные группы.
  • Улучшенная работа PE-анализатора и PE-парсера.
  • Доступ к логам осуществляется посредством нажатия на строку с адресом.
  • Binary Ninja помогает найти нужную библиотеку для выполнения той или иной бинарной функции.

12. Fileobj Hex Editor

Fileobj был написан на python и основывается на ncurses. Интерфейс этого HEX-редактора напоминает Vi, соответственно, у этих программ много одинаковых функций. Кроме того, Fileobj умеет выполнять большинство команд Vi, что удобно для пользователей.

13. Joe Hex Editor

Джо — еще один HEX-редактор на ncurses, доступный пользователям Linux. Имеет пользовательский mode-less интерфейс, который весьма прост в использовании. Доступ к справочным материалам предоставляется через специальную кнопку на экране.

  • Для упрощения работы можно использовать комбинации клавиш.
  • Настройка конфигураций.
  • Поддержка всех популярных форматов файлов.

14. VBdiff Hex Editor

Название этой программы — VBdiff — буквально обозначает «Визуально двоичный diff». Этот бесплатный редактор способен открывать два файла одновременно и может их сравнивать. Умеет работать с большими документами.

15. HexCmp

HexCmp входит в состав программного обеспечения Fairdell. Это удобное приложение для сравнения и редактирования двоичных файлов как в двоичном, так и в 16-ричном форматах.

Выводы

Упомянутые выше HEX редакторы Linux, достаточно часто используются владельцами компьютеров, работающих под этой операционной системой. Некоторые из них более популярны среди специалистов — программистов и разработчиков. Другие приходятся по вкусу тем, кто пользуется подобным ПО лишь от случая к случаю. Тем не менее, можно сказать, что все они достаточно гибкие и функциональные для того, чтобы удовлетворить потребности всех пользователей.

10 ways to analyze binary files on Linux

Tux with binary code background

We work with binaries daily, yet we understand so little about them. By binaries, I mean the executable files that you run daily, right from your command line tools to full-fledged applications.

Linux provides a rich set of tools that makes analyzing binaries a breeze! Whatever might be your job role, if you are working on Linux, knowing the basics about these tools will help you understand your system better.

In this article, we will cover some of the most popular of these Linux tools and commands, most of which will be available natively as part of your Linux distribution. If not, you can always use your package manager to install and explore them. Remember: learning to use the right tool at the right occasion requires plenty of patience and practice.

What it does: Help to determine the file type.

This will be your starting point for binary analysis. We work with files daily. Not everything is an executable type; there is a whole wide range of file types out there. Before you start, you need to understand the type of file that is being analyzed. Is it a binary file, a library file, an ASCII text file, a video file, a picture file, a PDF, a data file, etc.?

The file command will help you identify the exact file type that you are dealing with.

What it does: Print shared object dependencies.

If you have already used the file command above on an executable binary, you can’t miss the «dynamically linked» message in the output. What does it mean?

When software is being developed, we try not to reinvent the wheel. There are a set of common tasks that most software programs require, like printing output or reading from standard in, or opening files, etc. All of these common tasks are abstracted away in a set of common functions that everybody can then use instead of writing their own variants. These common functions are put in a library called libc or glibc.

Читать:
Как изменить msi пакет

How does one find which libraries the executable is dependent on? That’s where ldd command comes into the picture. Running it against a dynamically linked binary shows all its dependent libraries and their paths.

ltrace

What it does: A library call tracer.

We now know how to find the libraries an executable program is dependent on using the ldd command. However, a library can contain hundreds of functions. Out of those hundreds, which are the actual functions being used by our binary?

The ltrace command displays all the functions that are being called at run time from the library. In the below example, you can see the function names being called, along with the arguments being passed to that function. You can also see what was returned by those functions on the far right side of the output.

Hexdump

What it does: Display file contents in ASCII, decimal, hexadecimal, or octal.

Often, it happens that you open a file with an application that doesn’t know what to do with that file. Try opening an executable file or a video file using vim; all you will see is gibberish thrown on the screen.

Opening unknown files in Hexdump helps you see what exactly the file contains. You can also choose to see the ASCII representation of the data present in the file using some command-line options. This might help give you some clues to what kind of file it is.

strings

What it does: Print the strings of printable characters in files.

If Hexdump seems a bit like overkill for your use case and you are simply looking for printable characters within a binary, you can use the strings command.

When software is being developed, a variety of text/ASCII messages are added to it, like printing info messages, debugging info, help messages, errors, and so on. Provided all this information is present in the binary, it will be dumped to screen using strings.

readelf

What it does: Display information about ELF files.

ELF (Executable and Linkable File Format) is the dominant file format for executable or binaries, not just on Linux but a variety of UNIX systems as well. If you have utilized tools like file command, which tells you that the file is in ELF format, the next logical step will be to use the readelf command and its various options to analyze the file further.

Having a reference of the actual ELF specification handy when using readelf can be very useful. You can find the specification here.

objdump

What it does: Display information from an object file.

Binaries are created when you write source code which gets compiled using a tool called, unsurprisingly, a compiler. This compiler generates machine language instructions equivalent to the source code, which can then be executed by the CPU to perform a given task. This machine language code can be interpreted via mnemonics called an assembly language. An assembly language is a set of instructions that help you understand the operations being performed by the program and ultimately being executed on the CPU.

objdump utility reads the binary or executable file and dumps the assembly language instructions on the screen. Knowledge of assembly is critical to understand the output of the objdump command.

Remember: assembly language is architecture-specific.

strace

What it does: Trace system calls and signals.

If you have used ltrace, mentioned earlier, think of strace being similar. The only difference is that, instead of calling a library, the strace utility traces system calls. System calls are how you interface with the kernel to get work done.

To give an example, if you want to print something to the screen, you will use the printf or puts function from the standard library libc; however, under the hood, ultimately, a system call named write will be made to actually print something to the screen.

What it does: List symbols from object files.

If you are working with a binary that is not stripped, the nm command will provide you with the valuable information that was embedded in the binary during compilation. nm can help you identify variables and functions from the binary. You can imagine how useful this would be if you don’t have access to the source code of the binary being analyzed.

To showcase nm, we will quickly write a small program and compile it with the -g option, and we will also see that the binary is not stripped by using the file command.

What it does: The GNU debugger.

Well, not everything in the binary can be statically analyzed. We did execute some commands which ran the binary, like ltrace and strace; however, software consists of a variety of conditions that could lead to various alternate paths being executed.

The only way to analyze these paths is at run time by having the ability to stop or pause the program at any given location and being able to analyze information and then move further down.

That is where debuggers come into the picture, and on Linux, gdb is the defacto debugger. It helps you load a program, set breakpoints at specific places, analyze memory and CPU register, and do much more. It complements the other tools mentioned above and allows you to do much more runtime analysis.

One thing to notice is, once you load a program using gdb, you will be presented with its own (gdb) prompt. All further commands will be run in this gdb command prompt until you exit.

We will use the «hello» program that we compiled earlier and use gdb to see how it works.

Conclusion

Once you are comfortable with using these native Linux binary analysis tools and understanding the output they provide, you can then move onto more advanced and professional open source binary analysis tools like radare2.

How to find files in Linux

How Hexdump works

Hexdump helps you investigate the contents of binary files. Learn how hexdump works.

Binary code on a computer screen

Run a command on binary files with this script

Try this simple script to easily run a command on binary files regardless of their packaging.

How to view files in binary from bash?

I would like to view the contents of a file in the current directory, but in binary from the command line. How can I achieve this?

13 Answers 13

xxd does both binary and hexadecimal.

unless you want to edit it of course. Most linux distros have hexdump by default (but obviously not all).

Type :%!xxd to view the hex strings, the n :%!xxd -r to return to normal editing.

Luboš Turek's user avatar

As a fallback there’s always od -xc filename

sudo apt-get install bless

Bless is GUI tool which can view, edit, seach and a lot more. Its very light weight.

If you want to open binary files (in CentOS 7):

Pang's user avatar

Raju's user avatar

Hexyl formats nicely: sudo apt install hexyl

enter image description here

caduceus's user avatar

You can open emacs (in terminal mode, using emacs -nw for instance), and then use Hexl mode: M-x hexl-mode .

To get the output all in a single line in Hexadecimal:

Mariano Ivaldi's user avatar

to convert a file to its binary codes(hexadecimal representation) we say:

to see all the contents and codes in a binary file , we could use commands like readelf and objdump , hexdump . .

for example if we want to see all the convert all the contents of a binary file(executable, shared libraries, object files) we say:

but readelf is the best utility for analyzing elf(executable and linking format) files. so if we say:

all the contents in the binary file bash would be shown to us, also we could provide different flags for readelf to see all the sections and headers of an elf file separately, for example if we want to see only the elf header we say:

Похожие статьи