Основы командной строки Linux

Основы командной строки Linux
Photo by Gabriel Heinzer / Unsplash

Шпаргалка по Bash

sudo -i #run bash from superuser
	 -s #run bash from superuser
su #run bash from superuser
su -l #run bash from superuser, going to the root user's home directory
Ctrl + c #kill command
Ctrl + z #stop(suspend) command
command & #run command in dackground
nohup command & #save running processes after terminal shutdown
jobs #list jobs running in background current console
fg [number] #foreground job [number]
bg [number] #background job [numder]
Shift + PgUp #scroll up
Shift + PgDn #scroll down
history #history of command
Ctrl + r #search command history
Ctrl + a #move cursor to beginning
Ctrl + e #move cursor to end
Ctrl + k #cut (when cursor in beginning)
Ctrl + y #udo cat
Ctrl + l #clear terminal
uname -a #print description your OS

Раз уж мы запустили машину, хорошо было бы уметь её выключить или перезагрузить

systemctl poweroff #poweroff
systemctl shutdown #shutdown
systemctl reboot #reboot
poweroff #poweroff
reboot #reboot
shutdown -h now #poweroff
systemctl suspend #режим приостановки
systemctl hibernate #спящий режим

Перенаправление вывода/ввода

> #directs command output to file. creates file and overwrites if is exist
2> #directs output error to file
>> #appends command output to file
< #directs content of file to command
ls dir1 > result.txt 2> error.txt #directs output to result.txt, if errors occur direct to error.txt
| #pipeline, direct output to other command 
grep #sort result
	-i #Отключение чувствительности к регистру
tee #directs command output to file, and print on console
xargs #line by line direct output to other command
find . -name "*.txt" | xargs rb -f #построчно передать на удаление найденные файлы

Работа с файлами и директориями

pwd #print working directory
ls /tmp/ #list dir tmp
   -l (ll) #long list
   -h #human output
   -a #list hidden files
   -r #list in revers name
   -t #list new file first
   -rt #older first
ls * #show subdir
cd #change dir [~ .. - /] [.] -current dir
mkdir #make dir
      -p /tmp/dir1/dir2 #create pareante dirs
touch #create file
cat #concatenate and display file
less #show file content
	/ # find in less
	q # quit
head -[n] #display first n line of file
tail -[n] #display last n line of file
	tail -f #follow the end of a changing file
cp [file(s)] [destination] #copy file
   -r #copy recursively
   -i #copy interactively
   /root/file . #copy file to current dir
mv [sourse] [destination] #move or rename file
   -i #mv interactively
   /root/file . #mv file to current dir
rm /tmp/testfle #remove file
rmdir /tmp/testdir #remove empty dir
      -r #remove dir and its content
      -i #interactively
      -rf #force remove (принудительно)

Менеджер пакетов apt

apt search #search package
    show #show info about package
    install #install
    remove #remove
    purge #remove package and config
      -y #auto answer yes
    update #resynchronize sources
    upgrade #upgrade all installed packages to newest version
    apt depends firefox #depends of firefox
    apt rdepends firefox #revers depends
cat /etc/apt/sources.list #list of connected repository
dpkg -l #find version of installed application
     -i package.deb #install package
     -r package.deb #remove package

Работа с Архивами

tar c #create archive
    r #append to archive
    t #list contents of archive
    x #extract archive
    v #verbose mod (+info)
    f file #name of file
tar cvf archive.tar file1 file2 dir1 dir2 #create tar from file1 file2 dir1 dir2
tar tvf archive.tar #list contents of archive
tar rvf archive.tar file3 #add file to archive
tar rvf archive.tar dir3 #add dir to archive
tar xvf archive.tar file3 #extract only file3 from archive
tar xvf archive.tar -C ~/Desktop/ #extract archive to folder "Desktop"
	tar zcvf compressed.tar.gz file1 file2 #Compress to .gz
	tar jcvf compressed.tar.bz2 file1 file2 #Compress to .bz2
	tar ztvf compressed.tar.gz #List
	tar jtvf compressed.tar.bz2 #List

Регулярные выражения

* #matches zero or all characters
? #matches exactly one character
!a #not 'a'
[] #matches any of the characters enclosed in the brackers
[1-9] #matches any numbers in range 1-9
	ls [1-9].txt #print all files 1.txt; 2.txt; ... ;9.txt
	ls [!a-m] #not a-m
\ #escape character

Описание команд и файлов

file somefile #info of file
whatis ls #description command
apropos gzip #description for keywords "gzip"
stat file #description file
gzip --help #short manual
man -k gzip #search for keyword "gzip"
man gzip #manual for gzip
	G #go to start of man
	Shift + G #go to end of man
	/ #search for keywords in man
		N #next finding keyword
		Shifr + N #previous finding keywor
	Q #exit from man

