Шпаргалка по командам Linux с примерами

4160
Шпаргалка по командам Linux с примерами
Шпаргалка по командам Linux с примерами

Команды Linux могут показаться пугающими на первый взгляд, если вы не привыкли пользоваться терминалом. Существует множество команд для выполнения операций и процессов в системе Linux.

Системный администратор

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

В этом руководстве вы найдете часто используемые команды Linux с синтаксисом и примерами.

Список команд Linux

Информация об аппаратном обеспечении

Show bootup messages:

dmesg

See CPU information:

cat /proc/cpuinfo

Display free and used memory with:

free -h

List hardware configuration information:

lshw

See information about block devices:

lsblk

Show PCI devices in a tree-like diagram:

lspci -tv

Display USB devices in a tree-like diagram:

lsusb -tv

Show hardware information from the BIOS:

dmidecode

Display disk data information:

hdparm -i /dev/disk

Conduct a read-speed test on device/disk:

hdparm -tT /dev/[device]

Test for unreadable blocks on device/disk:

badblocks -s /dev/[device]

Поиск

grep [pattern] [file_name]

Recursively search for a pattern in a directory:

grep -r [pattern] [directory_name]

Find all files and directories related to a particular name:

locate [name]

List names that begin with a specified character [a] in a specified location [/folder/location] by using the find command:

find [/folder/location] -name [a]

See files larger than a specified size [+100M] in a folder:

find [/folder/location] -size [+100M]

Файловые команды

List files in the directory:

ls

List all files (shows hidden files):

ls -a

Show directory you are currently working in:

pwd

Создание новой директории:

mkdir [directory]

Удаление файла:

rm [file_name] 

Remove a directory recursively:

rm -r [directory_name]

Recursively remove a directory without requiring confirmation:

rm -rf [directory_name]

Копирование содержимого одного файла в другой файл:

cp [file_name1] [file_name2]

Recursively copy the contents of one file to a second file:

cp -r [directory_name1] [directory_name2]

Rename [file_name1] to [file_name2] with the command:

mv [file_name1] [file_name2]

Создание символической ссылки на файл:

ln -s /path/to/[file_name] [link_name]

Create a new file:

touch [file_name]

Show the contents of a file:

more [file_name]

или используйте команду cat:

cat [file_name]

Append file contents to another file:

cat [file_name1] >> [file_name2]

Вывести первые 10 строк файла:

head [file_name]

Show the last 10 lines of a file:

tail [file_name]

Encrypt a file:

gpg -c [file_name]

Decrypt a file:

gpg [file_name.gpg]

Show the number of words, lines, and bytes in a file:

wc

Навигация по каталогам

Move up one level in the directory tree structure:

cd ..

Change directory to $HOME:

cd

Change location to a specified directory:

cd /chosen/directory

Сжатие файлов

Archive an existing file:

tar cf [compressed_file.tar] [file_name]

Извлечение заархивированного файла:

tar xf [compressed_file.tar]

Create a gzip compressed tar file by running:

tar czf [compressed_file.tar.gz]

Compress a file with the .gz extension:

gzip [file_name]

Передача файлов

Безопасное копирование файла в каталог сервера:

scp [file_name.txt] [server/tmp]

Синхронизируйте содержимое каталога с резервным каталогом с помощью команды rsync:

rsync -a [/your/directory] [/backup/] 

Пользователи

Подробности об активных пользователях:

id

Показать последние входы в систему:

last

Показать, кто в настоящее время вошел в систему, можно с помощью команды who:

who

Показать, какие пользователи вошли в систему и их активность:

w

Add a new group by typing:

groupadd [group_name]

Add a new user:

adduser [user_name]

Add a user to a group:

usermod -aG [group_name] [user_name]

Временно повысьте привилегии пользователя до суперпользователя или root с помощью команды sudo:

sudo [command_to_be_executed_as_superuser]

Delete a user:

userdel [user_name] 

Modify user information with:

usermod

Установка пакетов

Список всех установленных пакетов с помощью yum:

yum list installed

Find a package by a related keyword:

yum search [keyword]

Show package information and summary:

yum info [package_name]

Install a package using the YUM package manager:

yum install [package_name.rpm]

Install a package using the DNF package manager:

dnf install [package_name.rpm]

