Создать bin файл linux

How to Create Binary File from Shell Script

While working with the Linux systems, we used many of commands on daily basis. Most of the commands are available in binary format in /bin, /sbin , /usr/bin, /usr/sbin, etc directories. As a system administrator or student we wrote many of shell script to do few task or automate them. This article will help you to create binary file of your shell script, so no one can see the source code of your script and we can use them as a command. To create binary file from a script we use SHC compiler written by Francisco Javier Rosales García.

Follow the below steps to do this.

Step 1 – Prerequsities

First of all, You need to install required packages for SHC compiler.

For Ubuntu, Debian and LinuxMint

sudo apt-get install libc6-dev

For CentOS, RHEL & Fedora

sudo yum install glibc-devel

Step 2 – Download and Install SHC

Download the latest source code of SHC compiler from its official webpage or using below commands and extract on your system.

cd /usr/src wget http://www.datsi.fi.upm.es/~frosal/sources/shc-3.8.9.tgz sudo tar xzf shc-3.8.9.tgz

Now compile the SHC source code on your system and install it using following command.

cd shc-3.8.9 make make install

Step 3 – Create Shell Script

Let’s create a shell script as per your requirement or skip this step if you already created. For this article we have created below sample script which add the integer values given on command line parameter and show the sum of them.

#!/bin/bash total=0 for i in $@; do if [ ! -z "$" ]; then echo "Please enter numeric only" exit 1 fi total=$(($total + $i)) done if [ $total -eq 0 ]; then echo "Plesae execute script like: $0 10 20 30" exit 0 fi echo $total

Step 4 – Create Binary of Script

At this stage we have installed SHC compiler and have a shell script named script.sh. Use the following command to create binary file of your script.

The above command will create two files in current directory. One will be script.sh.x.c which is in C language format of your script. Second one will be script.sh.x which will be in binary format.

Step 5 – Test Binary Script:

If you try to open binary format of script, you will see that it is not in human readable format.

Now move this script under /usr/bin directory to use from anywhere in system. Also remove .sh.x from file name. So it will be available with simple name. Also set the execute permissions to everyone

mv script.sh.x /usr/bin/script chmod +x /usr/bin/script

Now type command ‘script’ from anywhere in system. You will see the same results as your shell script does.

script 10 20 30 60

Источник

Читайте также:  Консультант плюс линукс версия

Как сделать бинарник из bash скрипта

Появилась необходимость, скомпилировать bash скрипт в бинарный исполняемый файл. Смысл и цели этих манипуляций каждый может найти себе сам, вдруг понадобится. Нашелся такой проект http://www.datsi.fi.upm.es/~frosal/ , некоего Francisco Javier Rosales García. Утилита называется shc, транслятор языка bash в C, с последующей компиляцией в двоичный формат. Все манипуляции производим на виртуальной машине с debian 8 jessie на борту. Скачиваем архив, разархивируем, компилируем:

root@debian8:~ # wget http://www.datsi.fi.upm.es/~frosal/sources/shc-3.8.9b.tgz root@debian8:~ # tar -xzf ./shc-3.8.9b.tgz root@debian8:~ # cd shc-3.8.9b root@debian8:~/shc-3.8.9b # make cc -Wall shc.c -o shc *** ▒Do you want to probe shc with a test script? *** Please try. make test

Использование shc

root@debian8:~/shc-3.8.9b # ./shc -help shc Version 3.8.9b, Generic Script Compiler shc Copyright (c) 1994-2015 Francisco Rosales shc Usage: shc [-e date] [-m addr] [-i iopt] [-x cmnd] [-l lopt] [-rvDTCAh] -f script -e %s Expiration date in dd/mm/yyyy format [none] -m %s Message to display upon expiration ["Please contact your provider"] -f %s File name of the script to compile -i %s Inline option for the shell interpreter i.e: -e -x %s eXec command, as a printf format i.e: exec('%s',@ARGV); -l %s Last shell option i.e: -- -r Relax security. Make a redistributable binary -v Verbose compilation -D Switch ON debug exec calls [OFF] -T Allow binary to be traceable [no] -C Display license and exit -A Display abstract and exit -h Display help and exit Environment variables used: Name Default Usage CC cc C compiler command CFLAGS C compiler flags Please consult the shc(1) man page. 
root@debian8:~/shc-3.8.9b # ./script.sh testing testing
root@debian8:~/shc-3.8.9b # ./shc -r -T -f ./script.sh

