Перейти к содержимому

Busybox linux что это

  • автор:

BusyBox в Linux: что это за проект и зачем он нужен?

Сисадмины, а также пользователи UNIX/Linux-систем привыкли к работе со своей любимой командной оболочкой и к стандартным программным средствам. Но использовать их всегда и везде невозможно. На помощь придёт BusyBox — упрощенный shell с набором компактных системных средств.

Команды Linux поставляются вместе с системой при установке дистро. Некоторые из основных команд, такие как cd, kill и echo, фактически встроены в вашу оболочку. Другие, например ls, mv и cat — часть основного пакета служебных программ. Но в мире открытого кода всегда есть альтернативы, и одна из самых интересных — BusyBox.

* BusyBox — это проект, который обеспечивает простую реализацию почти 400 распространенных команд. Этот набор UNIX-утилит командной строки имеет открытый исходный код (GPL — лицензия на свободное ПО).

Подробнее о BusyBox в Linux

BusyBox реализовывает почти 400 общих команд, в том числе ls, mv, ln, mkdir, more, ps, gzip, bzip2, tar и grep. Он также содержит версию языка программирования awk, редактор потока sed, средство проверки файловой системы fsck, пакеты менеджеров rpm и dpkg. Также у BusyBox есть оболочка (sh), которая обеспечивает лёгкий доступ ко всем этим командам. Проект содержит все основные команды, необходимые интерфейсу портативных операционных систем POSIX, чтобы выполнить общие задачи обслуживания системы.

У BusyBox есть команда init, которую можно запустить как PID 1, чтобы она служила родительским процессом для всех других системных служб. Другими словами, проект можно использовать как альтернативу systemd, OpenRC, sinit, init и другим демонам запуска.

BusyBox очень маленький, менее 1 МБ, поэтому он так популярен в граничных вычислениях, встроенных системах и IoT, где дисковое пространство на вес золота. В мире контейнеров и облачных вычислений он также пользуется спросом, как основа для создания минимальных образов контейнеров Linux.

Минимализм в действии

BusyBox привлекателен из-за его минимализма, который так ценит сообщество. Все его команды собраны в один двоичный файл (busybox), а его руководство занимает всего 81 страницу, но охватывает почти 400 команд.

В качестве примера, вот вывод shadow версии useradd —help:

-b, —base-dir BASE_DIR base directory for home

-c, —comment COMMENT GECOS field of the new account

-d, —home-dir HOME_DIR home directory of the new account

-D, —defaults print or change the default config

-e, —expiredate EXPIRE_DATE expiration date of the new account

-f, —inactive INACTIVE password inactivity

-g, —gid GROUP name or ID of the primary group

-G, —groups GROUPS list of supplementary groups

-h, —help display this help message and exit

-k, —skel SKEL_DIR alternative skeleton dir

-K, —key KEY=VALUE override /etc/login.defs

-l, —no-log-init do not add the user to the lastlog

-m, —create-home create the user’s home directory

-M, —no-create-home do not create the user’s home directory

-N, —no-user-group do not create a group with the user’s name

-o, —non-unique allow users with non-unique UIDs

-p, —password PASSWORD encrypted password of the new account

-r, —system create a system account

-R, —root CHROOT_DIR directory to chroot into

-s, —shell SHELL login shell of the new account

-u, —uid UID user ID of the new account

-U, —user-group create a group with the same name as a user

А вот версия той же команды для BusyBox:

-h DIR Home directory

-g GECOS GECOS field

-s SHELL Login shell

-G GRP Group

-S Create a system user

-D Don’t assign a password

-H Don’t create home directory

-u UID User id

-k SKEL Skeleton directory (/etc/skel)

Это различие — преимущество или ограничение? Зависит от ваших предпочтений. Вы хотите иметь 20 или 10 вариантов команд? Для многих пользователей минимализм BusyBox оптимален. В целом, это хорошая минимальная среда, которую можно использовать в качестве запасного варианта или для установки более надёжных инструментов, таких как Bash, Zsh, GNU Awk и т.д.

Инсталляция BusyBox

В Linux вы можете установить BusyBox с помощью диспетчера пакетов. Например, в

Fedora и подобных:

$ sudo dnf install busybox

На Debian и производных:

$ sudo apt install busybox

В macOS используйте MacPorts или Homebrew. В Windows используйте Chocolatey.

Вы можете установить BusyBox в качестве оболочки с помощью команды chsh —shell. Мы храним BusyBox в /lib64, но его расположение зависит от того, где он установлен в вашем дистрибутиве.

$ which busybox

/lib64/busybox/busybox

$ chsh —shell /lib64/busybox/sh

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

Тестируйте BusyBox

Вам не нужно менять оболочку на BusyBox, чтобы просто затестить её. Вы можете запустить приложение из текущей оболочки:

$ busybox sh

В вашей системе всё ещё будут установлены версии команд, которые не относятся к BusyBox. Поэтому, чтобы испытать новые инструменты, вы должны вводить команды в качестве аргументов для busybox исполняемого файла:

sh

BusyBox vX.YY.Z (2021-08-25 07:31:48 NZST) multi-call binary.

Usage: ls [-1AaCxdLHRFplinshrSXvctu] [-w WIDTH] [FILE].

List directory contents

-1 One column output

-a Include entries that start with .

-A Like -a, but exclude . and ..

-x List by lines

Для “полного” взаимодействия с BusyBox вы можете создавать символические ссылки busybox для каждой команды:

DESCRIPTION

BusyBox combines tiny versions of many common UNIX utilities into a single small executable. It provides minimalist replacements for most of the utilities you usually find in GNU coreutils, util-linux, etc. The utilities in BusyBox generally have fewer options than their full-featured GNU cousins; however, the options that are included provide the expected functionality and behave very much like their GNU counterparts.

BusyBox has been written with size-optimization and limited resources in mind. It is also extremely modular so you can easily include or exclude commands (or features) at compile time. This makes it easy to customize your embedded systems. To create a working system, just add /dev, /etc, and a Linux kernel. BusyBox provides a fairly complete POSIX environment for any small or embedded system.

BusyBox is extremely configurable. This allows you to include only the components you need, thereby reducing binary size. Run ‘make config’ or ‘make menuconfig’ to select the functionality that you wish to enable. Then run ‘make’ to compile BusyBox using your configuration.

After the compile has finished, you should use ‘make install’ to install BusyBox. This will install the ‘bin/busybox’ binary, in the target directory specified by CONFIG_PREFIX. CONFIG_PREFIX can be set when configuring BusyBox, or you can specify an alternative location at install time (i.e., with a command line like ‘make CONFIG_PREFIX=/tmp/foo install’). If you enabled any applet installation scheme (either as symlinks or hardlinks), these will also be installed in the location pointed to by CONFIG_PREFIX.

USAGE

BusyBox is a multi-call binary. A multi-call binary is an executable program that performs the same job as more than one utility program. That means there is just a single BusyBox binary, but that single binary acts like a large number of utilities. This allows BusyBox to be smaller since all the built-in utility programs (we call them applets) can share code for many common operations.

You can also invoke BusyBox by issuing a command as an argument on the command line. For example, entering

will also cause BusyBox to behave as ‘ls’.

Of course, adding ‘/bin/busybox’ into every command would be painful. So most people will invoke BusyBox using links to the BusyBox binary.

For example, entering

will cause BusyBox to behave as ‘ls’ (if the ‘ls’ command has been compiled into BusyBox). Generally speaking, you should never need to make all these links yourself, as the BusyBox build system will do this for you when you run the ‘make install’ command.

If you invoke BusyBox with no arguments, it will provide you with a list of the applets that have been compiled into your BusyBox binary.

COMMON OPTIONS

Most BusyBox applets support the —help argument to provide a terse runtime description of their behavior. If the CONFIG_FEATURE_VERBOSE_USAGE option has been enabled, more detailed usage information will also be available.

COMMANDS

Currently available applets include:

COMMAND DESCRIPTIONS

Listen to ACPI events and spawn specific helpers on event arrival

Accept and ignore compatibility options -g -m -s -S -v

addgroup addgroup [-g GID] [-S] [USER] GROUP

Add a group or add a user to a group

adduser adduser [OPTIONS] USER [GROUP]

Create new user, or add USER to GROUP

