Linux Manual
Manual
man [command]- get help on the commandman [section-number] [command]- get help on the command in the section given by section-numberaproposman -k [keyword]- find the commands which deals with the keywordwhatisman -f [command]- one line help on the command
System Information
uname- show OS-sPrint kernel name-rPrint kernel release-mPrint Architecture-oPrint Operating System-n- show first letter of the domain-a- show every details about the system
sudo hostnamectl set-hostname mylittlecloudboxchanging hostname
Memory Management
freeShow memory usagefree -h|--humanShow human readable memory usagefree -h|--human --siShow human readable memory usage in power of 1000 instead of 1024free -s|--seconds 5Show memory usage and update continuously every five seconds
Users Management
adduser
-
add a new user, automatically creating a
- home directory
- choosing login shell
- creating a password
-
id user- show all the groups user is in and its uid and gid su - user- switch user to theuser, usually used for users with login disabled
useradd
- usually used to create account for services like
mysqlsystemd - adds new user but with no home directory
useradd -m username- adds new user and also creates a home directory
/etc/passwd file
- contains information about all the users on system
- format -
user_name:password:UID:GID:other_information:home_directory:login_shell- sample -
totoro:x:1000:1001:totoro:/home/totoro:/usr/bin/zshuser_name-totoropassword-xmeans encryptedUID-1001GID-1001other_information-totorohome_directory-/home/totorologin_shell-/usr/bin/zsh
- sample -
other_information- this usually contains the description about the user. On older machine it contained contact info, room number, which we are asked when we useadduserlogin_shell- for user account which is unusable it is set to/usr/sbin/nologinor/bin/falsepassword-xin password indicates encrypted password, which is present in the shadow file
/etc/shadow file
- contains the information about the password used by the users
- format -
user:$encryption$salt$hash:lastPasswordChange:min:max:warning:disable:expire:reserved_fielduser- name of the userpassword- combination of$encryption$salt$hash*or!indicates that we cannot login in the system with that userencryption- type of encryption used$1- md5$2blowfish$2aeksBlowfish$5sha-256$6SHA-512
$salt- salt value added while encryption$hash- the encrypted password
lastPasswordChange- date in unix format (no of days since Jan 1, 1970) of last password changemin- min number of days before you can change your password,0means can be changed nowmax- max number of days till which your password is valid,9999means will never expirewarning- no of days before expiration to show the password expiration warningdisable- no of days after expiration that the account will be disabled in, nothing means never disableexpire- date when account will expirereserved_field- sample
totoro:$6$g3NynZLzI5A.7UcE$2vSxbUvSasdfsG4:18898:0:99999:7:::totoro- user$6- indicates sha512 encryption$g3NynZLzI5A.7UcE- salt$2vSxbUvSasdfsG4- hash, will be longer, here used as example18898- last date when account was changed0- password can be changed now9999- password will never expire7- expiration warning will appear 7 days before expiration
passwd
- change password for the current user
passwd username- change password for theusername
chage
- change the account expiration date, and other expiration dates mentioned in the
/etc/shadowfile
getent
- get entries from Name Service Switch libraries
- config file in
/etc/nsswitch.conf
usermod
- modify the entires of
/etc/passwdfile - change the home directory, login shell, UID, etc.
finger
- show the description of the user form the
/etc/passwdfile
chfn
- change finger
- changes the description of the user form
/etc/passwdfile
how to force user to change password when the login next time
passwd --expire [uid]sudo chage --lastday 1970-01-01 [uid]sudo chage --lastday 0 [uid]
[uid] user will asked to change their password next time they login.
Lock a user account
usermod -L [uid]- lock, place a!in the password field of the uid in/etc/passwdfileusermod -L [uid]- unlockpasswd -l [uid]chage -E0 [uid]
last
- prints the last time the user logged in the system
deluser
deluser user- delete the userdeluser --remove-home user- delete user and remove the home directory
Groups Management
groupadd
groupadd group_name- create new groupgroup_name
groupdel
groupdel group_name- delete groupgroup_name
groupmod
- modify some group
groupmod --new-name new_group_name group_name- renamegroup_nametonew_group_name
/etc/group file
- contains the information related to the groups on the system
- format -
group_name:password:gid:members
/etc/gshadow
- contains the information regarding the passwords for the groups
- format -
group_name:password:group_administrator:group_members
gpasswd
- add new member to a group
gpasswd -A member_name group_name- add member
member_nameto groupgroup_nameas group administrator -Asignifies group administrator
- add member
usermod -aG group_name user_name-aappend-Ggroup- add user
user_nameto groupgroup_nameas a member
usermod -a group_name user_name- add
group_namegroup to the useuser_name
- add
power of group administrators
Suppose a user is group administrator of group1 then
gpasswd -a user_name group1- adduser_nametogroup1getent group group1- get the details of the groupgroup1gpasswd -d user_name group1- removeuser_namefromgroup1gpasswd group1- set the password for thegroup1
newgrp
- temporarily add a group to your user
newgrp grpname- you will need group password for this
sudo
sudo lets you execute a command as another user, usually root.
- for some user to use
sudoadd that user tosudo(in debian based distros) orwheel(in rel, arch)group. Useusermod -aG sudo usernamefor adding username to sudo group. For this change to take place use must re-login. - or you can do
sudo visudo- under
# User privilege specificationadd you user as %username ALL=(ALL:ALL) ALL- now
usernamecan use sudo without re-logging in.
- under
File Management
Everything is file in linux.
ordinary file- binary/text filedirectory file- contains filename and there inode number-
device file -
pwd- print working directory cd- change directorycd ~- change to the home directorycd -- change to previous directory(used for toggeling)mkdir- make directoryrmdir- remove directory(empty directory)ls- list files- Options and flags:
-xmulticolumnar output-Fmark executables with *, directories with /, symbolic links with @-ashow all files-Rrecursive list-rsort in reverse-llong listing-tsort by last modification time-usort by last access time-idisplay inode numberls -l- time of last file modificationls -lu- time of last accessls -lc- time of last inode modification
mv- moving filesrsync- sync filesrsync -z|--compress -v|--verbose /foo /barCopy directory, overwrites destinationrsync --ignore-existing -a|--archive-a|--archive -z|--compress -v|--verbose /foo /barCopy directory, without overwriting destinationrsync -avz /foo username@hostname:/barCopy local directory to remote directoryrsync -avz username@hostname:/foo /barCopy remote directory to local directory
rm- remove filescp [file] [destination]- copy file to the destination-i- interactive copy(provides warning while overwriring)-R- recursive copy
touch filename- creates a new filetouch [MMDDhhmm] file- modifies the last time of modificationcat [filename]- displays the contents of the file-v [filename]- displays the non-graphical characters also-n [filename]- displays the line number als
ln Hard-links and Soft-links
inode number- the unique number given to a filels -i- show inode number- Making hard links
ln filename new-filename- make hardlink
- Making soft links (symbolic links)
ln -s file new-filename- make softlinks
umask
umask is the number that is subtracted from the default file and directory permissions, to set permission for newly created directory or file. The default permission for directory is 777 and for file is 666. This cannot be changed.
umask- show default umaskumask no- set umask as no
Archiving and compressing
gzip to compress tar to archive and zip to archive and compress
gzip and gnuzip (.gz)
gzip -d [filename]- decompress the filegzip -r [filename]- recursive compressiongzip -l [filename]- list the compression ratio
tar - archival program (.tar file)
-ccreate an archive-xextract the archive-tview the archive-farch - specifies the archive arch-vverbose mode
tar -cvf [archive name] [files to add...]
- now to compress the file use gzip
gzip [archive name]- creates a tar-gzipped filetar -xvf [archive name]- extracts the archivetar -tvf [archive name]- view the archive
- Doing archiving and compression together (-z)
tar -cvzf [compressed archive]- create a compressed archive
zip AND unzip - compressing and archiving together (.zip)
zip [archive name] [input files]- creates an archivezip -r [archive name]- recursive compressingunzip [archive name]- unzips an archiveunzip -v [archive name]- viewing detail about the compressed file
Basic File Attributes
ls -l - long listing files
The columns are as follows:
- File Type and Permissions
- Links - the number of links associated with that particular file
- Ownership - owner of the file
- Group Ownership
- File Size in bytes
- Last Modification Date
- Filename
File Ownership
- The user-id (UID)
- The group-id (GID)
id - view UID and GID associated with particular user
File Permissions (Discretionary Access Control)
|0|1|2|3|4|5|6|7|8|9|
|d|r|w|x|r|w|x|r|w|x|
r- read permissionw- write permission-
x- execute permission -
0- defines the type of file d for directory, - for normal file 1,2,3- permission granted to owner of file4,5,6- permission granted to group owner of file7,8,9- permission granted to other users
chmod - used to change the permissions of the file
chmod [category][operation][permission] [filename...]
- category - u-user, g-group, o-other, a-all(ugo)
- operation - + assign permission, - remove permission, = absolute permission
- permission - r, w, x
chmod [ocatal-code] [filename...] - used to assign absolute permission
a b c
|0| |4 2 1| |4 2 1| |4 2 1|
|d| |r|w|x| |r|w|x| |r|w|x|
octal-code - a three digit code for permission of the file
How directory permission affect the file permissions:
- if the directory has write permission for all than they can delete the files in the directory
Changing file ownership
chown [options] [owner] [files...]- change owner of file to ownerchgrp [group] [files...]- change group of file to groupchmod 777 filethis octal notation don't show all the flags-
chmod 0777 filethis is the actual octal notation -
there are three flags more
- 4 -
setuid-s - 2 -
setgid-s - 1 -
stickybit-t
setuid
setuid- is a permission bit flag
- when
setuidflag is set, it allows user to run an executable with the permission of the file owner
- Do
ls /bin/passwd, you will see the permission as.rwsr-xr-x- that means the
setuidbit is set - and other users can also run this file with the permission of the root user
- that means the
Demonstration
- shell script can't use the
setuid, if you use#!/bin/bashat start of script, bash throws the root power if the effective uid don't match the uid. - here is a c program
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
setuid(0); //sets the uid to that of the root user
system("ls -lh /srv/setuid/private")
return 0;
}
how to setuid
chmod u+s file_name-+sfor the setuid bitchmod 4755 filename-4for the setuid bit
setgid
-
enabling
setgidfor a directory sets the group of all new files created in directory to be the group of the directory -
chmod g+s filename- set thesetgidflag chmod g-s filename- set thesetgidflagchmod 2770 filename- set thesetgidflag,2indicatessetgid
stickybit
- when this bit is set for a directory only the owner of files can remove the files in that directory
- when set for a directory, the file will be not remove from swap for fast startup times (now not used due to fast secondary storage).
chmod 1770 filename- set the sticky bit1indicates the sticky bitchmod +t filename- set the sticky bit
Advance Access Control Extensions
These provide extension on top of the existing DAC or modify them.
ACL - access control list
- should be turned on to be used, some don't even support it
- files with ACL permission turned one show a
+in thels -lh getfacl- get file ACLsetfacl- set file ACL-mindicates modifysetfacl -m g:group_name:permissions files- sets the group permissions for the files
setfacl -Rm g:group_name:permissions directory- sets the permissions recursively to all files inside a directory
setfacl -dm g:group_name:permissions files- sets the default permissions for the directory
- it will apply to the newly created files too
-kremove default ACL permissions-xremove ACL permissions-Rxremove ACL permissions recursively-Rbremove all ACL permissions recursively
Disk Management
dfList disks, size, used and available spacedf -h|--human-readableList disks, size, used and available space in a human readable formatduList current directory, subdirectories and file sizesdu /foo/barList specified directory, subdirectories and file sizesdu -h|--human-readableList current directory, subdirectories and file sizes in a human readable formatdu -d|--max-depthList current directory, subdirectories and file sizes within the max depthdu -d 0List current directory size
Finding Files on System
find
It recursively examines a directory tree to look for files matching some criteria, and then take some action on them.
find [path-list] [selection-criteria-action]
This is how find operates:
- First it recursively examines all files in the directories specified in
path-list - It then matches each file for one more selection criteria
- Finally, it takes some action on those selected files.
The path-list comprised of one or more directories separated by whitespace.
find / -name a.out -print #find a file named a.out in / directory and the print its name
find . -name "*.c" -print #find all c file in current directory and then print its name
Selection Criteria
-inum number- for inode number-type xx - can be f(ordinary file), d(directory file), l(symbolic link)-perm nnn- having permissionnnn-links n- having n links-user uname- owned by user uname-group gname- owned by group gname-size +x[c]- if size is greater than x blocks or more than c characters-mtime -x- if modified less than x days-mewer flname- if modified after flname-mmin -x- if modified in less than x minutes-atime +x- if accessed in more than x days-amin +x- if accessed in more than x minutes-name flname- having name flname-iname flname- having name flname but this is case sensitive-follow- after following a symbolic link-prune- but don't descend directory if matched-mount- but don't look in other file system
Action
-print- print the name of the file-ls- executes ls -lids on the following files-exec cmd {} \- executes linux command cmd
Operators
Used to join two selection criteria or negate the one we have.
!the not operator-othe or operator-athe and operator
Examples
find .. -type f -not \( -name "*Windows*" -o -name "*.md" -o -name "*.txt" -o -name "LICENSE" \)find . -type f -not -path "./.git/*" -a -not -path "./.vscode/*"
locate - locate files
locate find files using indexing
updatedbUpdate the indexlocate foo.txtFind a filelocate --ignore-caseFind a file and ignore caselocate f*.txtFind a text file starting with 'f'
Network Management
HTTP request
curl https://example.comReturn response bodycurl -i|--include https://example.comInclude status code and HTTP headerscurl -L|--location https://example.comFollow redirectscurl -O|--remote-name foo.txt https://example.comOutput to a text filecurl -H|--header "User-Agent: Foo" https://example.comAdd a HTTP headercurl -X|--request POST -H "Content-Type: application/json" -d|--data '{"foo":"bar"}' https://example.comPOST JSON-
curl -X POST -H --data-urlencode foo="bar" http://example.comPOST URL Form Encoded -
wget <https://example.com/file.txt>Download a file to the current directory wget -O|--output-document foo.txt <https://example.com/file.txt>Output to a file with the specified name
Network Troubleshooting
ping example.comSend multiple ping requests using the ICMP protocol-
ping -c 10 -i 5 example.comMake 10 attempts, 5 seconds apart -
ip addrList IP addresses on the system -
ip route showShow IP addresses to router -
curl ifconfig.meObtain external IP address -
netstat -i|--interfacesList all network interfaces and in/out usage -
netstat -l|--listeningList all open ports -
traceroute example.comList all servers the network traffic goes through -
mtr -w|--report-wide example.comContinually list all servers the network traffic goes through -
mtr -r|--report -w|--report-wide -c|--report-cycles 100 example.comOutput a report that lists network traffic 100 times -
nmap 0.0.0.0Scan for the 1000 most common open ports on localhost nmap 0.0.0.0 -p1-65535Scan for open ports on localhost between 1 and 65535nmap 192.168.4.3Scan for the 1000 most common open ports on a remote IP addressnmap -sP 192.168.1.1/24Discover all machines on the network by ping'ing them
DNS
dig example.comShow query information of a domain A recordsdig -4 example.comShow IPv4 A informationdig -6 example.comShow IPv6 AAA informationdig example.com @nameserverShow query of a specific nameserver-
dig example.com -p 123Show query of a specific port number -
cat /etc/resolv.confresolv.conflists nameservers
Process Management
Every process have
- PID - process-id
- PPID - parent process id
The shell process:
$$- current shell PID
ps - process status
ps- process statusps -fFull listing showing PPID of each processps [-e|-A]All processes including user and system processesps -uusr Processes of user usr onlyps -aProcesses of all users excluding processes not associated with terminalps -lLong listing showing memory related informationps -tterm Processes running on terminal
Mechanism of process creation
fork- system call fork is called to fork current process. PID changed.exec- the memory image is overwritten with new program.wait- the parent executed wait system call for the child process to complete.
If the parent process dies earlier then the child process is called orphan. They are the adopted by init and killed. Processes whose parent don't wait for their death moves to zombies state. It remains in this state until there parent picks up there exit code. Deamons are the process who don't have a controlling terminal. Usually are system processes.
Types of commands
- External commands -
cat,ls - Shell scripts
- Internal commands -
cd,echo- can change the directory
Running jobs in background
&- using the&symbol at the end of a command. The process runs in the background.
e.g. sort emp.list &
nohup- no hangup - command to detach a process from a terminal
e.g. nohup sort emp.list &
Job execution with low priority
nice command- runs a job at low prioritynice -n [level] command- increase the priority of the command by level which can be between 1 to 19.
Killing process with signals
kill PID- kills a processkill -s [Signal] PID- send the signal to the process- Signal can be as folows:
KILLkill -l- list all the signals
Job Control
A job is the name given to a group of processes.
Easiest way to create a job is by using pipeline of two or more commands.
bg- relegate a job to the backgroundfg- bring it back to the foregroundjobs- list the active jobsCtrl+z- suspend a foreground jobkill- kill a job
Use
- suspend the job - use
Ctrl+z - use
bgto send it to background - now your job is running in the background
- list the jobs using
jobs - to bring a job to foreground use the
fgcommand
fg
fg %- brings first job to foregroundfg %sort- brings sort job to foregroundbg %?perm- send to the background job containing stringperm-
bg %2- sends second job to background -
stty -a- see the current terminal configstart = ^q; stop = ^s; susp = ^z; dsusp = ^y;
-
lsof- List all open files and the process using them -
lsof -itcp:4000- Return the process listening on port 4000 -
jobsList all background jobs jobs -pList all background jobs with their PID
Process priority
nice -n -20 fooChange process priority by namerenice 20 PIDChange process priority by PIDps -o ni PIDReturn the process priority of PID
Stopping Processes
CTRL+CKill a process running in the foregroundkill PIDShut down process by PID gracefully. Sends TERM signal.kill -9 PIDForce shut down of process by PID. SendsSIGKILLsignal.pkill fooShut down process by name gracefully. Sends TERM signal.pkill -9 fooforce shut down process by name. SendsSIGKILLsignal.killall fooKill all process with the specified name gracefully.
Scheduling Tasks
| * | * | * | * | * |
|---|---|---|---|---|
| Minute | Hour | Day of month | Month | Day of the week |
crontab -lList cron tabcrontab -eEdit cron tab in Vimcrontab /path/crontabLoad cron tab from a file-
crontab -l > /path/crontabSave cron tab to a file -
* * * * * fooRun foo every minute */15 * * * * fooRun foo every 15 minutes0 * * * * fooRun foo every hour15 6 * * * fooRun foo daily at 6:15 AM44 4 * * 5 fooRun foo every Friday at 4:44 AM0 0 1 * * fooRun foo at midnight on the first of the month-
0 0 1 1 * fooRun foo at midnight on the first of the year -
at -lList scheduled tasks at -c 1Show task with ID 1at -r 1Remove task with ID 1at now + 2 minutesCreate a task in Vim to execute in 2 minutesat 12:34 PM next monthCreate a task in Vim to execute at 12:34 PM next monthat tomorrowCreate a task in Vim to execute tomorrow
Date Time Language Management
cal [ [month] year]- print the calender of the giver year and monthdate- displays current date-
date +[symbol]- display the current date particular part given by the symbol[d - day] [y - year] [H,M,S - hour, minute, second] [D - date] [T - time] -
timedatectl list-timezones- list time zones sudo timedatectl set-timezone Australia/Sydneyselect a time zonelocalelocale -alocale -all
Device Management
lsusb- List USB deviceslspci- List PCI hardwarelshw- List all hardwarelsmod- list loaded kernel modules
libinput
libinputlibinput-gestures -dlibinput-gestures-setup desktoplibinput-gestures-setup servicelibinput-gestures-setup startlibinput-gestures-setup stop-
libinput list-devices -
xinput xinput listxinput list-propsxinput list-props "MSFT0001:01 06CB:CD5F Touchpad"xinput list-props "MSFT0001:01 06CB:CD5F Touchpad"xinput list-props "MSFT0001:01 06CB:CD5F Touchpad" | grep Capxinput set-prop "MSFT0001:01 06CB:CD5F Touchpad" 325 1xinput set-props "MSFT0001:01 06CB:CD5F Touchpad" 325 1
Other General Purpose Utilities
xargs
- better than
xargswhen running some commands for many files - do
man xargsfor help
some uses
convert all files from one extension to another using some other tool
ls -1 | sed -e 's/\.mkv//' | xargs -I _ ffmpeg -i _.mkv _.mp4
ls -1prints the files in a folder in one columnsed -e 's/\.mkv//'remove the extension.mkvfrom the file namexargs -I _ ffmpeg -i _.mkv _.mp4converts the file to amp4file voila!
gnome desktop environment hiding some useless collection of files
find /usr -name "*lsp_plug*desktop" 2>/dev/null | cut -f 5 -d '/' | xargs -I {} cp /tmp/1 ~/.local/share/applications/{}
find /usr -name "*lsp_plug*desktop" 2>/dev/nullprints the name of all.desktopfiles containing*lsp_plug*,2>/dev/nullignores any errorscut -f 5 -d '/'prints the name of files,-dsets the delimiter-fselects the fieldxargs -I {} cp /tmp/1 ~/.local/share/applications/{}copies the contents of file/temp/1but uses the manes we generated.
fold
Wrap the text to certain length
fold -w 66 -s file.tex