Информация о пользователе

whoami #display your userneme
w #show who's logged on and what they're doing
cat /etc/passwd #see list of users
cat /etc/shadow #see encrypted passwords
id #display group of your username
cat /etc/group #see a list of groups

Права доступа

chmod ugoa +-= rwx filename #sintaxis of chmod
	u #user
	g #group
	o #other
	a #all
	+ #add permission
	- #remove permission
	= #make this the only permission
	r #read
	w #write
	x #execute
	0 #никаких прав
	1 #только выполнение
	2 #только запись
	3 #выполнение и запись
	4 #только чтение
	5 #чтение и выполнение
	6 #чтение и запись
	7 #чтение запись и выполнение
	744 #разрешить все для владельца, а остальным только чтение
	755 #все для владельца, остальным только чтение и выполнение
	764 #все для владельца, чтение и запись для группы, и только чтение для остальных
	777 #всем разрешено все.
sudo -l #list programs you can run as root

Работа с процессами

ps #list processes of current session
   -f #full format
   -e #all processes
   -x #process out of terminal
   -u [username] #ps of user "username"
   -p [PID] #display info on PID
pstree #tree of processes
sudo systemctl kill mariadb #завершение процесса
sudo systemctl kill -9 mariadb #принудительное завершение процесса
kill -9 [pid] #(устаревшее)принудительное завершение процесса по pid
killall httpd #завершение всех процессов с именем "httpd"
xkill #мышкой кликнуть на окно программы, которую хочешь завершить
pkill -u [username] #запрос на прерывание всех процессов пользователя "username"
pidof /usr/sbin/sshd #определение PID процесса sshd
pgrep sshd -l #определение PID процесса sshd

Поиск файлов и команд

find . -name "In*" #find in current dir for name start In...
find . -size +5M #find in current dir file more 5 Mb
find . -type f #find all file type file
	     d #find all file type directory
find . -type f | wc -l #count the number of rows(files)

find /home/user/Downloads -name "*.jpg" -exec mv {} /home/user/Pic/ \; #mv all jpeg from Downloads in Pic

locate #fast search files
which #find command locate
Type #output of the exact command
Whereis #find command locate, sours, manuals

Пользователи и группы

addgroup testgroup #create new group
useradd testuser -g testgroup #create new user and add hm in testgroup
	-m #создать домашний каталог пользователя
	-U #создать личную группу с именем, совпадающим с именем пользователя
usermod -aG testgroup testuser #add user in group
chown testuser:testgroup ./testfile.txt #change owner testfile
chown -R testuser:testgroup ./ #change owner for all dir and files recursive
su testuser #work from other testuser
Ctrl+D #exit from testuser
id testuser #get user id, group
sudo passwd testuser #create pass in testuser
sudo userdel -r testuser #удалить пользователя, домашний каталог пользователя с его содержимым и папку электронной почты

find /home -uid 1001 #Отыскать все файлы в dir /home, принадлежащие пользователю c id 1001
find / -gid 1007 # -//- по gid
find / -name testuser # -//- по name
find / -group testgroup # -//- по group

Его величество grep

grep -n text file.txt #find coincidences "text" in file.txt and numerate string
     -i #without register
ls -l | grep "Documents" #find Documents in ls
ps auxf | grep myproc | grep -v grep #исключить из выдачи процесс самого grep

Информация о носителях информации

fdisk -l #what partitions are there on the disk
df -h #free space on disk

Read more

Логи попыток входа по SSH

Логи попыток входа по SSH

Основанно на этой статье cat /var/log/auth.log grep "Failed password" /var/log/auth.log grep "failure" /var/log/auth.log Используя функционал команд awk, uniq и sort, можно определить, с каких IP-адресов было наибольшее количество неудачных попыток установления SSH-соединений: grep "Failed password"

Аутентификация SSH по ключу

Аутентификация SSH по ключу

1. Создайте ключ на локальном компьютере: запустите терминал и выполните команду ssh-keygen. Задайте пароль (кодовую фразу) для ключа, или можно несколько раз нажать Enter. cat ~/.ssh/id_rsa #посмотреть приватный ключ cat ~/.ssh/id_rsa.pub #посмотреть публичный ключ 1. Скопируйте ключ на сервер: выполните в терминале команду ssh-copy-id user@

Docker manual

Docker manual

Base of Docker sudo systemctl start docker #start docker demon manually docker ps #показывает список запущенных контейнеров docker ps -a #показывает список запущенных и остановленных контейнеров docker container ls #аналогично docker images #показывает список локальных образов docker run hello-world #создание контейнера из образа hellp-world --name simple_name #задаем имя контейнеру