adjtimex adjtimex [-q] [-o OFS] [-f FREQ] [-p TCONST] [-t TICK]

Read or set kernel time variables. See adjtimex(2)

ar ar x|p|t|r [-ov] ARCHIVE [FILE].

Extract or list FILEs from an ar archive, or create it

Print system architecture

arp arp [-vn] [-H HWTYPE] [-i IF] -a [HOSTNAME] [-v] [-i IF] -d HOSTNAME [pub] [-v] [-H HWTYPE] [-i IF] -s HOSTNAME HWADDR [temp] [-v] [-H HWTYPE] [-i IF] -s HOSTNAME HWADDR [netmask MASK] pub [-v] [-H HWTYPE] [-i IF] -Ds HOSTNAME IFACE [netmask MASK] pub

Manipulate ARP cache

arping arping [-fqbDUA] [-c CNT] [-w TIMEOUT] [-I IFACE] [-s SRC_IP] DST_IP

Send ARP requests/replies

ash ash [-il] [-|+Cabefmnuvx] [-|+o OPT]. [-c ‘SCRIPT’ [ARG0 ARGS] | FILE [ARGS] | -s [ARGS]]

Unix shell interpreter

awk awk [OPTIONS] [AWK_PROGRAM] [FILE]. base32 base32 [-d] [-w COL] [FILE]

Base32 encode or decode FILE to standard output

Base64 encode or decode FILE to standard output

Strip directory path and .SUFFIX from FILE

Print the config file used by busybox build

Arbitrary precision calculator

$BC_LINE_LENGTH changes output width

beep beep -f FREQ -l LEN -d DELAY -r COUNT -n blkdiscard blkdiscard [-o OFS] [-l LEN] [-s] DEVICE

Discard sectors on DEVICE

Print UUIDs of all filesystems

blockdev blockdev OPTION BLOCKDEV bootchartd bootchartd start [PROG ARGS]|stop|init

Create /var/log/bootchart.tgz with boot chart data

start: start background logging; with PROG, run PROG, then kill logging with USR1 stop: send USR1 to all bootchartd processes init: start background logging; stop when getty/xdm is seen (for init scripts) Under PID 1: as init, then exec $bootchart_init , /init, /sbin/init

brctl brctl COMMAND [BRIDGE [ARGS]]

Manage ethernet bridges Commands:

Decompress FILEs (or stdin)

Decompress to stdout

bzip2 bzip2 [-cfkdt123456789] [FILE].

Compress FILEs (or stdin) with bzip2 algorithm

Display a calendar

Print FILEs to stdout

chat chat EXPECT [SEND [EXPECT [SEND]]. ]

Useful for interacting with a modem connected to stdin/stdout. A script consists of "expect-send" argument pairs. Example:

chat » ATZ OK ATD123456 CONNECT » ogin: pppuser word: ppppass ‘

chattr chattr [-R] [-v VERSION] [-p PROJID] [-+=AacDdijsStTu] FILE.

Change ext2 file attributes

chgrp chgrp [-RhLHPcvf]. GROUP FILE.

Change the group membership of FILEs to GROUP

chmod chmod [-Rcvf] MODE[,MODE]. FILE.

MODE is octal number (bit pattern sstrwxrwxrwx) or [ugoa]<+|-|=>[rwxXst]

chown chown [-RhLHPcvf]. USER[:[GRP]] FILE.

Change the owner and/or group of FILEs to USER and/or GRP

Read user:password from stdin and update /etc/passwd

chpst chpst [-vP012] [-u USER[:GRP]] [-U USER[:GRP]] [-e DIR] [-/ DIR] [-n NICE] [-m BYTES] [-d BYTES] [-o N] [-p N] [-f BYTES] [-c BYTES] PROG ARGS

Change the process state, run PROG

chroot chroot NEWROOT [PROG ARGS]

Run PROG with root directory set to NEWROOT

chrt chrt -m | -p [PRIO] PID | [-rfobi] PRIO PROG ARGS

Change scheduling priority and class for a process

Change the foreground virtual terminal to /dev/ttyN

Calculate CRC32 checksum of FILEs

cmp cmp [-ls] FILE1 [FILE2 [SKIP1 [SKIP2]]]

Compare FILE1 with FILE2 (or stdin)

comm comm [-123] FILE1 FILE2

Compare FILE1 with FILE2

cp cp [-arPLHpfinlsTu] SOURCE DEST or: cp [-arPLHpfinlsu] SOURCE.

Copy SOURCEs to DEST

cpio cpio [-dmvu] [-F FILE] [-R USER[:GRP]] [-H newc] [-tio] [EXTR_FILE].

Extract (-i) or list (-t) files from a cpio archive, or take file list from stdin and create an archive (-o)

Main operation mode:

Calculate CRC32 checksum of FILEs

crond crond [-fbS] [-l N] [-d N] [-L LOGFILE] [-c DIR] crontab crontab [-c DIR] [-u USER] [-ler]|[FILE] cryptpw cryptpw [-P FD] [-m TYPE] [-S SALT] [PASSWORD] [SALT]

Print crypt(3) hashed PASSWORD

Give PROG a controlling tty if possible. Example for /etc/inittab (for busybox init): ::respawn:/bin/cttyhack /bin/sh Giving controlling tty to shell running with PID 1: $ exec cttyhack sh Starting interactive shell from boot shell script:

Print selected fields from FILEs to stdout

Display time (using +FMT), or set time

Recognized TIME formats:

Tiny RPN calculator. Operations: Arithmetic: + — * / % ^

— divide with remainder | — modular exponentiation v — square root p — print top of the stack without popping f — print entire stack k — pop the value and set precision i — pop the value and set input radix o — pop the value and set output radix Examples: dc -e’2 2 + p’ -> 4, dc -e’8 8 * 2 2 + / p’ -> 16

dd dd [if=FILE] [of=FILE] [ibs=N obs=N/bs=N] [count=N] [skip=N] [seek=N] [conv=notrunc|noerror|sync|fsync] [iflag=skip_bytes|count_bytes|fullblock|direct] [oflag=seek_bytes|append|direct]

Copy a file with converting and formatting

N may be suffixed by c (1), w (2), b (512), kB (1000), k (1024), MB, M, GB, G

Deallocate unused virtual terminal /dev/ttyN

Delete group GROUP from the system or user USER from group GROUP

Delete USER from the system

df df [-PkmhTai] [-B SIZE] [-t TYPE] [FILESYSTEM].

Print filesystem usage statistics

dhcprelay dhcprelay CLIENT_IFACE[,CLIENT_IFACE2]. SERVER_IFACE [SERVER_IP]

Relay DHCP requests between clients and server

diff diff [-abBdiNqrTstw] [-L LABEL] [-S FILE] [-U LINES] FILE1 FILE2

Compare files line by line and output the differences between them. This implementation supports unified diffs only.

Strip non-directory suffix from FILENAME

dmesg dmesg [-cr] [-n LEVEL] [-s SIZE]

Print or control the kernel ring buffer

dnsd dnsd [-dvs] [-c CONFFILE] [-t TTL_SEC] [-p PORT] [-i ADDR]

Small static DNS server daemon

Convert FILE in-place from DOS to Unix format. When no file is given, use stdin/stdout.

Summarize disk space used for FILEs (or directories)

Print a binary keyboard translation table to stdout

Display DHCP leases granted by udhcpd

Print ARGs to stdout

Eject DEVICE or default /dev/cdrom

env env [-i0] [-u NAME]. [-] [NAME=VALUE]. [PROG ARGS]

Print current environment or run PROG after setting up environment

envdir envdir DIR PROG ARGS

Set various environment variables as specified by files in the directory DIR, run PROG

envuidgid envuidgid USER PROG ARGS

Set $UID to USER’s uid and $GID to USER’s gid, run PROG

ether-wake ether-wake [-b] [-i IFACE] [-p aa:bb:cc:dd[:ee:ff]/a.b.c.d] MAC

Send a magic packet to wake up sleeping machines. MAC must be a station address (00:11:22:33:44:55) or a hostname with a known ‘ethers’ entry.

Convert tabs to spaces, writing to stdout

Print the value of EXPRESSION

EXPRESSION may be:

Beware that many operators need to be escaped or quoted for shells. Comparisons are arithmetic if both ARGs are numbers, else lexicographical. Pattern matches return the string matched between \( and \) or null; if \( and \) are not used, they return the number of characters matched or 0.

Print prime factors

fakeidentd fakeidentd [-fiw] [-b ADDR] [STRING]

Provide fake ident (auth) service

fallocate fallocate [-o OFS] -l LEN FILE

Preallocate space for FILE

Change file attributes on FAT filesystem

Show and modify frame buffer settings

fbsplash fbsplash -s IMGFILE [-c] [-d DEV] [-i INIFILE] [-f CMD] fdflush fdflush DEVICE

Force floppy disk drive to detect disk change

Format floppy disk

fdisk fdisk [-ul] [-C CYLINDERS] [-H HEADS] [-S SECTORS] [-b SSZ] DISK

Change partition table

Get active console

find find [-HL] [PATH]. [OPTIONS] [ACTIONS]

Search for files and perform actions on them. First failed action stops processing of current file. Defaults: PATH is current directory, action is ‘-print’

findfs findfs LABEL=label or UUID=uuid

Find a filesystem device based on a label or UUID

[Un]lock file descriptor, or lock FILE, run PROG

Wrap input lines in FILEs (or stdin), writing to stdout

Display free and used memory

Free all memory used by the specified ramdisk

fsck fsck [-ANPRTV] [-t FSTYPE] [FS_OPTS] [BLOCKDEV].

Check and repair filesystems

fsck.minix fsck.minix [-larvsmf] BLOCKDEV

Check MINIX filesystem

fsfreeze fsfreeze —[un]freeze MOUNTPOINT

Flush and halt writes to MOUNTPOINT

fstrim fstrim [OPTIONS] MOUNTPOINT fsync fsync [-d] FILE.

Write all buffered blocks in FILEs to disk

ftpd ftpd [-wvS] [-a USER] [-t SEC] [-T SEC] [DIR]

FTP server. Chroots to DIR, if this fails (run by non-root), cds to it. It is an inetd service, inetd.conf line: 21 stream tcp nowait root ftpd ftpd /files/to/serve Can be run from tcpsvd:

ftpget ftpget [OPTIONS] HOST [LOCAL_FILE] REMOTE_FILE

Download a file via FTP

ftpput ftpput [OPTIONS] HOST [REMOTE_FILE] LOCAL_FILE

Upload a file to a FTP server

fuser fuser [-msk46] [-SIGNAL] FILE or PORT/PROTO

Find processes which use FILEs or PORTs

getopt getopt [OPTIONS] [—] OPTSTRING PARAMS

O=`getopt -l bb: — ab:c:: "$@"` || exit 1 eval set — "$O" while true; do case "$1" in -a) echo A; shift;; -b|—bb) echo "B:’$2’"; shift 2;; -c) case "$2" in "") echo C; shift 2;; *) echo "C:’$2’"; shift 2;; esac;; —) shift; break;; *) echo Error; exit 1;; esac done

getty getty [OPTIONS] BAUD_RATE[,BAUD_RATE]. TTY [TERMTYPE]

Open TTY, prompt for login name, then invoke /bin/login

BAUD_RATE of 0 leaves it unchanged

Search for PATTERN in FILEs (or stdin)

Print the groups USER is in

Decompress FILEs (or stdin)

gzip gzip [-cfkdt123456789] [FILE].

Compress FILEs (or stdin)

Halt the system

hd is an alias for hexdump -C

hdparm hdparm [OPTIONS] [DEVICE] head head [OPTIONS] [FILE].

Print first 10 lines of FILEs (or stdin). With more than one FILE, precede each with a filename header.

hexdump hexdump [-bcdoxCv] [-e FMT] [-f FMT_FILE] [-n LEN] [-s OFS] [FILE].

Display FILEs (or stdin) in a user specified format

Edit FILE in hexadecimal

Print out a unique 32-bit identifier for the machine

hostname hostname [-sidf] [HOSTNAME | -F FILE]

Show or set hostname or DNS domain name

httpd httpd [-ifv[v]] [-c CONFFILE] [-p [IP:]PORT] [-u USER[:GRP]] [-r REALM] [-h HOME] or httpd -d/-e/-m STRING

Listen for incoming HTTP requests

Show or set hardware clock (RTC)

i2cdetect i2cdetect -l | -F I2CBUS | [-ya] [-q|-r] I2CBUS [FIRST LAST]

Detect I2C chips

i2cdump i2cdump [-fy] [-r FIRST-LAST] BUS ADDR [MODE]

Examine I2C registers

i2cget i2cget [-fy] BUS CHIP-ADDRESS [DATA-ADDRESS [MODE]]

Read from I2C/SMBus chip registers

i2cset i2cset [-fy] [-m MASK] BUS CHIP-ADDRESS DATA-ADDRESS [VALUE] . [MODE]

Set I2C registers

Read/write I2C data in one transfer

Print information about USER or the current user

Configure a network interface

ifdown ifdown [-nmvf] [-i FILE] -a | IFACE. ifenslave ifenslave [-cdf] MASTER_IFACE SLAVE_IFACE.

Configure network interfaces for parallel routing

Network interface plug detection daemon

ifup ifup [-nmvf] [-i FILE] -a | IFACE. inetd inetd [-fe] [-q N] [-R N] [CONFFILE]

Listen for network connections and launch programs

Init is the first process started during boot. It never exits. It (re)spawns children according to /etc/inittab. Signals:

HUP: reload /etc/inittab TSTP: stop respawning until CONT QUIT: re-exec another init USR1/TERM/USR2/INT: run halt/reboot/poweroff/Ctrl-Alt-Del script

Run PROG on filesystem changes. When a filesystem event matching MASK occurs on FILEn, PROG ACTUAL_EVENTS FILEn [SUBFILE] is run. If PROG is -, events are sent to stdout. Events:

inotifyd waits for PROG to exit. When x event happens for all FILEs, inotifyd exits.

insmod insmod FILE [SYMBOL=VALUE].

Load kernel module

install install [-cdDsp] [-o USER] [-g GRP] [-m MODE] [-t DIR] [SOURCE]. DEST

Copy files and set attributes

Change I/O priority and class

iostat iostat [-c] [-d] [-t] [-z] [-k|-m] [ALL|BLOCKDEV. ] [INTERVAL [COUNT]]

Report CPU and I/O statistics

ip ip [OPTIONS] address|route|link|tunnel|neigh|rule [ARGS]

OPTIONS := -f[amily] inet|inet6|link | -o[neline]

ip addr add|del IFADDR dev IFACE | show|flush [dev IFACE] [to PREFIX] ip route list|flush|add|del|change|append|replace|test ROUTE ip link set IFACE [up|down] [arp on|off] [multicast on|off] [promisc on|off] [mtu NUM] [name NAME] [qlen NUM] [address MAC] [master IFACE | nomaster] ip tunnel add|change|del|show [NAME] [mode ipip|gre|sit] [remote ADDR] [local ADDR] [ttl TTL] ip neigh show|flush [to PREFIX] [dev DEV] [nud STATE] ip rule [list] | add|del SELECTOR ACTION

ipaddr ipaddr add|del IFADDR dev IFACE | show|flush [dev IFACE] [to PREFIX]

ipaddr add|change|replace|delete dev IFACE [CONFFLAG-LIST] IFADDR IFADDR := PREFIX | ADDR peer PREFIX [broadcast ADDR|+|-] [anycast ADDR] [label STRING] [scope SCOPE] PREFIX := ADDR[/MASK] SCOPE := [host|link|global|NUMBER] CONFFLAG-LIST := [CONFFLAG-LIST] CONFFLAG CONFFLAG := [noprefixroute] ipaddr show|flush [dev IFACE] [scope SCOPE] [to PREFIX] [label PATTERN]

ipcalc ipcalc [-bnmphs] ADDRESS[/PREFIX] [NETMASK]

Calculate and display network settings from IP address

Upper-case options MQS remove an object by shmkey value. Lower-case options remove an object by shmid value.