Установка пакета с помощью APT package manager:

apt-get install [package_name]

Install an .rpm package from a local file:

rpm -i  [package_name.rpm]

Remove an .rpm package:

rpm -e [package_name.rpm]

Install software from source code:

tar zxvf [source_code.tar.gz]
cd [source_code]
./configure
make
make install

Process Related

See a snapshot of active processes:

ps

Show processes in a tree-like diagram:

pstree

Display a memory usage map of processes:

pmap

See all running processes:

top

Завершение процесса Linux под заданным идентификатором ID:

kill [process_id]

Terminate a process under a specific name:

pkill [proc_name]

Terminate all processes labelled “proc”:

killall [proc_name]

List and resume stopped jobs in the background:

bg

Bring the most recently suspended job to the foreground:

fg

Bring a particular job to the foreground:

fg [job]

List files opened by running processes:

lsof

 

Системная информация

Show system information:

uname -r 

Информация о релизе ядра:

uname -a  

Display how long the system has been running, including load average:

uptime 

See system hostname:

hostname

Show the IP address of the system:

hostname -i 

List system reboot history:

last reboot 

See current time and date:

date

Query and change the system clock with:

timedatectl 

Show current calendar (month and day):

cal

List logged in users:

w

See which user you are using:

whoami

Show information about a particular user:

finger [username]

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

Для проверки дискового пространства в Linux можно использовать команды df и du.

See free and used space on mounted systems:

df -h

Show free inodes on mounted filesystems:

df -i

Display disk partitions, sizes, and types with the command:

fdisk -l

Использование диска для всех файлов и каталогов:

du -ah

Show disk usage of the directory you are currently in:

du -sh

Display target mount point for all filesystem:

findmnt

Mount a device:

mount [device_path] [mount_point]

SSH Login

Connect to host as user:

ssh user@host

Securely connect to host via SSH default port 22:

ssh host

Connect to host using a particular port:

ssh -p [port] user@host

Connect to host via telnet default port 23:

telnet host

Разрешение файлов

Команда Chown в Linux изменяет права на файлы и каталоги.

Назначить всем разрешения на чтение, запись и выполнение:

chmod 777 [file_name]

Назначить разрешение на чтение, запись и выполнение владельцу и разрешение на чтение и выполнение группе и другим:

chmod 755 [file_name]

Назначить полное разрешение владельцу, а разрешение на чтение и запись — группе и другим:

chmod 766 [file_name]

Изменение права собственности на файл:

chown [user] [file_name]

Изменение владельца и групповой принадлежности файла:

chown [user]:[group] [file_name]

Сеть

Список IP-адресов и сетевых интерфейсов:

ip addr show

Assign an IP address to interface eth0:

ip address add [IP_address]

Display IP addresses of all network interfaces with:

ifconfig

Смотрим активные (прослушиваемые) порты с помощью команды netstat:

netstat -pnltu

Show tcp and udp ports and their programs:

netstat -nutlp

Display more information about a domain:

whois [domain]

Вывод информацию DNS с помощью команды dig:

dig [domain] 

Do a reverse lookup on domain:

dig -x host

Do reverse lookup of an IP address:

dig -x [ip_address]

Perform an IP lookup for a domain:

host [domain]

Show the local IP address:

hostname -I

Загрузите файл из домена с помощью команды wget:

wget [file_name]

Быстрые клавиши Linux

Kill process running in the terminal:

Ctrl + C

Stop current process:

Ctrl + Z

The process can be resumed in the foreground with fg or in the background with bg.

Cut one word before the cursor and add it to clipboard:

Ctrl + W

Cut part of the line before the cursor and add it to clipboard:

Ctrl + U

Cut part of the line after the cursor and add it to clipboard:

Ctrl + K

Paste from clipboard:

Ctrl + Y

Recall last command that matches the provided characters:

Ctrl + R

Run the previously recalled command:

Ctrl + O

Exit command history without running a command:

Ctrl + G

Run the last command again:

!!

Log out of current session:

exit

Заключение

Чем чаще вы используете команды Linux, тем быстрее вы их запомните. Не напрягайтесь по поводу запоминания их синтаксиса, воспользуйтесь нашей шпаргалкой.

При возникновении сомнений обратитесь к этому полезному руководству по наиболее распространенным командам Linux.