На выходе получаем 2 новых файла: script.sh.x — двоичный исполняемый файл script.sh.x.c — С код полученный из bash скрипта, при желании его можно подправить руками и скомпилировать штатными средствами системы. Проверяем бинарник:

root@debian8:~/shc-3.8.9b # ./script.sh.x "binary file" binary file

Использовать полученный бинарник можно практически на любой версии linux. Скрипту можно установить срок годности (опция -e), по истечение которого файл будет выдавать сообщение (опция -m).

Источник

Русские Блоги

Обычные установки Linux — это tar, zip, gz, rpm, deb, bin и т. Д. Мы можем просто разделить его на три категории:

Первое: упакуйте или сжимайте файлы tar, zip, gz и т. Д., Обычно после распаковки, или запускайте файл sh после распаковки;

Во-вторых: соответствующие deb, rpm и т. Д. С инструментами управления, обычно такие установочные файлы можно легко установить с помощью сторонних командных строк или пользовательского интерфейса, например apt в Ubuntu для установки deb и yum в Redhat для установки rpm. ;

В-третьих: как и класс .bin, он на самом деле упаковывает sh и zip в bin или упаковывает sh и rpm в bin и т. Д. Когда установочный файл bin запускается в командной строке, он фактически sh в bin для распаковки zip в bin. Или процесс установки rpm;

Два установочных файла bin

Читайте также:  Get fonts for linux

Установочный файл .bin можно рассматривать как упаковку файлов sh и других установочных файлов, таких как zip или rpm. Как показано ниже:

Преимущества установочного файла .bin:

1) Есть только один пакет, файл .bin;

2) Его можно запускать прямо в Linux, потому что это sh (первая половина — sh);

3) sh может содержать информацию о протоколе, которая должна быть получена пользователем, и предлагать пользователю принять ее. Если пользователь не принимает ее, установка завершается;

Выполнение трех установочных файлов .bin

1) Супер просто: sh xxxx.bin или напрямую xxxx.bin.

2) Процесс выглядит следующим образом:

Производство четырех установочных файлов .bin

1) Скомпонованный файл sh (пример: YYYY.bin)

# ! / bin / sh
PATH =/ usr / bin: / bin
umask 022
echo_args = » -e »
localinstall =$ 1
more XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXxx
EOF
agreed =
while [ x $ agreed = x ] ; do
echo
echo » Do you agree to the above license terms? [yes or no] »
read reply leftover
case $ reply in
y* | Y* )
agreed = 1 ;;
n* | N* )
echo » If you don’t agree to the license you can’t install this software » ;
exit 1 ;;
esac
done
if [ -d » $localinstall » ] ; then
outname =$ localinstall / OUTNAME
else
outname = OUTNAME
fi
echo » Unpacking. »
tail -n + AAA $ 0 > $ outname
if [ -x / usr / bin / sum ] ; then
echo » Checksumming. «

sum = ` / usr / bin / sum $ outname`
index = 1
for s in $ sum
do
case $ index in
1 ) sum1 =$ s ;
index = 2 ;
;;
2 ) sum2 =$ s ;
index = 3 ;
;;
esac
done
if [ $ sum1 ! = SUM1 -o $ sum2 ! = SUM2 ] ; then
echo » The download file appears to be corrupted. »
echo » Please do not attempt to install this archive file. »
exit 1
fi
else echo «Can’t find /usr/bin/sum to do checksum. Continuing anyway.»fiecho «Done.»exit 0

# Этот файл YYYY.bin можно использовать повторно, OUTNAME, SUM1, SUM2 — все идентификаторы, что означает, что zip-архив должен быть упакован в корзину, путь к rpm, контрольная сумма и размер файла суммы.

# Пользовательское соглашение: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

# tail -n + AAA $ 0 > $ outname, AAA — это количество строк в файле sh, эта команда извлекает zip или rpm после sh в корзину;

# сумма используется для проверки правильности извлеченного файла zip или rpm;

# Последнее должно exit 0 ,должен.
# Вы также можете установить Yunxin unzip или rpm перед выходом, или вы можете установить zip или rpm самостоятельно.