ipcs ipcs [[-smq] -i SHMID] | [[-asmq] [-tcplu]] iplink iplink set IFACE [up|down] [arp on|off] [multicast on|off] [promisc on|off] [mtu NUM] [name NAME] [qlen NUM] [address MAC] [master IFACE | nomaster] iplink add [link IFACE] IFACE [address MAC] type TYPE [ARGS] iplink delete IFACE type TYPE [ARGS] TYPE ARGS := vlan VLANARGS | vrf table NUM VLANARGS := id VLANID [protocol 802.1q|802.1ad] [reorder_hdr on|off] [gvrp on|off] [mvrp on|off] [loose_binding on|off] iplink show [IFACE] ipneigh ipneigh show|flush [to PREFIX] [dev DEV] [nud STATE] iproute iproute list|flush|add|del|change|append|replace|test ROUTE

iproute list|flush SELECTOR SELECTOR := [root PREFIX] [match PREFIX] [proto RTPROTO] PREFIX := default|ADDR[/MASK] iproute get ADDR [from ADDR iif IFACE] [oif IFACE] [tos TOS] iproute add|del|change|append|replace|test ROUTE ROUTE := NODE_SPEC [INFO_SPEC] NODE_SPEC := PREFIX [table TABLE_ID] [proto RTPROTO] [scope SCOPE] [metric METRIC] INFO_SPEC := NH OPTIONS NH := [via [inet|inet6] ADDR] [dev IFACE] [src ADDR] [onlink] OPTIONS := [mtu [lock] NUM] [advmss [lock] NUM]

iprule iprule [list] | add|del SELECTOR ACTION iptunnel iptunnel add|change|del|show [NAME] [mode ipip|gre|sit] [remote ADDR] [local ADDR] [ttl TTL]

iptunnel add|change|del|show [NAME] [mode ipip|gre|sit] [remote ADDR] [local ADDR] [[i|o]seq] [[i|o]key KEY] [[i|o]csum] [ttl TTL] [tos TOS] [[no]pmtudisc] [dev PHYS_DEV]

Report or set VT console keyboard mode

Send a signal (default: TERM) to given PIDs

killall killall [-lq] [-SIG] PROCESS_NAME.

Send a signal (default: TERM) to given processes

Send a signal (default: TERM) to all processes outside current session

Log kernel messages to syslog

View FILE (or stdin) one screenful at a time

Create hard LINK to FILE

ln ln [-sfnbtv] [-S SUF] TARGET. LINK|DIR

Create a link LINK or DIR/TARGET to the specified TARGET(s)

Load a console font from stdin

Load a binary keyboard translation table from stdin

logger logger [-s] [-t TAG] [-p PRIO] [MESSAGE]

Write MESSAGE (or stdin) to syslog

Begin a new session on the system

$LOGIN_TIMEOUT Seconds (default 60, 0 — disable) $LOGIN_PRE_SUID_SCRIPT Execute before user ID change

Print the name of the current user

Show messages in syslogd’s circular buffer

losetup losetup [-rP] [-o OFS] <-f|LOOPDEV>FILE: associate loop devices losetup -c LOOPDEV: reread file size losetup -d LOOPDEV: disassociate losetup -a: show status losetup -f: show next free loop device lpd lpd SPOOLDIR [HELPER [ARGS]]

SPOOLDIR must contain (symlinks to) device nodes or directories with names matching print queue names. In the first case, jobs are sent directly to the device. Otherwise each job is stored in queue directory and HELPER program is called. Name of file to print is passed in $DATAFILE variable. Example:

lpq lpq [-P queue[@host[:port]]] [-U USERNAME] [-d JOBID]. [-fs] lpr lpr -P queue[@host[:port]] -U USERNAME -J TITLE -Vmh [FILE]. ls ls [-1AaCxdLHRFplinshrSXvctu] [-w WIDTH] [FILE].

List directory contents

List ext2 file attributes

List loaded kernel modules

Show all open files

List all PCI devices

Decompress to stdout

Decompress FILEs (or stdin)

lzopcat lzopcat [-vF] [FILE]. makedevs makedevs [-d device_table] rootdir

Create a range of special files as specified in a device table. Device table entries take the form of:

<name> <type> <mode> <uid> <gid> <major> <minor> <start> <inc> <count> Where name is the file name, type can be one of: f Regular file d Directory c Character device b Block device p Fifo (named pipe) uid is the user id for the target file, gid is the group id for the target file. The rest of the entries (major, minor, etc) apply to to device special files. A ‘-‘ may be used for blank entries.

Create multipart MIME-encoded message from FILEs

Other options are silently ignored

man man [-aw] [SECTION] MANPAGE[.SECTION].

Display manual page

$COLUMNS overrides output width

Print or check MD5 checksums

Bare mdev is a kernel hotplug helper. To activate it: echo /sbin/mdev >/proc/sys/kernel/hotplug

It uses /etc/mdev.conf with lines [-][ENV=regex;]. DEVNAME UID:GID PERM [>|=PATH]|[!] [@|$|*PROG] where DEVNAME is device name regex, @major ,minor[-minor2], or environment variable regex. A common use of the latter is to load modules for hotplugged devices:

If /dev/mdev.seq file exists, mdev will wait for its value to match $SEQNUM variable. This prevents plug/unplug races. To activate this feature, create empty /dev/mdev.seq at boot.

If /dev/mdev.log file exists, debug log will be appended to it.

Control write access to your terminal y Allow write access to your terminal n Disallow write access to your terminal

microcom microcom [-d DELAY_MS] [-t TIMEOUT_MS ] [-s SPEED] [-X] TTY

Copy bytes from stdin to TTY and from TTY to stdout

mkdir mkdir [-m MODE] [-p] DIRECTORY.

mkdosfs mkdosfs [-v] [-n LABEL] BLOCKDEV [KBYTES]

Make a FAT32 filesystem

mke2fs mke2fs [-Fn] [-b BLK_SIZE] [-i INODE_RATIO] [-I INODE_SIZE] [-m RESERVED_PERCENT] [-L LABEL] BLOCKDEV [KBYTES] mkfifo mkfifo [-m MODE] NAME

Create named pipe

mkfs.ext2 mkfs.ext2 [-Fn] [-b BLK_SIZE] [-i INODE_RATIO] [-I INODE_SIZE] [-m RESERVED_PERCENT] [-L LABEL] BLOCKDEV [KBYTES] mkfs.minix mkfs.minix [-c | -l FILE] [-nXX] [-iXX] BLOCKDEV [KBYTES]

Make a MINIX filesystem

mkfs.vfat mkfs.vfat [-v] [-n LABEL] BLOCKDEV [KBYTES]

Make a FAT32 filesystem

mknod mknod [-m MODE] NAME TYPE [MAJOR MINOR]

Create a special file (block, character, or pipe)

mkpasswd mkpasswd [-P FD] [-m TYPE] [-S SALT] [PASSWORD] [SALT]

Print crypt(3) hashed PASSWORD

mkswap mkswap [-L LBL] BLOCKDEV [KBYTES]

Prepare BLOCKDEV to be used as swap partition

mktemp mktemp [-dt] [-p DIR] [TEMPLATE]

Create a temporary file with name based on TEMPLATE and print its name. TEMPLATE must end with XXXXXX (e.g. [/dir/]nameXXXXXX). Without TEMPLATE, -t tmp.XXXXXX is assumed.

Base directory is: -p DIR, else $TMPDIR , else /tmp

modinfo modinfo [-adlpn0] [-F keyword] MODULE modprobe modprobe [-rq] MODULE [SYMBOL=VALUE]. more more [FILE].

View FILE (or stdin) one screenful at a time

mount mount [OPTIONS] [-o OPT] DEVICE NODE

Mount a filesystem. Filesystem autodetection requires /proc.

There are filesystem-specific -o flags.

Check if DIR is a mountpoint

mpstat mpstat [-A] [-I SUM|CPU|ALL|SCPU] [-u] [-P num|ALL] [INTERVAL [COUNT]]

mt mt [-f DEVICE] OPCODE VALUE

Control magnetic tape drive operation

bsf bsfm bsr bss datacompression drvbuffer eof eom erase fsf fsfm fsr fss load lock mkpart nop offline ras1 ras2 ras3 reset retension rewind rewoffline seek setblk setdensity setpart tell unload unlock weof wset

mv mv [-finT] SOURCE DEST or: mv [-fin] SOURCE.

Rename SOURCE to DEST, or move SOURCEs to DIRECTORY

