Crmgo Blog

LINUX COMMANDS

LINUX COMMANDS

LINUX COMMANDS Command Description System Information arch display the computer architecture uname -m uname -r display the currently used kernel version dmidecode -q show hardware system components - (SMBIOS / DMI) hdparm -i /dev/hda output hard disk characteristics hdparm -tT /dev/sda test performance...

LINUX COMMANDS

LINUX COMMANDS

 

Command Description
System Information
arch display computer architecture
uname -m
uname -r display the currently used kernel version
dmidecode -q show hardware system components - (SMBIOS / DMI)
hdparm -i /dev/hda display hard disk characteristics
hdparm -tT /dev/sda test data read performance from the hard disk
cat /proc/cpuinfo display processor information
cat /proc/interrupts show interrupts
cat /proc/meminfo check memory usage
cat /proc/swaps show swap file(s)
cat /proc/version display kernel version
cat /proc/net/dev show network interfaces and their statistics
cat /proc/mounts display mounted file systems
lspci -tv show PCI devices in tree format
lsusb -tv show USB devices in tree format
date display system date
cal 2007 display the 2007 calendar
date 041217002007.00 set system date and time MMDDhhmmYYYY.ss (MonthDayHourMinutesYear.Seconds)
clock -w save system time to BIOS
System Shutdown
shutdown -h now Stop the system
init 0
telinit 0
shutdown -h hours:minutes & schedule system shutdown for a specified time
shutdown -c cancel a scheduled system shutdown
shutdown -r now Reboot the system
reboot
logout log out of the system
Files and Directories
cd /home change to the '/home' directory
cd .. change to the parent directory
cd ../.. change to the directory two levels up
cd change to the home directory
cd ~user change to the home directory of user 'user'
cd - change to the directory you were in before the current one
pwd show the current directory
ls display the contents of the current directory
ls -F display the contents of the current directory with type-indicating characters appended to names
ls -l show detailed listing of files and directories in the current directory
ls -a show hidden files and directories in the current directory
ls *[0-9]* show files and directories containing digits in their names
tree display the file and directory tree starting from the root (/)
lstree
mkdir dir1 create a directory named 'dir1'
mkdir dir1 dir2 create two directories simultaneously
mkdir -p /tmp/dir1/dir2 create a directory tree
rm -f file1 delete the file named 'file1'
rmdir dir1 delete the directory named 'dir1'
rm -rf dir1 delete the directory named 'dir1' and all its contents recursively
rm -rf dir1 dir2 delete two directories and their contents recursively
mv dir1 new_dir rename or move a file or directory
cp file1 file2 copy file file1 to file file2
cp dir/* . copy all files from directory dir to the current directory
cp -a /tmp/dir1 . copy directory dir1 with all its contents to the current directory
cp -a dir1 dir2 copy directory dir1 to directory dir2
ln -s file1 lnk1 create a symbolic link to a file or directory
ln file1 lnk1 create a "hard" (physical) link to a file or directory
touch -t 0712250000 fileditest modify the creation date and time of a file; if it doesn't exist, create a file with the specified date and time (YYMMDDhhmm)
Finding Files
find / -name file1 find files and directories named file1. Search starts from the root (/)
find / -user user1 find files and directories belonging to user user1. Search starts from the root (/)
find /home/user1 -name "*.bin" Find all files and directories whose names end with '.bin'. Search starts from '/home/user1'
find /usr/bin -type f -atime +100 find all files in '/usr/bin' that have not been accessed in more than 100 days
find /usr/bin -type f -mtime -10 find all files in '/usr/bin' created or modified within the last 10 days
find / -name *.rpm -exec chmod 755 '{}' \; find all files and directories whose names end with '.rpm' and change their permissions
find / -xdev -name "*.rpm" find all files and directories whose names end with '.rpm', ignoring removable media such as cdrom, floppy, etc.
locate "*.ps" find all files containing '.ps' in their name. It is recommended to run 'updatedb' beforehand
whereis halt shows the location of binary files, source code, and manuals related to the 'halt' file
which halt displays the full path to the 'halt' file
Mounting File Systems
mount /dev/hda2 /mnt/hda2 mounts partition 'hda2' at mount point '/mnt/hda2'. Ensure the mount point directory '/mnt/hda2' exists
umount /dev/hda2 unmounts partition 'hda2'. Before executing, leave '/mnt/hda2'
fuser -km /mnt/hda2 force unmounting of the partition. Used when the partition is busy with some user
umount -n /mnt/hda2 perform unmounting without updating /etc/mtab. Useful when the file has "read-only" attributes or there is insufficient disk space
mount /dev/fd0 /mnt/floppy mount a floppy disk
mount /dev/cdrom /mnt/cdrom mount a CD or DVD
mount /dev/hdc /mnt/cdrecorder mount a CD-R/CD-RW or DVD-R/DVD-RW(+-)
mount -o loop file.iso /mnt/cdrom mount an ISO image
mount -t vfat /dev/hda5 /mnt/hda5 mount a Windows FAT32 file system
mount -t smbfs -o username=user,password=pass//winclient/share [/mnt/share mount a Windows network file system (SMB/CIFS)
mount -o bind /home/user/prg /var/ftp/user "mounts" a directory into a directory (binding). Available since kernel version 2.4.0. Useful, for example, for providing the contents of a user's directory via ftp when the ftp server is running in a "sandbox" (chroot), where symbolic links cannot be used.
Disk Space
df -h displays information about mounted partitions showing total, available, and used space (Translator's Note. The -h flag does not work in all *nix systems)
ls -lSr [|more outputs a list of files and directories recursively sorted by size in ascending order and allows for paginated viewing
du -sh dir1 calculates and displays the size occupied by directory 'dir1' (Translator's Note. The -h flag does not work in all *nix systems)
du -sk * [| sort -rn displays the size and names of files and directories, sorted by size
rpm -q -a [--qf '%10{SIZE}t%{NAME}n' [| sort -k1,1n shows the disk space used by rpm package files, sorted by size (fedora, redhat, etc.)
dpkg-query -W -f='${Installed-Size;10}t${Package}n'[| sort -k1,1n shows the disk space used by deb package files, sorted by size (ubuntu, debian, etc.)
Users and Groups
groupadd group_name create a new group named group_name
groupdel group_name delete group group_name
groupmod -n new_group_name old_group_name rename group old_group_name to new_group_name
useradd -c "Nome Cognome" -g admin -d /home/user1 -s /bin/bash user1 create user user1, set their home directory to /home/user1, shell to /bin/bash, add them to group admin, and add comment Nome Cognome
useradd user1 create user user1
userdel -r user1 delete user user1 and their home directory
usermod -c "User FTP" -g system -d /ftp/user1 -s /bin/nologin user1 change user attributes
passwd change password
passwd user1 change password for user user1 (root only)
chage -E 2005-12-31 user1 set the expiration date for user user1's account
pwck check the correctness of system account files. Checks /etc/passwd and /etc/shadow
grpck checks the correctness of system account files. Checks /etc/group
newgrp [-] group_name changes the primary group of the current user. If "-" is specified, the situation will be identical to the user logging out and logging back in. If no group is specified, the primary group will be assigned from /etc/passwd
Setting/Changing File Permissions
ls -lh view permissions on files and directories in the current directory
ls /tmp [| pr -T5 -W$COLUMNS display the contents of the /tmp directory and split the output into five columns
chmod ugo+rwx directory1 add permissions to directory directory1 ugo(User Group Other)+rwx(Read Write eXecute) - full rights for everyone. The same can be done with "chmod 777 directory1"
chmod go-rwx directory1 remove all permissions from the group and others for directory directory1.
chown user1 file1 assign user user1 as the owner of file file1
chown -R user1 directory1 recursively assign user user1 as the owner of directory directory1
chgrp group1 file1 change the group owner of file file1 to group1
chown user1:group1 file1 change the owner and group owner of file file1
find / -perm -u+s find all files with SUID set, starting from the root
chmod u+s /bin/binary_file assign the SUID bit to file /bin/binary_file. This allows any user to execute the file with the file owner's permissions.
chmod u-s /bin/binary_file remove the SUID bit from file /bin/binary_file.
chmod g+s /home/public assign the SGID bit to directory /home/public.
chmod g-s /home/public remove the SGID bit from directory /home/public.
chmod o+t /home/public assign the STICKY bit to directory /home/public. Allows files to be deleted only by their owners
chmod o-t /home/public remove the STICKY bit from directory /home/public
Special File Attributes
chattr +a file1 allow opening the file for writing only in append mode
chattr +c file1 allows the kernel to automatically compress/decompress the file contents.
chattr +d file1 tells the dump utility to ignore this file during backup
chattr +i file1 makes the file immutable: no editing, deletion, moving, or creating links to it.
chattr +s file1 allows secure deletion of the file, i.e., setting the s attribute means that when the file is deleted, the space it occupied on the disk is filled with zeros, preventing data recovery.
chattr +S file1 indicates that changes will be synchronized upon saving, as if the sync command were executed
chattr +u file1 this attribute indicates that upon file deletion, its contents will be saved and the user can restore them if necessary
lsattr show file attributes
Archiving and Compressing Files
bunzip2 file1.bz2 decompress file 'file1.gz'
gunzip file1.gz
gzip file1 compress file 'file1'
bzip2 file1
gzip -9 file1 compress file file1 with maximum compression
rar a file1.rar test_file create rar archive 'file1.rar' and include file test_file
rar a file1.rar file1 file2 dir1 create rar archive 'file1.rar' and include file1, file2, and dir1
unrar x file1.rar extract rar archive
tar -cvf archive.tar file1 create tar archive archive.tar containing file file1
tar -cvf archive.tar file1 file2 dir1 create tar archive archive.tar containing file file1, file2, and dir1
tar -tf archive.tar display archive contents
tar -xvf archive.tar extract archive
tar -xvf archive.tar -C /tmp extract archive to /tmp
tar -cvfj archive.tar.bz2 dir1 create archive and compress it with bzip2(Translator's Note. The -j flag does not work in all *nix systems)
tar -xvfj archive.tar.bz2 decompress and extract archive(Translator's Note. The -j flag does not work in all *nix systems)
tar -cvfz archive.tar.gz dir1 create archive and compress it with gzip
tar -xvfz archive.tar.gz decompress and extract archive
zip file1.zip file1 create compressed zip archive
zip -r file1.zip file1 file2 dir1 create compressed zip archive including multiple files and/or directories
unzip file1.zip decompress and extract zip archive
RPM Packages (Fedora, Red Hat, etc.)
rpm -ivh package.rpm install package with messages and progress bar
rpm -ivh [--nodeps package.rpm install package with messages and progress bar without dependency checking
rpm -U package.rpm upgrade package without changing configuration files; if the package is not installed, it will be installed
rpm -F package.rpm upgrade package only if it is already installed
rpm -e package_name.rpm remove package
rpm -qa display list of all packages installed in the system
rpm -qa [| grep httpd among all packages installed in the system, find the package containing "httpd" in its name
rpm -qi package_name display information about a specific package
rpm -qg "System Environment/Daemons" display packages belonging to a package group
rpm -ql package_name display list of files included in the package
rpm -qc package_name display list of configuration files included in the package
rpm -q package_name [--whatrequires display list of packages required to install a specific package by dependencies
rpm -q package_name [--whatprovides show capability provided by a rpm package
rpm -q package_name [--scripts display scripts run during package installation/removal
rpm -q package_name [--changelog display package revision history
rpm -qf /etc/httpd/conf/httpd.conf check which package owns the specified file. Specify the full path and file name.
rpm -qp package.rpm -l displays list of files included in the package but not yet installed in the system
rpm [--import /media/cdrom/RPM-GPG-KEY import public key of digital signature
rpm [--checksig package.rpm check package signature
rpm -qa gpg-pubkey check integrity of installed package contents
rpm -V package_name check size, permissions, type, owner, group, MD5 checksum, and last modification date of the package
rpm -Va check contents of all packages installed in the system. Use with caution!
rpm -Vp package.rpm check a package that is not yet installed in the system
rpm2cpio package.rpm [| cpio [--extract [--make-directories *bin* extract files containing 'bin' in their name from the package
rpm -ivh /usr/src/redhat/RPMS/`arch`/package.rpm install a package built from source code
rpmbuild [--rebuild package_name.src.rpm build a package from source code
YUM - Package Update Tool (Fedora, RedHat, etc.)
yum install package_name download and install package
yum update update all packages installed in the system
yum update package_name update package
yum remove package_name remove package
yum list display list of all packages installed in the system
yum search package_name find package in repository
yum clean packages clean rpm cache by removing downloaded packages
yum clean headers remove all file headers that the system uses to resolve dependencies
yum clean all clean rpm cache by removing downloaded packages and headers
DEB Packages (Debian, Ubuntu, etc.)
dpkg -i package.deb install / update package
dpkg -r package_name remove package from the system
dpkg -l show all packages installed in the system
dpkg -l [| grep httpd among all packages installed in the system, find the package containing "httpd" in its name
dpkg -s package_name display information about a specific package
dpkg -L package_name display list of files included in the package installed in the system
dpkg [--contents package.deb display list of files included in the package not yet installed in the system
dpkg -S /bin/ping find the package containing the specified file.
APT - Package Management Tool (Debian, Ubuntu, etc.)
apt-get install package_name install / update package
apt-cdrom install package_name install / update package from cdrom
apt-get update get updated package lists
apt-get upgrade update packages installed in the system
apt-get remove package_name remove package installed in the system while keeping configuration files
apt-get purge package_name remove package installed in the system and delete configuration files
apt-get check check dependency integrity
apt-get clean remove downloaded package archive files
apt-get autoclean remove old downloaded package archive files
Viewing File Contents
cat file1 display contents of file file1 to standard output
tac file1 display contents of file file1 to standard output in reverse order (last line becomes first, etc.)
more file1 paginated display of contents of file file1 to standard output
less file1 paginated display of contents of file file1 to standard output, but with ability to scroll in both directions (up-down), search within content, etc.
head -2 file1 display first two lines of file file1 to standard output. By default, ten lines are displayed
tail -2 file1 display last two lines of file file1 to standard output. By default, ten lines are displayed
tail -f /var/log/messages display contents of file /var/log/messages to standard output as text appears in it.
Text Manipulation
cat file [| grep -i "Criteria" > result.txt general syntax for processing file contents and outputting result to a new file
cat file [| grep -i "Criteria" » result.txt general syntax for processing file contents and outputting result to an existing file. If the file does not exist, it will be created
grep Aug /var/log/messages from file '/var/log/messages', select and display lines containing "Aug" to standard output
grep [^Aug /var/log/messages from file '/var/log/messages', select and display lines starting with "Aug" to standard output
grep [0-9] /var/log/messages from file '/var/log/messages', select and display lines containing digits to standard output
grep Aug -R /var/log/* select and display lines containing "Aug" to standard output in all files located in directory /var/log and below
sed 's/stringa1/stringa2/g' example.txt in file example.txt, replace "string1" with "string2", output result to standard output.
sed ['/^$/d' example.txt remove empty lines from file example.txt
sed ['/ *#/d; [/^$/d' example.txt remove empty lines and comments from file example.txt
echo 'test' [| tr '[:lower:]' '[:upper:]' convert characters from lowercase to uppercase
sed -e '1d' result.txt remove first line from file example.txt
sed -n '/string1/p' display only lines containing "string1"
sed -e 's[/ *$[/]/' example.txt remove whitespace characters at the end of each line
sed -e 's[/string1[/]/g' example.txt remove line "string1" from text without changing the rest
sed -n '1,8p;5q' example.txt take lines from first to eighth from file and display the first five of them
sed -n '5p;5q' example.txt display fifth line
sed -e 's/0*/0/g' example.txt replace any sequence of zeros with a single zero
cat -n file1 number lines when displaying file contents
cat example.txt [| awk 'NR%2==1' when displaying file contents, do not output even-numbered lines
echo a b c [| awk '{print $1}' display first column. Separation is by space(s) or tab(s) by default
echo a b c [| awk '{print $1,$3}' display first and third columns. Separation is by space(s) or tab(s) by default
paste file1 file2 combine contents of file1 and file2 in table format: row 1 from file1 = row 1 column 1-n, row 1 from file2 = row 1 column n+1-m
paste -d '+' file1 file2 combine contents of file1 and file2 in table format with separator "+"
sort file1 file2 sort contents of two files
sort file1 file2 [| uniq sort contents of two files, not displaying duplicates
sort file1 file2 [| uniq -u sort contents of two files, displaying only unique lines (lines appearing in both files are not displayed to standard output)
sort file1 file2 [| uniq -d sort contents of two files, displaying only duplicate lines
comm -1 file1 file2 compare contents of two files, not displaying lines belonging to file 'file1'
comm -2 file1 file2 compare contents of two files, not displaying lines belonging to file 'file2'
comm -3 file1 file2 compare contents of two files, removing lines appearing in both files
Character Set and File Format Conversion
dos2unix filedos.txt fileunix.txt convert text file from MSDOS to UNIX format (difference in carriage return characters)
unix2dos fileunix.txt filedos.txt convert text file from UNIX to MSDOS format (difference in carriage return characters)
recode ..HTML < page.txt > page.html convert contents of text file page.txt to html file page.html
recode -l [| more display list of available formats
File System Analysis
badblocks -v /dev/hda1 check partition hda1 for bad blocks
fsck /dev/hda1 check/restore integrity of linux file system on partition hda1
fsck.ext2 /dev/hda1 check/restore integrity of ext2 file system on partition hda1
e2fsck /dev/hda1
e2fsck -j /dev/hda1 check/restore integrity of ext3 file system on partition hda1 specifying that the journal is located there
fsck.ext3 /dev/hda1 check/restore integrity of ext3 file system on partition hda1
fsck.vfat /dev/hda1 check/restore integrity of fat file system on partition hda1
fsck.msdos /dev/hda1
dosfsck /dev/hda1
Formatting File Systems
mkfs /dev/hda1 create linux file system on partition hda1
mke2fs /dev/hda1 create ext2 file system on partition hda1
mke2fs -j /dev/hda1 create journaling ext3 file system on partition hda1
mkfs -t vfat 32 -F /dev/hda1 create FAT32 file system on partition hda1
fdformat -n /dev/fd0 format floppy disk without checking
mkswap /dev/hda3 create swap space on partition hda3
Swap Space
mkswap /dev/hda3 create swap space on partition hda3
swapon /dev/hda3 activate swap space located on partition hda3
swapon /dev/hda2 /dev/hdb3 activate swap spaces located on partitions hda2 and hdb3
Creating Backups
dump -0aj -f /tmp/home0.bak /home create full backup of directory /home to file /tmp/home0.bak
dump -1aj -f /tmp/home0.bak /home create incremental backup of directory /home to file /tmp/home0.bak
restore -if /tmp/home0.bak restore from backup /tmp/home0.bak
rsync -rogpav [--delete /home /tmp synchronize /tmp with /home
rsync -rogpav -e ssh [--delete /home ip_address:/tmp synchronize via SSH tunnel
rsync -az -e ssh [--delete ip_addr:/home/public /home/local synchronize local directory with remote directory via ssh tunnel with compression
rsync -az -e ssh [--delete /home/local ip_addr:/home/public synchronize remote directory with local directory via ssh tunnel with compression
dd bs=1M if=/dev/hda [| gzip [| ssh user@ip_addr 'ddof=hda.gz' make a "snapshot" of local disk to a file on remote computer via ssh tunnel
tar -Puf backup.tar /home/user create incremental backup of directory '/home/user' to file backup.tar preserving permissions
( cd /tmp/local/ && tar c . ) [| ssh -C user@ip_addr 'cd/home/share/ && tar x -p' copy contents of /tmp/local to remote computer via ssh tunnel to /home/share/
( tar c /home ) [| ssh -C user@ip_addr 'cd /home/backup-home && tar x -p' copy contents of /home to remote computer via ssh tunnel to /home/backup-home
tar cf - . [| (cd /tmp/backup ; tar xf - ) copy one directory to another preserving permissions and links
find /home/user1 -name '*.txt' [| \ xargs cp -av [--target-directory=/home/backup/[--parents search in /home/user1 for all files ending with '.txt' and copy them to another directory
find /var/log -name '*.log' [| tar cv [--files-from=- [|bzip2 > log.tar.bz2 search in /var/log for all files ending with '.log' and create bzip archive from them
dd if=/dev/hda of=/dev/fd0 bs=512 count=1 create copy of MBR (Master Boot Record) from /dev/hda to floppy disk
dd if=/dev/fd0 of=/dev/hda bs=512 count=1 restore MBR from floppy disk to /dev/hda
CDROM
cdrecord -v gracetime=2 dev=/dev/cdrom -eject blank=fast -force clean a rewritable cdrom
mkisofs /dev/cdrom > cd.iso create an iso image of cdrom on disk
mkisofs /dev/cdrom [| gzip > cd_iso.gz create a compressed iso image of cdrom on disk
mkisofs -J -allow-leading-dots -R -V "Label CD" -iso-level 4 -o ./cd.iso data_cd create an iso image of a directory
cdrecord -v dev=/dev/cdrom cd.iso burn an ISO image
gzip -dc cd_iso.gz [| cdrecord dev=/dev/cdrom - burn a compressed ISO image
mount -o loop cd.iso /mnt/iso mount an ISO image
cd-paranoia -B rip audio tracks from a CD to wav files
cd-paranoia [-- "-3" rip first three audio tracks from a CD to wav files
cdrecord [--scanbus scan bus to identify the scsi channel
Network (LAN and WiFi)
ifconfig eth0 display configuration of network interface eth0
ifup eth0 activate (bring up) interface eth0
ifdown eth0 deactivate (bring down) interface eth0
ifconfig eth0 192.168.1.1 netmask 255.255.255.0 set ip address and subnet mask for interface eth0
ifconfig eth0 promisc put interface eth0 into promiscuous mode for "sniffing" packets
ifconfig eth0 -promisc disable promiscuous mode on interface eth0
dhclient eth0 activate interface eth0 in dhcp mode.
route -n display local routing table
netstat -rn
route add -net 0/0 gw IP_Gateway set default gateway ip address
route add -net 192.168.0.0 netmask 255.255.0.0 gw 192.168.1.1 add static route to network 192.168.0.0/16 via gateway with ip address 192.168.1.1
route del 0/0 gw IP_gateway remove default gateway ip address
echo "1" > /proc/sys/net/ipv4/ip_forward enable packet forwarding
hostname display computer name
host www[.yandex[.ru resolve hostname www[.yandex[.ru to ip address and vice versa
host 93.158.134.3
ip link show display status of all interfaces
mii-tool eth0 display status and connection type for interface eth0
ethtool eth0 displays statistics for interface eth0 including supported and current connection modes
netstat -tupn displays all established network connections by TCP and UDP protocols without resolving names to ip addresses and without displaying PIDs and process names providing these connections
netstat -tupln displays all network connections by TCP and UDP protocols without resolving names to ip addresses and without displaying PIDs and process names listening on ports
tcpdump tcp port 80 display all traffic on TCP port 80 (usually - HTTP)
iwlist scan scan airwaves for availability of wireless access points
iwconfig eth1 display configuration of wireless network interface eth1
Microsoft Windows networks (SAMBA)
nbtscan ip_addr resolve netbios name nbtscan is not installed by default in all systems, you may need to install it manually. nmblookup is included in the samba package.
nmblookup -A ip_addr
smbclient -L ip_addr/hostname display resources shared on a windows machine
smbget -Rr smb:[//ip_addr[/share similar to wget, can retrieve files from windows machines via smb protocol
mount -t smbfs -o username=user,password=pass[//winclient[/share [/mnt[/share mount smb resource provided on a windows machine to local file system
IPTABLES (firewall)
iptables -t filter -nL display all rule chains
iptables -nL
iptables -t nat -L display all rule chains in NAT table
iptables -t filter -F clear all rule chains in filter table
iptables -F
iptables -t nat -F clear all rule chains in NAT table
iptables -t filter -X delete all user-defined rule chains in filter table
iptables -t filter -A INPUT -p tcp [--dport telnet -j ACCEPT allow incoming telnet connection
iptables -t filter -A OUTPUT -p tcp [--dport http -j DROP block outgoing HTTP connections
iptables -t filter -A FORWARD -p tcp [--dport pop3 -j ACCEPT allow "forwarding" (forward) POP3 connections
iptables -t filter -A INPUT -j LOG [--log-prefix "DROP INPUT" enable kernel logging of packets passing through INPUT chain and adding prefix "DROP INPUT" to the message
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE enable NAT (Network Address Translate) for outgoing packets on interface eth0. Allowed when using dynamically assigned ip addresses.
iptables -t nat -A PREROUTING -d 192.168.0.1 -p tcp -m tcp [--dport 22 \ -j DNAT [--to-destination 10.0.0.2:22 redirect packets addressed to one host to another host
Monitoring and Debugging
top display running processes, their resource usage, and other useful information (with automatic data update)
ps -eafw display running processes, their resource usage, and other useful information (once)
ps -e -o pid,args [--forest display PIDs and processes in tree format
pstree display process tree
kill -9 98989
kill -KILL 98989
kill -TERM 98989 Gracefully terminate process with PID 98989
kill -1 98989 force process with PID 98989 to re-read configuration file
kill -HUP 98989
lsof -p 98989 display list of files opened by process with PID 98989
lsof /home/user1 display list of open files from directory /home/user1
strace -c ls > /dev/null display list of system calls created and received by process ls
strace -f -e open ls > /dev/null display library calls
watch -n1 'cat /proc/interrupts' display interrupts in real-time
last reboot display system reboot history
last user1 display user user1's login history in the system and their session duration
lsmod display loaded kernel modules
free -m show RAM status in megabytes
smartctl -A /dev/hda monitor status of hard disk /dev/hda via SMART
smartctl -i /dev/hda check SMART availability on hard disk /dev/hda
tail /var/log/dmesg display last ten entries from kernel boot log
tail /var/log/messages display last ten entries from system log
Other Useful Commands
apropos …keyword displays list of commands that somehow relate to keywords. Useful when you know what a program does but don't remember the command
man ping call manual for program, in this case, - ping
whatis …keyword displays description of actions for the specified program
mkbootdisk [--device /dev/fd0 `uname -r` creates bootable floppy disk
gpg -c file1 encrypts file file1 using GNU Privacy Guard
gpg file1.gpg decrypts file file1 using GNU Privacy Guard
wget -r www[.example[.com recursively downloads contents of site www[.example[.com
wget -c www[.example[.com/file[.iso download file www[.example[.com/file[.iso with ability to pause and resume later
echo 'wget -c www[.example[.com/files[.iso' [| at 09:00 start download at specified time
ldd /usr/bin/ssh display list of libraries required for ssh to work
alias hh='history' assign alias hh to command history

The kernel operates in a single address space. That is, one module or driver can corrupt the entire kernel.
Ctrl + Alt + F(1-6) switches between virtual consoles. ttyN - where N is the console number?
Ctrl + Alt + F7 switches to the graphical console
startx _launches the X Windows System (switches to graphical mode)
ho -r or runlevel _displays the OS runlevel !!!
init n (n from 0 to 6) starts one of the OS runlevels, for example, 3. That is, it launches the rc3.d file, which contains symbolic links to files in init.d.
The link name can start with K-stop or S-start, followed by the startup priority number.
*************
mount /dev/hda4 mnt/hda4 -t data=<journaling mode> _writeback, ordered, journal?
Creating a new ext3 file system
1. Create a partition using parted or fdisk
2. Format the partition with mkfs
3. Assign a label to the partition using e2label
4. Create a mount point with mkdir
5. Add the partition to the /etc/fstab file
*************
GRUB bootloader
Press E to enter the record editor interface. Esc to discard changes and return to the menu.
Press B (after editing) to execute commands and boot the OS
Press C to enter the command-line interface, enter commands, and press Enter to execute
help all - displays all commands
Select the kernel and press A. At the end of the line, add the runlevel number separated by a space.
less /boot/grub/grub.conf _bootloader configuration file
**************************
2.1 Superblocks - important disk information?
dumpe2fs /dev/sda1 | grep superblock _superblock information
Using a backup superblock: all?
1. Boot from a Live CD or CentOS installation disk
2. fsck -y -b 8193 /dev/sda1 _Check disk; 8193 is the number of the first backup superblock
3. Mount the file system
3.1 In the usual way
3.2 If unsuccessful:
mount sb=8193 /dev/sda1 /mnt _backup superblock number /device /mount point
4. Add the sb option (sb=8193) to our file system in /etc/fstab
*********************
File access permissions
123 456 789
s t rwx rwx rwx
s _SUID bit - 4 (000) The file acquires the rights of the file owner, not the user who launched it (the passwd utility must have execute permissions). ***In the shell, files with the SUID bit are highlighted in red.
t _Sticky bit - 1 (000)
1/2/3 _read/write/execute for the owner
4/5/6 _read/write/execute for the owner's group
7/8/9 _read/write/execute for others
Read permission is denoted by the number 4, write by 2, and execute by 1.
If all permissions are allowed, the permission number set for a specific group on the file is 7.

chmod [options] [mode] file - change access permissions. -v - outputs debug information, -R - recursive mode, changes permissions for all subdirectories and files
chmod 4755 test.txt _4-adds the suid bit, 7-full permissions for the owner, 5 and 5 - read and execute for group and others - this command on a file in the root home directory (folder) issued the message: You have new mail in /var/spool/mail/root ?
-rwsr-xr-x root root 1 _should be read as rws (s instead of x) rx rx, root - owner, root - owner's group, 1 - number of links
Reverse: chmod 0755 test.txt or chmod 755 test.txt - 0 before 7 is substituted by default.
chmod 750 test.txt - 0 zeroes the permission value
chmod -R u=rwx,g=rx,o=x myfiles - 2nd method of changing permissions for a directory or file.
chmod -R u-x,g-x,o-x myfiles - 3rd method of changing permissions for a directory or file separately for each user group, where a - owner, g - owner's group, o - all others.
chmod -R a-x myfiles - 4th method of changing permissions for a directory or file for all users. In 3 and 4 you can use -/+
chmod +x script.sh - add execute permission for all groups. 5th method of changing permissions.

sgid-bit - 2 (000) - owner group permissions are inherited. If the sgid bit is set for a directory, then files created in it, when run, will take the directory's group identifier, not the group to which the file owner belongs.
Running a program with owner group permissions? How to do it correctly?
sgid-bit for a file: chmod 2755 test.txt

sticky-bit - 1 (000) - if set on a directory, then only the owner of this directory, the file owner, or root can delete and rename files in this directory. Having only write permission to this directory is not enough.
chmod 1755 test.txt

chown [options] [owner]:[group] test.txt - change file owner and group. -v - outputs debug information, -R - recursive mode.
[owner]:[group] - this is the new owner and new group.
chown -R user1:user1 * - change owner and group for all files and subdirectories of the current directory. Cannot change the owner of a subdirectory. Who has the right to change the owner of a file or directory?
chgrp group1 file1 – change group.

umask XXXX - change (set) access mode, sets access permissions for newly created directories and files!!!
The umask value is subtracted from 777 for directories and from 666 for files.
umask - find out what umask is used in the system, mine: 0022.
New directories: 0777 - 0022 = 0755. New files 0666 - 0022 = 0644

umask 0 1 2 3 4 5 6 7
Access mode mask r w x r w - r - x r - - - w x - w - - - x - - -

mount [options] [device] [mount_point] - mount a filesystem
umount [options] [device] OR [mount_point] -f force unmount
mount - list mounted filesystems
When mounting, you can specify permissions. You can mount the entire filesystem as read-only. This will override previously assigned permissions.
Mount a CD: mount -t iso9660 /dev/cdrom /mnt _specify filesystem type (not mandatory for CDs)
Mount an image: mount -o loop -t iso9660 image.iso /mnt/iso didn't work?
iso9660 for mounting Unix systems and CDs/DVDs; mount -t ext3 /dev/sda4 /disk mount does not create partitions.
nfs for mounting network filesystems
vfat, ntfs for mounting Windows partitions
ufs for Solaris
The file /etc/fstab contains a list of filesystems to be automatically mounted at OS startup.
[device] [mount_point] [filesystem_type] [options] [dump_flag _obsolete] [fsck_flag (0-do not check, 1-check, 2-check after 1 has been checked)]
cat /etc/fstab –
Device names:
hdc – hard disks
scsi -

cat /etc/mtab (mount) _ view information about mounted filesystems. Not manually editable.
/etc/filesystems _ list of possible filesystems. Used by the mount command for auto-completion if the -t flag with the filesystem type is not specified.

The proc filesystem exists only in RAM. It is used as an interface to kernel data structures. This is a virtual filesystem, loaded into memory at system startup, and does not occupy space on the hard drive. Many files in it can be modified, thereby changing kernel parameters in real time.
cat /proc/cpuinfo, meminfo, mounts, devices, filesystems, modules, version, cmdline - list of parameters passed to the kernel at boot. A great source of system information!!!

Working with files:
Create a text file using a text editor like vi/vim, or by redirecting the output of the echo or cat command.
vim editor:
i - enter insert mode. Esc - after entering text, return to command mode.
: - to enter commands for file operations, editing settings, and other commands.
Now you can enter: w - to write/save the file, and q to exit the editor. q! – exit without saving.
/ - search
touch test.txt – update the access time of an existing file (create a new one in the current directory). By default, a file is created with permissions 644. Usually changed to 775/ 755
touch 's probelom'.txt – create a file with a space in the name.

cp [options] [source] [destination] - copy a file or directory.
cp test.txt test1.txt - create test1 as a copy of test.txt, cp /etc/test.txt ~ - copy test.txt to the home directory.
cp -r /etc/ /root/dok - copy the contents of the /etc/ directory into the newly created folder /root/dok. You cannot copy a file while simultaneously creating a folder, only the contents of the directory.

mv [options] [source] [destination] - move files
mv file.txt /tmp/ - move file.txt to /tmp/ without renaming
mv /tmp/file.txt ~/file2.txt - move file.txt, renaming it to file2.txt

A soft link points to a file, a hard link points to the file's inode.
ln [options] [target] [link_name] - create links between files.
ln -s file.txt lnk - create a symbolic (soft) link lnk (via -s) - instead of the file's path name, you can specify an alias, which points to the file.
ln file2.txt file.txt - create a hard link - points to the file's inode
unlink lnk - remove a soft link

cat – view, less – page-by-page/line-by-line output, q – exit, Shift + PgUp/PgDn – navigation.
cat test.txt test1.txt – display the contents of 2 files on the screen.
cat test.txt test1.txt > test2.txt – merge files into 1.
cat test1.txt > test2.txt – replace the contents of file test2 with the contents of file test1.
cat test1.txt >> test2.txt – append the contents of file test1 to the contents of file test2.
cat - >> test1.txt – append data to file test1 directly from the shell. Ctrl + C – save changes.

head -n 20 test.txt – display the first 20 lines of the file (10 lines by default).
tail -n 20 test.txt – display the last 20 lines of the file (10 lines by default).
nl test.txt – display the file with line numbers.

df [options] [file] – filesystem usage statistics. You can use df, df -h, or df -h /dev/sda1.
du [options] [file] – disk space statistics. du -hs /usr/share – display the size of the /usr/share directory.
-h – provides statistics in a human-readable format (e.g., MB, etc.). -s – summarizes the results of subdirectories and files within them.

echo [options] [string] – display a string of text. echo -n 'blablabla' – displays blablabla on the same line.
echo 'blablabla' – displays blablabla on a new line.
echo 'blablabla' > file.txt – replace the contents of the file; echo 'blablabla' >> file.txt – append to the file contents.

wc [options] [file] – file statistics !!!
-c – number of bytes in the file, -m – number of characters in the file, -l – number of lines in the file, -L – length of the longest line.
-w – number of words in the file.

find [search_path] [search_option] [value] [action_option] – search for files or directories.
-name – name of the file or directory to find.
-type – object type: f – regular file, d – directory, b – block device, c – character device, p – named pipe, l – symbolic link, s – socket.
-size – use file size as a search criterion.
-mtime – modification date.
-ctime – time of the last change to file attributes. What is the difference between mtime and ctime?
-atime – time of the last access to the file touch?
-perm 777 – with access rights 777.
-print – simply print the full path of the file.
-exec – execute a specific command for the found objects.
find / -name pab -type d
find /tmp/ -name core -type f -print | xargs /bin/rm -f – search for a file, print it to the screen, and using xargs, pass it as an argument to the rm command.
find /etc/ -perm 777 -type f – search for files with permissions 777 in the /etc directory.
find /etc/ -name pablish -exec rm -rf {} \; – execute the rm -rf command for the found objects. The found items will be substituted in place of {} as arguments.

F4 - open file
Working with directories:
mkdir - create, ls - view, mv - rename/move, rm -rf - delete occupied directories, rmdir - delete empty directories !!!
mkdir –p ~/test/cda/blabla _100% create subdirectories in the home directory
mkdir -p /root/dok/dir2{dir1,dir2,dir3} – create directory structure dok/dir2 with 3 sections dir1-3
«.» - current directory, «..» - parent directory, for root «.» = «..»
mkdir -m 700 dir2 - explicitly set permissions for the new directory
rm -rf* - delete all contents of the current partition,
where -r - recursive mode, -f - disable confirmation prompts
rmdir ~/test _delete empty subdirectory of the home directory
mknod _create byte-oriented devices - printers, modems rm _delet?
mknod _create block-oriented devices - hard disk?
mknod _create named pipes rm _delet?
socket can be deleted with rm

ls - display directory contents.
ls -lhR /etc/ | less - redirect output through a pipe to the less command
-a - all including hidden files (starting with a dot), -h - file sizes, -l - full info, -i - inodes (index descriptors), -R - info for all subdirectories -t – sort by time, /*.txt – search by mask
Man ls – help.
q – exit, Pg Up, Pg Dn – navigation. / - enter search, n - down N - up
ls ../.. _view two levels up, ls ../man _find directory man one level up
ls -l /dev/sda = file /dev/sda, ls –l /root /tmp /usr …- display multiple files
ls –l /etc/*/*.conf – search by extension, "skipping" 1 level
ls -l /etc/[^a-w]*.conf - searches for directories not starting with a-w with conf extension.
ls –ld – permissions for the current directory.
cd – change directory – change directory
cd /usr/share/doc - navigate using absolute path
cd - _to previous directory, cd .. _one level up, cd ~ _to home directory,
cd ~/myfiles _navigate from any location to a newly created subdirectory of the home directory.

grep [options] pattern [file path to search] - Pattern search.
rpm -qa | grep chk - search for chk in the output of all packages installed in the system.

/dev/null - the so-called black hole, used to absorb unnecessary program output
command > /dev/null 2>&1 - redirect all errors to /dev/null.
/dev/zero - can be used to create a file of a specific size
dd if=/dev/zero of=file.iso bs=1024 count=1024 - create a 1 Mb iso file.
/dev/random, /dev/urandom - used by scripts to generate random numbers.

BASH:
# - command line with administrator privileges
$ - command line of a regular user - can work in the home directory without affecting the system as a whole

Ctrl + C - interrupt current process (SIGINT signal)
Ctrl + D - exit command interpreter
Ctrl + L - clear screen
Ctrl + Z - move process to background mode
Alt + D - delete all characters from current position to end of word
Alt + R - clear entire line
Double TAB - all available commands
Esc + D - delete from cursor to end of word

echo $BASH_VERSION - BASH version. $ - variable sign, i.e. output of BASH_VERSION variable.
echo $BASH - BASH location

Command format: command_name [flags/options] [arguments]
./name_script.sh - run a script from the home directory
BASH Configuration Files
1. Local - located in the home directories of system users and take precedence over Global files.
.bash_logout - script executed upon system logout
.bash_history - file containing command history, which is saved to the file after the user logs out. Can be configured to save immediately?
.bash_profile - script executed when you connect to the system (in some systems, bashlogin is used)
.bashrc - script executed every time a new shell is opened. It is executed, along with all commands listed within it.
2. Global:
/etc/profile
/etc/bashrc

history - view command history. The number of lines is set by the variable echo $HISTSIZE, defaulting to 1000 lines.
history N - display the last N lines.
history -d N - delete line N.
!! - execute the last entered command
!N - execute command N
!string - the most recent command starting with the string "string"

Input/Output Redirection.
File descriptor - a non-negative integer assigned by the OS to a file opened by a process. There are always 3 file descriptors open in the system.

Number Name Description Comment
0 stdin Standard input - keyboard input is handled by the keyboard
1 stdout Standard output - monitor display is handled by the monitor
2 stderr Used for outputting error messages

cat file1 file3 2>err_file - error outputting non-existent file3 is redirected to the newly created file err_file. 2 represents stderr.
cat < /etc/resolv.conf - redirection from a file.
cat > file, then press Enter, and type text on a new line. End input with Ctrl + C. The entered text is added to the newly created file.
date > date.txt - when redirecting to a file, existing data is overwritten.
date >> date.txt - when redirecting to a file, append to existing data.
vi <(ls /etc) - redirect the contents of the etc directory into a text editor. Under what name should the result be saved?
echo -e "'ls -l /etc/[^a-w]*.conf'\n" - searches for directories not starting with a-w with the .conf extension. Does not work??? '- ?
Possible redirections:

From Where
stdout File
stdout Stderr
stdout and stderr Stdout
stdout and stderr Stderr
stdout and stderr File
stderr File
stderr Stdout
Pipes connect the standard output of one command to the input of another and are denoted by: |
ls /usr/share | wc -l - count the number of lines in the directory

Built-in commands are commands built into bash. enable (enable -a) - view all (outputs a list of commands)
rpm -qa | grep hist - searches for "hist" in system packages; this does not exist because the history command is built into bash.
When running, built-in commands are executed first, and only then is a search performed in the $PATH variable.
enable -n pwd - disables the built-in pwd command. After this, the system command pwd located in /bin/pwd will be executed.
enable -n - list of disabled built-in commands

Variables
Parent process > child process > child process, etc.
Processes can sequentially pass variable information to a lower level from the parent process to child processes, but not the other way around. A child process cannot pass anything to the parent process.
Value=10 – creates a variable and assigns its value. The variable will be available only in the current session.
Export Value=10 – now the variable can be used from other programs.
Unset value – deletes the variable.
env – view environment variables (exported ones). Here we will see them only after executing the command: Export Value.
typeset – view environment variables, including those created by the user.
Vim script.sh, the script itself:
#!/bin/bash
Echo $value
./script.sh – executes the script in the root user's home directory.
The Shell is the parent process for the script. We could allow it to use the variable by exporting it, or deny it by not exporting it.
Common variables: view echo $
$HOSTNAME – hostname
$Shell – name of the command interpreter
$USER – name of the user logged into the system
$PATH – list of OS directories where the system searches for a command when typed in the console. The search proceeds sequentially through the directories until the first match is found.
$PWD – current working directory
$HOME – current user's home directory
$UID – numeric identifier of the current user
$# – number of passed arguments
echo $PATH – a variable storing the list of directories in the OS

Local variables.
$0 – contains the name of the executed file
$1 – first argument
$2 – second argument
$PS1 – command line prompt

Vim script.sh, the script itself:
#!/bin/bash
Echo “first arg” - $0
Echo “second arg” - $1
…
Echo “10 arg” - ${10} – starting from the 10th argument, they must be specified in curly braces.
./script.sh first_arg second_arg – passing the 1st and 2nd arguments to the script

Useful commands:
cat /etc/passwd – displays the list of users
pwd – view the working directory. pwd [-LP]
ps aux | grep mingetty – find all system processes and output only those containing the word mingetty
whoami – returns the current user account under which the user is working.
netstat -nr – for network analysis
su user1 – switch to another user. Question: in what case, after switching to a regular user, is it meaningful to run the command: cd ~?
exit – return to the root command line
useradd – add a user – command not found when entered before startx?
Question: sudo useradd PPetrov – error occurs after entering the requested password?
#passwd Uliashov – change the password for any user from under root
$passwd Ivanov – change the password for a user according to security criteria.
date – view system date and time
env – view environment variables (exported ones)
typeset – view environment variables, including those created by the user.
df –h – disk space usage
rm mod pcspkr – unload the kernel driver from RAM
modprobe pcspkr
lsmod – list of modules
modinfo pcspkr – display information about the module

Lecture #4

Each directory contains 2 links. Adding each subdirectory adds +1 link.
Some disable swap to avoid constant disk thrashing.
fdisk -l – disk configuration
free – RAM statistics
vnc viewer 10.95.4.229
DOS system allows creating 3 partitions
Primary - standard
Extended – extended, within which you can create a logical partition
Partitions 1 to 4 are Primary or Extended. From 5 onwards – logical
swapon -a / swapoff -a – enable/disable swap
etoolabel ???
partprobe?
Download VNC viewer
mkswap – ???
mkfs hdc1(2-6)
If you mount a partition into a new folder, files created in that folder will actually reside on the mounted partition, not in the folder itself.

1 free
2 cat /proc/swaps
3 swapoff -a /dev/mapper/VolGroup00-LogVol01 - path from step 2
4 mkfs /dev/mapper/VolGroup00-LogVol01
5 mkdir /novyi
6 mount /dev/mapper/VolGroup00-LogVol01 /novyi
7 create folders and files in the mount point folder
8 umount
9 mkswap /dev/mapper/VolGroup00-LogVol01 – formatted the device
10 swapon -a

alias 'fuck' = 'init 0' – do not do this
Only root can mount filesystems (mount).
You can mount a remote filesystem, for example, temporarily for backup purposes.
In /etc/fstab, you can specify user permissions to mount a specific folder.

Lecture #6

LVM – Logical Volume Manager – see description online.
LV > VG – group > PV – hd1, ... physical disks are combined into 1 group. Or conversely, 1 disk is split into several volumes???. Possible performance loss ~ 5%.
vgs, pvs, lvs
Task: obtain a logical volume. ??????????
pvcreate /dev/hdc5
PV
VG
vgcreate VG1 /dev/hdc5 - create group
lvcreate -L 100M -n DataBase VG1 - create logical volume
ls /dev/VG1/DataBase - check.
Do:
1 free
2 cat /proc/swaps
3 swapoff -a /dev/mapper/VolGroup00-LogVol01 - path from step 2 - disabled
4 lvremove /dev/mapper/VolGroup00-LogVol01 - deleted
5 cat /proc/swaps
6 vgs – shows free space
7 lvcreate -L 100M -n MYVOL1 VolGroup00
8 mkfs /dev/VolGroup00/MYVOL1 – formatting
8 mount /dev/mapper/VolGroup00-MYVOL2 /novyi or mount /dev/VolGroup00/MYVOL1 /novyi
ls -l /Dev/VolGroup00 – link to dev/mapper/Vol…
You can make an instant snapshot of the partition state:
lvcreate -s /dev//VolGroup00/MYVOL1 -n SNAP_MYVOL1 -L 100M - a snapshot is also a new partition. It can be mounted as a partition to a mount point, but if you create a file in it, it will not appear in the snapshot
when creating files in the mount point, lvs will show changes in the snapshot partition
Before changing data, their history is written to the snapshot
Snapshots are created in the same volume group.
Create a read-only snapshot:
lvcreate -p r -s /dev//VolGroup00/MYVOL1 -n SNAP_MYVOL1 -L 100M – prevents writing to the mount point.
Commands:
Ctrl + r + enter search text
Ctrl + u – clear entire output (error when entering password)
Ctrl + W – clear by words
Ctrl + L – clear screen ???
Alt + . – output last parameter
Ctrl + S – lock screen. Ctrl + Q - unlock

 

article taken from here

Note: This post may be AI-assisted and then human-edited. Editorial responsibility: Dmytro Lomaka, Kaltenkirchen.