2) Состоит из zip, gz или rpm (пример: XXXX.rpm)

Это zip или rpm, который вы хотите установить.

3) Сценарий sh для создания установочного файла bin (пример: createbin.sh, используйте указанные выше YYYY.sh и XXXX.rpm)

PATH =. : $ PATH
RPM = XXXX . rpm
LICENSEBIN = YYYY . bin
BASE =$( basename $ RPM . rpm )
sum = `sum $ RPM`
index = 1
for s in $ sum
do
case $ index in
1 ) sum1 =$ s ;
index = 2 ;
;;
2 ) sum2 =$ s ;
index = 3 ;
;;
esac
done
cat $ LICENSEBIN | sed -e s / OUTNAME /$ RPM / -e s / SUM1 /$ sum1 / -e s / SUM2 /$ sum2 / > linux_license_new . bin
dos2unix -k -q linux_license_new . bin
cat linux_license_new . bin $ RPM > $ -rpm . bin
sudo chmod a + x res /$ -rpm . bin

# dos2unix Убедитесь, что оболочка лицензии имеет формат linux;

# И этот файл оболочки нужно запустить в Linux;

Читайте также:  Install util linux windows

Источник

convert text file of bits to binary file

How can I create a binary file instructions.bin of the same data as instructions.txt . In other words the .bin file should be the same 192 bits that are in the .txt file, with 32 bits per line. I am using bash on Ubuntu Linux. I was trying to use xxd -b instructions.txt but the output is way longer than 192 bits.

5 Answers 5

oneliner to convert 32-bit strings of ones and zeros into corresponding binary:

$ perl -ne 'print pack("B32", $_)' < instructions.txt >instructions.bin 
  • perl -ne will iterate through each line of input file provided on STDIN ( instructions.txt )
  • pack(«B32», $_) will take a string list of 32 bits ( $_ which we just read from STDIN), and convert it to binary value (you could alternatively use «b32» if you wanted ascending bit order inside each byte instead of descending bit order; see perldoc -f pack for more details)
  • print would then output that converted value to STDOUT, which we then redirect to our binary file instructions.bin
$ hexdump -Cv instructions.bin 00000000 00 00 00 13 02 d1 20 83 00 73 02 b3 00 73 04 33 |. ..s. s.3| 00000010 00 73 64 b3 00 00 00 13 |.sd. | 00000018 $ xxd -b -c4 instructions.bin 00000000: 00000000 00000000 00000000 00010011 . 00000004: 00000010 11010001 00100000 10000011 .. . 00000008: 00000000 01110011 00000010 10110011 .s.. 0000000c: 00000000 01110011 00000100 00110011 .s.3 00000010: 00000000 01110011 01100100 10110011 .sd. 00000014: 00000000 00000000 00000000 00010011 . 

Adding the -r option (reverse mode) to xxd -b does not actually work as intended, because xxd simply does not support combining these two flags (it ignores -b if both are given). Instead, you have to convert the bits to hex yourself first. For example like this:

( echo 'obase=16;ibase=2'; sed -Ee 's/[01]/;\0/g' instructions.txt ) | bc | xxd -r -p > instructions.bin 
  • The part inside the parentheses creates a bc script. It first sets the input base to binary (2) and the output base to hexadecimal (16). After that, the sed command prints the contents of instructions.txt with a semicolon between each group of 4 bits, which corresponds to 1 hex digit. The result is piped into bc .
  • The semicolon is a command separator in bc , so all the script does is print every input integer back out (after base conversion).
  • The output of bc is a sequence of hex digits, which can be converted to a file with the usual xxd -r -p .
$ hexdump -Cv instructions.bin 00000000 00 00 00 13 02 d1 20 83 00 73 02 b3 00 73 04 33 |. ..s. s.3| 00000010 00 73 64 b3 00 00 00 13 |.sd. | 00000018 $ xxd -b -c4 instructions.bin 00000000: 00000000 00000000 00000000 00010011 . 00000004: 00000010 11010001 00100000 10000011 .. . 00000008: 00000000 01110011 00000010 10110011 .s.. 0000000c: 00000000 01110011 00000100 00110011 .s.3 00000010: 00000000 01110011 01100100 10110011 .sd. 00000014: 00000000 00000000 00000000 00010011 . 

Источник

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