nameif nameif [-s] [-c FILE] [IFNAME HWADDR].

Rename network interface while it in the down state. The device with address HWADDR is renamed to IFNAME.

Connect to HOST and provide network block device on BLOCKDEV

nc nc [OPTIONS] HOST PORT — connect nc [OPTIONS] -l -p PORT [HOST] [PORT] — listen netstat netstat [-ral] [-tuwx] [-enWp]

Display networking information

nice nice [-n ADJUST] [PROG ARGS]

Change scheduling priority, run PROG

Write FILEs to standard output with line numbers added

nmeter nmeter [-d MSEC] FORMAT_STRING

Monitor system in real time

Run PROG immune to hangups, with output to a non-tty

Print number of available CPUs

nsenter nsenter [OPTIONS] [PROG ARGS] nslookup nslookup [-type=QUERY_TYPE] [-debug] HOST [DNS_SERVER]

Query DNS about HOST

ntpd ntpd [-dnqNwl] [-I IFACE] [-S PROG] [-k KEYFILE] [-p [keyno:N:]PEER].

od od [-abcdfhilovxs] [-t TYPE] [-A RADIX] [-N SIZE] [-j SKIP] [-S MINSTR] [-w WIDTH] [FILE].

Print FILEs (or stdin) unambiguously, as octal bytes by default

openvt openvt [-c N] [-sw] [PROG ARGS]

Start PROG on a new virtual terminal

Ask kernel to rescan partition table

Change USER’s password (default: current user)

Paste lines from each input file, separated with tab

patch patch [-RNE] [-p N] [-i DIFF] [ORIGFILE [PATCHFILE]] pgrep pgrep [-flanovx] [-s SID|-P PPID|PATTERN]

Display process(es) selected by regex PATTERN

List PIDs of all processes with names that match NAMEs

Send ICMP ECHO_REQUESTs to HOST

Send ICMP ECHO_REQUESTs to HOST

pivot_root pivot_root NEW_ROOT PUT_OLD

Move the current root file system to PUT_OLD and make NEW_ROOT the new root file system

pkill pkill [-l|-SIGNAL] [-xfvno] [-s SID|-P PPID|PATTERN]

Send signal to processes selected by regex PATTERN

Display process memory usage

popmaildir popmaildir [OPTIONS] MAILDIR [CONN_HELPER ARGS]

Fetch content of remote mailbox to local maildir

Fetch from plain POP3 server: popmaildir -k DIR nc pop3.server.com 110 <user_and_pass.txt Fetch from SSLed POP3 server and delete fetched emails: popmaildir DIR — openssl s_client -quiet -connect pop3.server.com:995 <user_and_pass.txt

Halt and shut off power

Analyze power consumption on Intel-based laptops

Print environment VARIABLEs. If no VARIABLE specified, print all.

Format and print ARG(s) according to FORMAT (a-la C printf)

ps ps [-o COL1,COL2=HEADER] [-T]

Show list of processes

pscan pscan [-cb] [-p MIN_PORT] [-P MAX_PORT] [-t TIMEOUT] [-T MIN_RTT] HOST

Scan HOST, print all open ports

Display process tree, optionally start from USER or PID

Print the full filename of the current working directory

Show current directory for PIDs

Tell the kernel to automatically search and start RAID arrays

Set and print time from HOST using RFC 868

Print the device node associated with the filesystem mounted at ‘/’

Preload FILEs to RAM

Display the value of a symlink

Print absolute pathnames of FILEs

Reboot the system

Parse MIME-encoded message on stdin

Other options are silently ignored

Change scheduling priority of a running process

Reset the screen

Resize the screen

resume resume BLOCKDEV [OFFSET]

Restore system state from ‘suspend-to-disk’ data in BLOCKDEV

Reverse lines of FILE

rfkill rfkill COMMAND [INDEX|TYPE]

Enable/disable wireless devices

Remove (unlink) FILEs

Remove DIRECTORY if it is empty

Unload kernel modules

route route [-ne] [-A inet[6]] [ [-net|-host] TARGET [netmask MASK] [gw GATEWAY] [metric N] [mss BYTES] [window BYTES] [reject] [IFACE]]

Show or edit kernel routing tables

Output a cpio archive of the rpm file

rtcwake rtcwake [-a | -l | -u] [-d DEV] [-m MODE] [-s SEC | -t TIME]

Enter a system sleep state until specified wakeup time

run-init run-init [-d CAP,CAP. ] [-n] [-c CONSOLE_DEV] NEW_ROOT NEW_INIT [ARGS]

Free initramfs and switch to another root fs:

chroot to NEW_ROOT, delete all in /, move NEW_ROOT to /, execute NEW_INIT. PID must be 1. NEW_ROOT must be a mountpoint.

run-parts run-parts [-a ARG]. [-u UMASK] [—reverse] [—test] [—exit-on-error] [—list] DIRECTORY

Run a bunch of scripts in DIRECTORY

Start and monitor a service and optionally an appendant log service

Start a runsv process for each subdirectory. If it exits, restart it.

Receive a file using the xmodem protocol

script script [-afq] [-t[FILE]] [-c PROG] [OUTFILE]

Default OUTFILE is ‘typescript’

scriptreplay scriptreplay TIMINGFILE [TYPESCRIPT [DIVISOR]]

Play back typescripts, using timing information

sed sed [-i[SFX]] [-nrE] [-f FILE]. [-e CMD]. [FILE]. or: sed [-i[SFX]] [-nrE] CMD [FILE].

If no -e or -f, the first non-option argument is the sed command string. Remaining arguments are input files (stdin if none).

sendmail sendmail [-tv] [-f SENDER] [-amLOGIN 4<user_pass.txt | -auUSER -apPASS] [-w SECS] [-H ‘PROG ARGS’ | -S HOST] [RECIPIENT_EMAIL].

Read email from stdin and send it

Busybox specific options:

If no -a options are given, authentication is not done. If -amLOGIN is given but no -au/-ap, user/password is read from fd #4. Other options are silently ignored; -oi is implied. Use makemime to create emails with attachments.

seq seq [-w] [-s SEP] [FIRST [INC]] LAST

Print numbers from FIRST to LAST, in steps of INC. FIRST, INC default to 1.

setarch setarch PERSONALITY [-R] PROG ARGS

PERSONALITY may be:

Make writes to /dev/console appear on DEVICE (default: /dev/tty). Does not redirect kernel log output or reads from /dev/console.

setfattr setfattr [-h] -n|-x ATTR [-v VALUE] FILE.

Set extended attributes

setfont setfont [-m MAPFILE] [-C TTY] FILE

Load a console font

Modify kernel’s scancode-to-keycode map, allowing unusual keyboards to generate usable keycodes.

SCANCODE is either xx or e0xx (hexadecimal), KEYCODE is decimal.

Pin kernel output to VT console N. Default:0 (do not pin)

setpriv setpriv [OPTIONS] PROG ARGS

Run PROG with different privilege settings

-d,—dump Show current capabilities —nnp,—no-new-privs Ignore setuid/setgid bits and file capabilities —inh-caps CAP,CAP Set inheritable capabilities —ambient-caps CAP,CAP Set ambient capabilities

Print or set serial port parameters

PARAMETERs: (* = takes ARG, ^ = can be turned off by preceding ^) *port, *irq, *divisor, *uart, *baud_base, *close_delay, *closing_wait, ^fourport, ^auto_irq, ^skip_test, ^sak, ^session_lockout, ^pgrp_lockout, ^callout_nohup, ^split_termios, ^hup_notify, ^low_latency, autoconfig, spd_normal, spd_hi, spd_vhi, spd_shi, spd_warp, spd_cust ARG for uart:

Run PROG in a new session. PROG will have no controlling terminal and will not be affected by keyboard signals (^C etc).

setuidgid setuidgid USER PROG ARGS

Set uid and gid to USER’s uid and gid, drop supplementary group ids, run PROG

sh sh [-il] [-|+Cabefmnuvx] [-|+o OPT]. [-c ‘SCRIPT’ [ARG0 ARGS] | FILE [ARGS] | -s [ARGS]]

Unix shell interpreter

Print or check SHA1 checksums

Print or check SHA256 checksums

Print or check SHA3 checksums

Print or check SHA512 checksums

Show keys pressed

shred shred [-fuz] [-n N] [-s SIZE] FILE.

shuf shuf [-e|-i L-H] [-n NUM] [-o FILE] [-z] [FILE|ARG. ]

Randomly permute lines

slattach slattach [-ehmLF] [-c SCRIPT] [-s BAUD] [-p PROTOCOL] SERIAL_DEVICE

Configure serial line as SLIP network interface

Pause for a time equal to the total of the args given, where each arg can have an optional suffix of (s)econds, (m)inutes, (h)ours, or (d)ays

Collect memory usage data in /proc and write it to stdout

softlimit softlimit [-a BYTES] [-m BYTES] [-d BYTES] [-s BYTES] [-l BYTES] [-f BYTES] [-c BYTES] [-r BYTES] [-o N] [-p N] [-t N] PROG ARGS

Set soft resource limits, then run PROG

sort sort [-nrugMcszbdfiokt] [-o FILE] [-k START[.OFS][OPTS][,END[.OFS][OPTS]] [-t CHAR] [FILE].

Sort lines of text

split split [OPTIONS] [INPUT [PREFIX]] ssl_client ssl_client [-e] -s FD [-r FD] [-n SNI] start-stop-daemon start-stop-daemon [OPTIONS] [-S|-K] . [— ARGS. ]

Search for matching processes, and then -K: stop all matching processes -S: start a process unless a matching process is found

Display file (default) or filesystem status

FMT sequences for files:

FMT sequences for file systems:

Display printable strings in a binary file

stty stty [-a|g] [-F DEVICE] [SETTING].

Without arguments, prints baud rate, line discipline, and deviations from stty sane

su su [-lmp] [-s SH] [-] [USER [FILE ARGS | -c ‘CMD’ [ARG0 ARGS]]]

Run shell under USER (by default, root)

Single user login

Checksum and count the blocks in a file

sv sv [-v] [-w SEC] CMD SERVICE_DIR.

Control services monitored by runsv supervisor. Commands (only first character is enough):

status: query service status up: if service isn’t running, start it. If service stops, restart it once: like ‘up’, but if service stops, don’t restart it down: send TERM and CONT signals. If ./run exits, start ./finish if it exists. After it stops, don’t restart service exit: send TERM and CONT signals to service and log service. If they exit, runsv exits too pause, cont, hup, alarm, interrupt, quit, 1, 2, term, kill: send STOP, CONT, HUP, ALRM, INT, QUIT, USR1, USR2, TERM, KILL signal to service

svc svc [-udopchaitkx] SERVICE_DIR.

Control services monitored by runsv supervisor

svlogd svlogd [-tttv] [-r C] [-R CHARS] [-l MATCHLEN] [-b BUFLEN] DIR.

Read log data from stdin and write to rotated log files in DIRs

DIR/config file modifies behavior: sSIZE — when to rotate logs (default 1000000, 0 disables) nNUM — number of files to retain !PROG — process rotated log with PROG +,-PATTERN — (de)select line for logging E,ePATTERN — (de)select line for stderr

Check whether runsv supervisor is running. Exit code is 0 if it does, 100 if it does not, 111 (with error message) if SERVICE_DIR does not exist.

Stop swapping on DEVICE

Start swapping on DEVICE

switch_root switch_root [-c CONSOLE_DEV] NEW_ROOT NEW_INIT [ARGS]

Free initramfs and switch to another root fs:

chroot to NEW_ROOT, delete all in /, move NEW_ROOT to /, execute NEW_INIT. PID must be 1. NEW_ROOT must be a mountpoint.

Write all buffered blocks (in FILEs) to disk -d Avoid syncing metadata -f Sync filesystems underlying FILEs

Show/set kernel parameters

System logging utility

Concatenate FILEs and print them in reverse

Print last 10 lines of FILEs (or stdin) to. With more than one FILE, precede each with a filename header.

tar tar c|x|t [-ZzJjahvokO] [-f TARFILE] [-C DIR] [-T FILE] [-X FILE] [LONGOPT]. [FILE].

Create, extract, or list files from a tar file

taskset taskset [-ap] [HEXMASK | -c LIST]

Set or get CPU affinity

tc tc OBJECT CMD [dev STRING]

OBJECT: qdisc|class|filter CMD: add|del|change|replace|show

qdisc [handle QHANDLE] [root|ingress|parent CLASSID] [[QDISC_KIND] [help|OPTIONS]] QDISC_KIND := [p|b]fifo|tbf|prio|cbq|red|etc. qdisc show [dev STRING] [ingress] class [classid CLASSID] [root|parent CLASSID] [[QDISC_KIND] [help|OPTIONS] ] class show [ dev STRING ] [root|parent CLASSID] filter [pref PRIO] [protocol PROTO] [root|classid CLASSID] [handle FILTERID] [[FILTER_TYPE] [help|OPTIONS]] filter show [dev STRING] [root|parent CLASSID]

tcpsvd tcpsvd [-hEv] [-c N] [-C N[:MSG]] [-b N] [-u USER] [-l NAME] IP PORT PROG

Create TCP socket, bind to IP:PORT and listen for incoming connections. Run PROG for each connection.

Environment if no -E: PROTO=’TCP’ TCPREMOTEADDR=’ip:port’ (‘[ip]:port’ for IPv6) TCPLOCALADDR=’ip:port’ TCPORIGDSTADDR=’ip:port’ of destination before firewall Useful for REDIRECTed-to-local connections: iptables -t nat -A PREROUTING -p tcp —dport 80 -j REDIRECT —to 8080 TCPCONCURRENCY=num_of_connects_from_this_ip If -h: TCPLOCALHOST=’hostname’ (-l NAME is used if specified) TCPREMOTEHOST=’hostname’

Copy stdin to each FILE, and also to stdout

telnet telnet [-a] [-l USER] HOST [PORT]

Connect to telnet server

Handle incoming telnet connections

tftp tftp [OPTIONS] HOST [PORT]

Transfer a file from/to tftp server

Transfer a file on tftp client’s request

tftpd is an inetd service, inetd.conf line: 69 dgram udp nowait root tftpd tftpd -l /files/to/serve Can be run from udpsvd:

time time [-vpa] [-o FILE] PROG ARGS

Run PROG, display resource usage when it exits

timeout timeout [-s SIG] SECS PROG ARGS

Run PROG. Send SIG to it if it is not gone in SECS seconds. Default SIG: TERM.

top top [-bmH] [-n COUNT] [-d SECONDS]

Show a view of process activity in real time. Read the status of all processes from /proc each SECONDS and show a screenful of them. Keys:

touch touch [-cham] [-d DATE] [-t DATE] [-r FILE] FILE.

Update mtime of FILEs

tr tr [-cds] STRING1 [STRING2]

Translate, squeeze, or delete characters from stdin, writing to stdout

traceroute traceroute [-46Flnrv] [-f 1ST_TTL] [-m MAXTTL] [-q PROBES] [-p PORT] [-t TOS] [-w WAIT_SEC] [-s SRC_IP] [-i IFACE] [-z PAUSE_MSEC] HOST [BYTES]

Trace the route to HOST

traceroute6 traceroute6 [-nrv] [-f 1ST_TTL] [-m MAXTTL] [-q PROBES] [-p PORT] [-t TOS] [-w WAIT_SEC] [-s SRC_IP] [-i IFACE] [-z PAUSE_MSEC] HOST [BYTES]

Trace the route to HOST

Truncate FILEs to SIZE

Pipe stdin to stdout, add timestamp to each line

Print file name of stdin’s terminal

Print dimensions of stdin tty, or 80×24

tunctl tunctl [-f DEVICE] [-t NAME | -d NAME] [-u USER] [-g GRP] [-b]

Create or delete TUN/TAP interfaces

tune2fs tune2fs [-c MAX_MOUNT_COUNT] [-i DAYS] [-C MOUNT_COUNT] [-L LABEL] BLOCKDEV

Adjust filesystem options on ext[23] filesystems

ubiattach ubiattach -m MTD_NUM [-d UBI_NUM] [-O VID_HDR_OFF] UBI_CTRL_DEV

Attach MTD device to UBI

ubidetach ubidetach -d UBI_NUM UBI_CTRL_DEV

Detach MTD device from UBI

ubimkvol ubimkvol -N NAME [-s SIZE | -m] UBI_DEVICE

Create UBI volume

ubirename ubirename UBI_DEVICE OLD_VOLNAME NEW_VOLNAME [OLD2 NEW2].

Rename UBI volumes on UBI_DEVICE

ubirmvol ubirmvol -n VOLID | -N VOLNAME UBI_DEVICE

Remove UBI volume

ubirsvol ubirsvol -n VOLID -s SIZE UBI_DEVICE

Resize UBI volume

ubiupdatevol ubiupdatevol -t UBI_DEVICE | [-s SIZE] UBI_DEVICE IMG_FILE

Update UBI volume

udhcpc udhcpc [-fbqvRB] [-a[MSEC]] [-t N] [-T SEC] [-A SEC|-n] [-i IFACE] [-P PORT] [-s PROG] [-p PIDFILE] [-oC] [-r IP] [-V VENDOR] [-F NAME] [-x OPT:VAL]. [-O OPT]. udhcpc6 udhcpc6 [-fbqvR] [-t N] [-T SEC] [-A SEC|-n] [-i IFACE] [-s PROG] [-p PIDFILE] [-P PORT] [-ldo] [-r IPv6] [-x OPT:VAL]. [-O OPT]. udhcpd udhcpd [-fS] [-I ADDR] [-P PORT] [CONFFILE]

udpsvd udpsvd [-hEv] [-c N] [-u USER] [-l NAME] IP PORT PROG

Create UDP socket, bind to IP:PORT and wait for incoming packets. Run PROG for each packet, redirecting all further packets with same peer ip:port to it.

Environment if no -E: PROTO=’UDP’ UDPREMOTEADDR=’ip:port’ (‘[ip]:port’ for IPv6) UDPLOCALADDR=’ip:port’ If -h: UDPLOCALHOST=’hostname’ (-l NAME is used if specified) UDPREMOTEHOST=’hostname’

uevent runs PROG for every netlink notification. PROG’s environment contains data passed from the kernel. Typical usage (daemon for dynamic device node creation): # uevent mdev & mdev -s

umount umount [-rlfda] [-t FSTYPE] FILESYSTEM|DIRECTORY

Print system information

Decompress FILEs (or stdin)

Convert spaces to tabs, writing to stdout

uniq uniq [-cduiz] [-f,s,w N] [FILE [OUTFILE]]

Discard duplicate lines

Convert FILE in-place from Unix to DOS format. When no file is given, use stdin/stdout.

Delete FILE by calling unlink()

Decompress FILEs (or stdin)

unlzop unlzop [-cfUvF] [FILE]. unshare unshare [OPTIONS] [PROG ARGS] unxz unxz [-cfk] [FILE].

Decompress FILEs (or stdin)

unzip unzip [-lnojpq] FILE[.zip] [FILE]. [-x FILE]. [-d DIR]

Extract FILEs from ZIP archive

Display the time since the last boot

Pause for N microseconds

uudecode uudecode [-o OUTFILE] [INFILE]

Uudecode a file Finds OUTFILE in uuencoded source unless -o is given

uuencode uuencode [-m] [FILE] STORED_FILENAME

Uuencode FILE (or stdin) to stdout

vconfig vconfig COMMAND [OPTIONS]

Create and remove virtual ethernet devices

Lock a virtual terminal. A password is required to unlock.

Show CD volume name of the DEVICE (default /dev/cdrom)

watch watch [-n SEC] [-t] PROG ARGS

Run PROG periodically

Periodically write to watchdog device DEV

Use 500ms to specify period in milliseconds

Count lines, words, and bytes for FILEs (or stdin)

wget wget [-cqS] [—spider] [-O FILE] [-o LOGFILE] [—header ‘HEADER: VALUE’] [-Y on/off] [-P DIR] [-U AGENT] [-T SEC] URL.

Retrieve files via HTTP or FTP

Print the user name associated with the current effective user id

whois whois [-i] [-h SERVER] [-p PORT] NAME.

Query WHOIS info about NAME

xargs xargs [OPTIONS] [PROG ARGS]

Run PROG on every item given by stdin

xxd xxd [-pri] [-g N] [-c N] [-n LEN] [-s OFS] [-o OFS] [FILE]

Hex dump FILE (or stdin)

Decompress FILEs (or stdin)

Decompress to stdout

Repeatedly print a line with STRING, or ‘y’

Decompress to stdout

zcip zcip [OPTIONS] IFACE SCRIPT

Manage a ZeroConf IPv4 link-local address

$LOGGING =none Suppress logging $LOGGING =syslog Log to syslog

With no -q, runs continuously monitoring for ARP conflicts, exits only on I/O errors (link down etc)

LIBC NSS

GNU Libc (glibc) uses the Name Service Switch (NSS) to configure the behavior of the C library for the local environment, and to configure how it reads system data, such as passwords and group information. This is implemented using an /etc/nsswitch.conf configuration file, and using one or more of the /lib/libnss_* libraries. BusyBox tries to avoid using any libc calls that make use of NSS. Some applets however, such as login and su, will use libc functions that require NSS.

If you enable CONFIG_USE_BB_PWD_GRP, BusyBox will use internal functions to directly access the /etc/passwd, /etc/group, and /etc/shadow files without using NSS. This may allow you to run your system without the need for installing any of the NSS configuration files and libraries.

When used with glibc, the BusyBox ‘networking’ applets will similarly require that you install at least some of the glibc NSS stuff (in particular, /etc/nsswitch.conf, /lib/libnss_dns*, /lib/libnss_files*, and /lib/libresolv*).

Shameless Plug: As an alternative, one could use a C library such as uClibc. In addition to making your system significantly smaller, uClibc does not require the use of any NSS support files or libraries.

MAINTAINER

Denis Vlasenko <vda.linux@googlemail.com>

AUTHORS

The following people have contributed code to BusyBox whether they know it or not. If you have written code included in BusyBox, you should probably be listed here so you can obtain your bit of eternal glory. If you should be listed here, or the description of what you have done needs more detail, or is incorrect, please send in an update.

Emanuele Aina <emanuele.aina@tiscali.it>

Erik Andersen <andersen@codepoet.org>

Laurence Anderson <l.d.anderson@warwick.ac.uk>

Jeff Angielski <jeff@theptrgroup.com>

Edward Betts <edward@debian.org>

John Beppu <beppu@codepoet.org>

Brian Candler <B.Candler@pobox.com>

Randolph Chung <tausq@debian.org>

Dave Cinege <dcinege@psychosis.com>

Jordan Crouse <jordan@cosmicpenguin.net>

Magnus Damm <damm@opensource.se>

Larry Doolittle <ldoolitt@recycle.lbl.gov>

Glenn Engel <glenne@engel.org>

Gennady Feldman <gfeldman@gena01.com>

Karl M. Hegbloom <karlheg@debian.org>

Daniel Jacobowitz <dan@debian.org>

Matt Kraai <kraai@alumni.cmu.edu>

Stephan Linz <linz@li-pro.net>

John Lombardo <john@deltanet.com>

Glenn McGrath <bug1@iinet.net.au>

Manuel Novoa III <mjn3@codepoet.org>

Vladimir Oleynik <dzo@simtreas.ru>

Bruce Perens <bruce@pixar.com>

Tim Riker <Tim@Rikers.org>

Kent Robotti <robotti@metconnect.com>

Chip Rosenthal <chip@unicom.com>, <crosenth@covad.com>

Pavel Roskin <proski@gnu.org>

Gyepi Sam <gyepi@praxis-sw.com>

Linus Torvalds <torvalds@transmeta.com>

Mark Whitley <markw@codepoet.org>

Charles P. Wright <cpwright@villagenet.com>

Enrique Zanardi <ezanardi@ull.es>

Tito Ragusa <farmatito@tiscali.it>

Paul Fox <pgf@foxharp.boston.ma.us>

Roberto A. Foglietta <me@roberto.foglietta.name>

Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>

Mike Frysinger <vapier@gentoo.org>

Jie Zhang <jie.zhang@analog.com>

2021-11-09 version 1.34.1

Package name: community/busybox Version: 1.34.1-1 Upstream: https://www.busybox.net Licenses: GPL Manuals: /listing/community/busybox/ Table of contents

Powered by archmanweb, using mandoc for the conversion of manual pages.

The website is available under the terms of the GPL-3.0 license, except for the contents of the manual pages, which have their own license specified in the corresponding Arch Linux package.

How to use BusyBox on Linux

bash logo on green background

It’s easy to take Linux commands for granted. They come bundled with the system when you install Linux, and we often don’t question why they’re there. Some of the basic commands, such as cd , kill , and echo aren’t always independent applications but are actually built into your shell. Others, such as ls , mv , and cat are part of a core utility package (often GNU coreutils specifically). But there are always alternatives in the world of open source, and one of the most interesting is BusyBox.

What is BusyBox in Linux?

More Linux resources

BusyBox is an open source (GPL) project providing simple implementations of nearly 400 common commands, including ls , mv , ln , mkdir , more , ps , gzip , bzip2 , tar , and grep . It also contains a version of the programming language awk , the stream editor sed , the filesystem checker fsck , the rpm and dpkg package managers, and of course, a shell ( sh ) that provides easy access to all of these commands. In short, it contains all the essential commands required for a POSIX system to perform common system maintenance tasks as well as many user and administrative tasks.

In fact, it even contains an init command which can be launched as PID 1 to serve as the parent process for all other system services. In other words, BusyBox can be used as an alternative to systemd, OpenRC, sinit, init, and other launch daemons.

BusyBox is very small. As an executable, it’s under 1 MB, so it has gained much of its popularity in the embedded, Edge, and IoT space, where drive space is at a premium. In the world of containers and cloud computing, it’s also popular as a foundation for minimal Linux container images.

Minimalism

Part of the appeal of BusyBox is its minimalism. All of its commands are compiled into a single binary ( busybox ), and its man page is a mere 81 pages (by my calculation of piping man to pr ) but covers nearly 400 commands.

As an example comparison, here’s the output of the shadow version of useradd —help :

And here’s the BusyBox version of the same command:

Whether or not this difference is a feature or a limitation depends on whether you prefer to have 20 options or ten options in your commands. For some users and use-cases, BusyBox’s minimalism provides just enough for what needs to be done. For others, it’s a good minimal environment to have as a fallback or as a foundation for installing more robust tools like Bash, Zsh, GNU Awk, and so on.

Installing BusyBox

On Linux, you can install BusyBox using your package manager. For example, on Fedora and similar:

On Debian and derivatives:

On macOS, use MacPorts or Homebrew. On Windows, use Chocolatey.

You can set BusyBox as your shell using the chsh —shell command, followed by the path to the BusyBox sh application. I keep BusyBox in /lib64 , but its location depends on where your distribution installed it.

Replacing all common commands wholesale with BusyBox is a little more complex, because most distributions are «hard-wired» to look to specific packages for specific commands. In other words, while it’s technically possible to replace init with BusyBox’s init , your package manager may refuse to allow you to remove the package containing init for fear of you causing your system to become non-bootable. There are some distributions built upon BusyBox, so starting fresh is probably the easiest way to experience a system built around BusyBox.

Try BusyBox

You don’t have to change your shell to BusyBox permanently just to try it. You can launch a BusyBox shell from your current shell:

Your system still has the non-BusyBox versions of commands installed, though, so to experience BusyBox’s tools, you must issue commands as arguments to the busybox executable:

For the «full» BusyBox experience, you can create symlinks to busybox for each command. This is easier than it sounds, as long as you use a for-loop:

Add your directory of symlinks at the start of your path, and launch BusyBox:

Get busy

BusyBox is a fun project and an example of just how minimal computing can be. Whether you use BusyBox as a lightweight environment for an ancient computer you’ve rescued, as the userland for an embedded device, to trial a new init system, or just as a curiosity, it can be fun reacquainting yourself with old familiar, yet somehow new, commands.

Command line prompt

20 essential Linux commands for every user

From new user to power user, here are 20 Linux commands that will make your life easier.

Busybox linux что это

You are currently viewing Как использовать BusyBox

Команды Linux всегда воспринимаются как должное. Они поставляются вместе с системой при установке Linux, и мы часто не задаемся вопросом, зачем они нужны. Некоторые из основных команд, такие как cd, kill и echo, не всегда являются независимыми приложениями, но фактически встроены в вашу оболочку. Другие, такие как ls, mv и cat, являются частью основного пакета служебных программ (часто специально для GNU coreutils). Но в мире открытого кода всегда есть альтернативы, и одна из самых интересных — BusyBox.

Что такое BusyBox?

BusyBox — это проект с открытым исходным кодом (GPL), обеспечивающий простую реализацию почти 400 распространенных команд, включая ls, mv, ln, mkdir, more, ps, gzip, bzip2, tar и grep. Он также содержит версию языка программирования awk, редактор потока sed, средство проверки файловой системы fsck, менеджеры пакетов rpm и dpkg и, конечно же, оболочку (sh), которая обеспечивает легкий доступ ко всем этим командам. Короче говоря, он содержит все основные команды, необходимые системе POSIX для выполнения общих задач обслуживания системы, а также многих пользовательских и административных задач.

Фактически, он даже содержит команду init, которую можно запустить как PID 1, чтобы она служила родительским процессом для всех других системных служб. Другими словами, BusyBox можно использовать как альтернативу systemd, OpenRC, sinit, init и другим процессами запуска.

BusyBox очень маленький. Как исполняемый файл, он составляет менее 1 МБ, поэтому он приобрел большую популярность во встроенных устройствах, устройствах Edge и IoT, где дисковое пространство имеет первостепенное значение. В мире контейнеров и облачных вычислений он также популярен как основа для создания минимальных образов контейнеров Linux.

Минимализм

Отчасти привлекательность BusyBox заключается в его минимализме. Все его команды скомпилированы в единый двоичный файл (busybox), а его справочная система занимает всего 81 страницу, но он содержит почти 400 команд.

В качестве примера сравнения, вот результат shadow версии useradd —help :

А вот версия той же команды для BusyBox:

Является ли это различие функцией или ограничением, зависит от того, предпочитаете ли вы иметь в своих командах 20 или десять вариантов. Для многих пользователей и вариантов использования минимализм BusyBox предоставляет ровно столько, сколько необходимо для работы. Для других это хорошая минимальная среда, которую можно использовать в качестве запасного варианта или в качестве основы для установки более надежных инструментов, таких как Bash, Zsh, GNU Awk и т. Д.

Установка BusyBox

В Linux вы можете установить BusyBox с помощью диспетчера пакетов. Например, в Fedora и подобных:

В Debian и подобных:

Вы можете установить BusyBox в качестве оболочки с помощью команды chsh —shell, за которой следует путь к приложению BusyBox sh. Я храню BusyBox в / lib64, но его расположение будет зависеть от того, где он установлен в вашем дистрибутиве.

Замена всех распространенных команд оптом на BusyBox немного сложнее, потому что большинство дистрибутивов «жестко запрограммированы», чтобы искать конкретные пакеты для определенных команд. Другими словами, технически возможно заменить init на init от BusyBox, ваш менеджер пакетов может отказать вам в удалении пакета, содержащего init, из опасения, что ваша система станет неработоспособной. Есть некоторые дистрибутивы, построенные на BusyBox, поэтому начать с нуля, является самым простым способом испытать систему, построенную на BusyBox.

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

Для постоянной работы не нужно менять оболочку на BusyBox, чтобы просто протестировать ее. Вы можете запустить оболочку BusyBox из текущей оболочки:

В вашей системе будут установлены версии команд, не относящиеся к BusyBox, поэтому, чтобы испытать инструменты BusyBox, вы должны вводить команды в качестве аргументов для исполняемого файла busybox:

Список содержимого каталога

Для «полного» взаимодействия с BusyBox вы можете создавать символические ссылки на busybox для каждой команды. Это проще, чем кажется, если вы используете цикл for:

Добавьте свой каталог символических ссылок при старте в path и запустите BusyBox:

Быть «busy»

BusyBox — забавный проект и пример того, насколько минимальными могут быть вычисления. Независимо от того, используете ли вы BusyBox в качестве облегченной среды для спасенного вами древнего компьютера, в качестве пользовательского пространства для встроенного устройства, для испытания новой системы инициализации или просто в качестве любопытства, может быть заново познакомиться со старыми знакомыми, но c другой стороны новыми, командами.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *