Linux Commands

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 75

Cybersoc International- Linux Commands & File

system

11-06-2021
Table of Contents…

• Module 1- Introduction to Linux


• Module 2 – Linux file system concepts
• Module 3 - Linux File commands
• Module 4 - File Permission / Access
• Module 5 – DNS Commands
• Module 6 - Linux Troubleshooting commands

3
Module 1

4
What is Linux ?
 Linux is clone of UNIX
 The Linux OS was developed by Linus Torvalds in 1991
 Linux is an open-source operating system .It is reliable and secure then others also it is
completely open source.
 Multi-user, Multitasking, Multiprocessor
− One person can be logged on to the same Linux computer at the same time.
− The same user could even be logged into their account from two or more terminals at the
same time.
− A user can have more than one process (program) executing at the same time.

5
Why use Linux?
Linux is a perfect operating system if you want to get rid of viruses, malware, slowdowns, crashes, costly
repairs, and many more. Further, it provides various advantages over other operating systems, and we don't
have to pay for it.

6
Linux Distributions
Free Distributions
− Fedora Core
− Debian and Ubuntu
− Gentoo
− Slackware
− Knoppix
− centOS
− Many, many more

Commercial Distributions
− Red Hat Enterprise
− Suse
− Yellow Dog
7
Linux Architecture
Linux, like other OS has three parts
− Kernel
− Shell
− Users and Application

8
Kernel
− Kernel is heart of the operating system.
− Linux kernel is loaded first when the system is booted. It handles
allocation of devices, CPU, memory etc.

Shell
− The shell acts as an interface between the user and the kernel

Users & Applications


− This part of Linux operating system allows the user to interact
with the hardware (through shell and kernel) and run programs,
tools, application and perform input/output activities

9
Module 1

10
Linux File System Concept

11
1. / – Root
Every single file and directory starts from the root directory.
Only root user has write privilege under this directory.
Please note that /root is root user’s home directory, which is not same as /.

2. /bin – User Binaries


Contains binary executables.
Common linux commands you need to use in single-user modes are located under this directory.
Commands used by all the users of the system are located here.
For example: ls, cat, grep, cp.

3./sbin – System Binaries


Just like /bin, /sbin also contains binary executables.
But, the linux commands located under this directory are used typically by system aministrator,
for system maintenance purpose.
For example: reboot, fdisk, ifconfig

12
4. /etc – Configuration Files
Contains configuration files required by all programs.
This also contains startup and shutdown shell scripts used to start/stop individual
programs.
For example: /etc/resolv.conf.

5. /dev – Device Files


Contains device files.
These include terminal devices, usb, or any device attached to the system.
For example: /dev/tty1, /dev/usbmon0

6. /proc – Process Information


Contains information about system process.
This is a filesystem contains information about running process.
For example: /proc/{pid} directory contains information about the process with that
particular pid.
13
7. /var – Variable Files
var stands for variable files.
Content of the files that are expected to grow can be found under this
directory.
This includes — system log files (/var/log); packages and database files
(/var/lib); emails (/var/mail); temp files needed across reboots (/var/tmp);
8. /tmp – Temporary Files
Directory that contains temporary files created by system and users.
Files under this directory are deleted when system is rebooted.
9. /usr – User Programs
Contains binaries, libraries, documentation, and source-code for second
level programs.
/usr/bin contains binary files for user programs.
If you can’t find a user binary under /bin, look under /usr/bin.
For example: at, awk, cc, less, scp
14
10. /home – Home Directories
Home directories for all users to store their personal files.
For example: /home/john, /home/nikita

11. /boot – Boot Loader Files


Contains boot loader related files.
Kernel initrd, vmlinux, grub files are located under /boot
For example: initrd.img-2.6.32-24-generic, vmlinuz-2.6.32-24-generic

12. /lib – System Libraries


Contains library files that supports the binaries located under /bin and /sbin
Library filenames are either ld* or lib*.so.*

15
Module 1

16
Pwd
Current working directory
-The current working directory is the directory in which you are currently working

Cal
• cal command : Display a calendar
• cal without any parameter will display calendar for the current month and year.
• cal –y 2021 will display complete calendar for the year 2021
• cal 9 2021 will display calendar for September 2021

17
Date Command
• Print the current system date and time.

The output displays the day of the week, day of the month, month, year, current time, and time zone.
By default, the date command is set to the time zone of the operating system

Linux date Command Format Options


To format the date command’s output, you can use control characters preceded by a + sign. Format
controls begin with the % symbol and are substituted by their current values.

18
Linux File Commands

Module 1

19
Ls Command(List Files and Directories)

The ls command is used to view the contents of a directory. By default, this command will display the
contents of your current working directory.

1. List Files using ls with no option

ls with no option list files and directories in bare format where we won’t be able to view details like file types, size,
modified date and time, permission and links etc

20
2. List Files With option –l

ls -l (-l is character not one) shows file or directory, size, modified date and time, file or folder name and owner of
file and its permission.

When the long listing format is used, you can see the following file information:
•The file type.
•The file permissions.
•Number of hard links to the file.
•File owner.
•File group.
•File size.
•Date and Time.
•File name

21
3. View Hidden Files
By default, the ls command will not show hidden files. In Linux, a hidden file is any file that begins with a dot (.)
To display all files including the hidden files use the -a option

 4. Shows version of ls command


Check version of ls command.

22
5. List Files with Human Readable Format with option –lh
With combination of -lh option, shows sizes in human readable format.

23
Create and removing files :
1)touch command :
The touch command is used to create a blank new file, change and modify timestamps
of a file

Touch command Syntax to create a new file: You can create a single file at a time
using touch command.

Syntax:
touch file_name

Touch command to create multiple files: Touch command can be used to create the
multiple numbers of files at the same time. These files would be empty while creation.

Syntax:
touch File1_name File2_name File3_name

24
Touch command have various options. These options are very useful for various purpose.

1)touch -a: This command is used to change access time only. To change or update the last access or modification times of
a file touch -a command is used
Syntax: touch -a filename

2)touch -c : This command is used to check whether a file is created or not. If not created then don’t create it. This
command avoids creating files.
Syntax: touch -c filename

3)touch -m : This is used to change the modification time only. It only updates last modification time.
Syntax: touch -m filename

4)touch -t : This is used to create a file using a specified time.


Syntax: touch -t YYMMDDHHMM fileName

25
2) Cat command
cat (short for concatenate) is one of the most frequently used commands in Linux. cat command
allows us to create single or multiple files, view contain of file, concatenate files.To run this
command, type cat followed by the file’s name and its extension

Syntax: cat file.txt.


Here are other ways to use the cat command:

• cat > filename (creates a new file)


• cat filename1 filename2>filename3 joins two files (1 and 2) and stores the output of them in
a new file (3)

26
Cat command have various options. These options are very useful for various
purpose.

1) View Contents of Multiple Files in terminal: it will display contents of test and test1 file in terminal.
Syntax: cat test test1

2)Create a File with Cat Command: We will create a file called test2 file with below command.
Syntax: cat >test2
user, type desired text and press CTRL+D (hold down Ctrl Key and type ‘d‘) to exit. The text will be written in
test2 file

3) Use Standard Output with Redirection Operator: We can redirect standard output of a file into a new file
else existing file with ‘>‘ (greater than) symbol. Careful, existing contents of test1 will be overwritten by contents
of test file
Syntax: cat test > test1

4) Appending Standard Output with Redirection Operator: Appends in existing file with ‘>>‘ (double greater
than) symbol. Here, contents of test file will be appended at the end of test1 file.
Syntax: cat test >> test1
27
Copying Files & Directories with the cp Command
 cp command used to copy files from the current directory to a different directory
Syntax: cp [options] source-name destination

* copy a file in the current working directory. For example, to copy a file named file.txt to a file named
file_backup.txt
1) cp file.txt file_backup.txt
2) If the destination file exists, it will be overwritten. To get a confirmation prompt before overwriting the files,
use the -i option
3) cp -i file.txt file_backup.txt

Copy a file to a directory


4) To copy a file to a directory, specify the absolute or the relative path to the directory. When the destination
directory is omitted, the file is copied to the current directory.
In the following example, we are copying the file file.txt to the /backup directory:
cp file.txt /backup

28
• If you want to copy the file under a different name, you need to specify the desired file name. The command
below will copy the file to the specified directory as new_file.txt

cp file.txt /backup/new_file.txt

Copy multiple files


• To copy multiple files and directories at once, specify the names of source files and directories followed
with the destination directory as the last argument:

cp file.txt dir file1.txt file2.txt dir1

When copying multiple files, the destination must be a directory.

• The cp command also allows you to use pattern matching. For example, to copy all .png files from the
current directory to the /backup directory, you would use:

cp *.png /backup

29
Removing files

 To remove (or delete) a file in Linux from the command line, use either the rm (remove) or
unlink command
 The unlink command allows you to remove only a single file, while with rm you can remove
multiple files at once
1)To delete a single file, use the rm or unlink command followed by the file name:
Syntax: unlink filename
Syntax: rm filename
2)To delete multiple files at once, use the rm command followed by the file names separated by
space.
Syntax: rm filename1 filename2 filename3

You can also use a wildcard (*) and regular expansions to match multiple files. For example, to
remove all .pdf files in the current directory, use the following command
Syntax: rm *.pdf
3)Use the rm with the -i option to confirm each file before deleting it:
Syntax: rm -i filename(s)
30
:

Creating Directories (Folders) :

1)To create a directory in Linux pass the name of the directory as the argument to the
mkdir command.
- For example, to create a new directory newdir you would run the following command:

Syntax: mkdir newdir

2)To create multiple directories, specify the directories' names as the command arguments, separated
by space:
Syntax :mkdir dir1 dir2 dir3

31
 Remove Directories (Folders)
To remove/delete directories in Linux using the rmdir and rm

1 .Removing Directories with rmdir


• rmdir is a command for deleting empty directories. It is useful when you want to delete a directory only if it is empty,
without needing to check whether the directory is empty or not
rmdir dir1
• If the directory is not empty, you will get the following error:
rmdir: failed to remove 'dir1': No such file or directory

• In this case, you will need to use the rm command or manually remove the directory contents before you can delete it

2 .Removing Directories with rm


• rm is a command-line utility for deleting files and directories. rm command can delete both empty and non-empty
directories
• By default, when used without any option rm does not remove directories. To delete an empty directory, use the -d
(--dir) option and to delete a non-empty directory, and all of its contents use the -r (--recursive or -R) option

For example to delete a directory named dir1 along with all of its contents

rm -r dir1
32
• if a directory or a file within the directory is write-protected, you will be prompted to confirm the
deletion. To remove a directory without being prompted, use the -f option:

rm -rf dir1
• To remove multiple directories at once, invoke the rm command, followed by the names of the
directories separated by space. The command below will remove each listed directory and their
contents:
rm -r dir1 dir2 dir3
• The -i option tells rm to prompt you to confirm the deletion of each subdirectory and file. If the
directory contains a lot of files, this can be a little annoying, so you may consider using the -I option
what will prompt you only once before proceeding with the deletion.
rm -rI dir1
To remove the directory type y and hit Enter
rm: remove 1 argument recursively? Y

33
Move and rename Files and Directories in Linux (mv Command)

The mv command (short from move) is used to rename and move and files and directories from one
location to another.
mv [OPTIONS] SOURCE DESTINATION

The SOURCE can be one, or more files or directories, and DESTINATION can be a single file or directory.

• When multiple files or directories are given as a SOURCE, the DESTINATION must be a directory. In this case,
the SOURCE files are moved to the target directory.
• If you specify a single file as SOURCE, and the DESTINATION target is an existing directory, then the file is moved to the
specified directory.
• If you specify a single file as SOURCE, and a single file as DESTINATION target then you’re renaming the file .
• When the SOURCE is a directory and DESTINATION doesn’t exist, SOURCE will be renamed to DESTINATION.
Otherwise, if DESTINATION exist, it be moved inside the DESTINATION directory.

Note : To move a file or directory, you need to have write permissions on both SOURCE and DESTINATION. Otherwise, you will receive a
permission denied error.

34
Determining file content
file command can be used to check file type

Counting Words in a File

You can use the wc command to get a count of the total number of lines, words, and characters
contained in a file.
Here is the detail of all the four columns −
First Column − Represents the total number of lines in the
file.
Second Column − Represents the total number of words in
the file.
Third Column − Represents the total number of bytes in the
file. This is the actual size of the file.
36
Fourth Column − Represents the file name
Grep Command

• Grep is an acronym that stands for Global Regular Expression Print.


• Grep is a Linux command-line tool used to search for a string of characters in a
specified file.
• The text search pattern is called a regular expression. When it finds a match, it
prints the line with the result. The grep command is handy when searching
through large log files.

Using the grep Command

The grep command consists of three parts in its most basic form. The first
part starts with grep, followed by the pattern that you are searching for.
After the string comes the file name that the grep searches through.

37
The simplest grep command syntax looks like this:

To Search a File
To print any line from a file that contains a specific pattern of characters, in our case phoenix in the
file sample2, run the command

Syntax: grep phoenix sample2

38
Grep will display every line where there is a match for the word phoenix. When executing this
command, you do not get exact matches. Instead, the terminal prints the lines with words
containing the string of characters you entered. Here is an example

39
To Search Multiple Files
To search multiple files with the grep command, insert the filenames you want to search, separated
with a space character.
In our case, the grep command to match the word phoenix in three files sample,sample2, and
sample3 looks like this example:

Syntax: grep phoenix sample sample2 sample3

The terminal prints the name of every file that contains the matching lines, and the actual lines that include the
required string of characters

40
Vim Editor with Commands

The VIM editor is the most popular and classic text editor in the Linux family.

Below, are some reasons which make it a widely used editor –

1) It is available in almost all Linux Distributions


2) It works the same across different platforms and Distributions
3) It is user-friendly. Hence, millions of Linux users love it and use it for their editing needs.

The vim editor has two modes:

Command Mode: In command mode, actions are taken on the file. The vim editor starts in command
mode. Here, the typed words will act as commands in vim editor.
To pass a command, you need to be in command mode.

Insert Mode: In insert mode, entered text will be inserted into the file.
The Esc key will take you to the command mode from insert mode.
41
vim Command mode:
• The vim editor opens in this mode, and it only understands commands
• In this mode, you can, move the cursor and cut, copy, paste the text
• This mode also saves the changes you have made to the file
• By default vim, opens in command mode.

vim Editor Insert mode:


• This mode is for inserting text in the file.
• You can switch to the Insert mode from the command mode  by pressing 'i' on the keyboard
• Once you are in Insert mode, any key would be taken as an input for the file on which you are
currently working.
• To return to the command mode and save the changes you have made you need to press the Esc key

How to use vim editor


To launch the VIM Editor -Open the Terminal (CLI) and type
Syntax: vim <filename_NEW> or <filename_EXISTING>
And if you specify an existing file, then the editor would open it for you to edit. Else, you can create a new file

42
43
44
dw - Delete word
4dw - Delete 4 words
cw - Change word
x - Delete character at the cursor
r - Replace character
R - Overwrite characters from cursor onward
s - Substitute one character under cursor continue to insert
S - Substitute entire line and begin to insert at the beginning of the line

Note: You should be in the "command mode" to execute these commands. VI


editor is case-sensitive so make sure you type the commands in the right letter-
case.

46
Moving within a file

•k - Move cursor up
•j - Move cursor down
•h - Move cursor left
•l - Move cursor right

 You need to be in the command mode to move within a file. The default keys for navigation are
mentioned below else; You can also use the arrow keys on the keyboard.

Saving and Closing the file


Shift+zz - Save the file and quit
:w - Save the file but keep it open
:q - Quit without saving
:wq - Save the file and quit

 You should be in the command mode to exit the editor and save changes to the file
47
File Permission / Access Mode

Module 1

48
File Permission / Access Modes

Permissions that are set are called read, write and execute permissions.
Every file and directory has permissions set that determine who can access it.
Permission are set for:

 The owner of the file.


The owner's permissions determine what actions the owner of the file can perform on the
file
 The group members
 The group's permissions determine what actions a user, who is a member of the group that a
file belongs to, can perform on the file.
 All other
 The permissions for others indicate what action all other users can perform on the file.
49
What is
Permission ?

50
The Permission Indicators
Using ls -l command, it displays various information related to file permission as follows −

The permissions are broken into groups of threes, and each position in the group denotes a specific
permission, in this order: read (r), write (w), execute (x) −

• The first three characters (2-4) represent the permissions for the file's owner. For example, -rwxr-
xr-- represents that the owner has read (r), write (w) and execute (x) permission

• The second group of three characters (5-7) consists of the permissions for the group to which the
file belongs. For example, -rwxr-xr-- represents that the group has read (r) and execute (x)
permission, but no write permission

• The last group of three characters (8-10) represents the permissions for everyone else. For
example, -rwxr-xr-- represents that there is read (r) only permission
51
Methods of Implementing
Permissions
• Symbolic Method
• Numeric Method
Permissions- Symbolic Method
 Four symbols are used when displaying and applying permissions :
− r Permission to read a file or list a directory’s contents
− w Permission to write to a file or create and remove files from a directory
− x Permission to execute a program or change into a directory and do a long
listing of the directory
− - no permission ( in place of the r, w, or x )

52
Applying Permission with Symbolic Method

Symbolic Method

− chmod u+w, file name


( Grants write access to User. )

− chmod u=rw somefile ←file name


( Sets read and write permission to owner, with execute turned off, regardless of the current permission )

53
Permissions- Numeric
Method
Four numbers are used when displaying or applying permissions
• 4 Permission to read a file or list a directory’s contents
• 2 Permission to write to a file or create and remove files from a directory
• 1 Permission to execute a program or change into a directory and do a long listing of the directory
0 no permission ( in place of the 4, 2, or 1 )
Applying Permission with Numeric Method
• chmod command is used to change access modes
• Numeric Method

− chmod 664 somefile file name


( Grants Read and Write access to owner and group but read only it to and other. )
− chmod 600 somefile file name
( Sets read and write permission to owner, with execute turned off, with others and group have no
permissions )
− chmod 444 somefile file name
( Make the file world-readable )
54
DNS Commands
Module 1

55
DNS records
• DNS stands for Domain Name System or Domain Name Servers which translates Internet domain and
host names to IP addresses and vice versa

Domain DNS information can be verified from the Linux terminal using the following three commands.

• dig Command
• nslookup Command
• host Command

1) Verify a domain’s DNS records using the dig command:

dig Command: The dig command in Linux is used to gather DNS information.
It stands for Domain Information Groper, and it collects data about Domain Name Servers.
The dig command is helpful for diagnosing DNS problems, but is also used to display DNS information

56
• The first line displays the version of the dig command
• The HEADER section shows the information it received from the server. Flags refer to the answer
format
• The OPT PSEUDOSECTION displays advanced data:

EDNS – Extension system for DNS, if used


Flags – blank because no flags were specified
UDP – UDP packet size
57
 The QUESTION section displays the query data that was sent:

• First column is the domain name queried


• Second column is the type (IN = Internet) of query
• Third column specifies the record (A = Address), unless otherwise specified

 The most important section is the ANSWER section:

• The first column lists the name of the server that was queried
• The second column is the Time to Live, a set timeframe after which the record is refreshed
• The third column shows the class of query – in this case, “IN” stands for Internet
• The fourth column displays the type of query – in this case, “A” stands for an A (address) record
•  The final column displays the IP address associated with the domain name

 The STATISTICS section shows metadata about the query:


Query time – The amount of time it took for a response
SERVER – The IP address and port of the responding DNS server. You may notice a loopback address in this line
– this refers to a local setting that translates DNS addresses
WHEN – Timestamp when the command was run
MSG SIZE rcvd – The size of the reply from the DNS server

58
Other DIG commands:

• ANY Option
To return all of the results of the query, use the following:

dig google.com ANY

The system will list all google.com DNS records that it finds, along with the IP addresses

• Detailed Answer Option


Run +noall +answer with the dig command to access detailed information in the answers section :

dig google.com +noall +answer

• Reverse DNS Lookup

To look up a domain name by its IP address, type the following :

dig –x 172.217.14.238

59
MX ( mail exchange ) records using dig command on Linux
To retrieve domain MX records simply use MX option in combination to domain name
you wish to query. For example, the below command will query MX records for
google.com

60
The +short option to retrieve only mail exchange (MX) records:

2) Checking DNS records of a domain using nslookup command

nslookup command is a program to query Internet domain name servers. Nslookup has two
modes interactive and non-interactive.

• Interactive mode allows the user to query name servers for information about various hosts and
domains or to print a list of hosts in a domain.
• Non-interactive mode is used to print just the name and requested information for a host or
domain
61
1. How to find the A record of а domain
This command is used to see how many A records are there and see the IP Addresses of each one.

2. How to check the NS records of a domain.


By checking the NS records, you can see which is the authoritative server for a specific domain.

62
3)How to find the MX records responsible for the email exchange.
we are checking the MX records of the mail servers. here we can see if all the mail servers are working well.

4)How to check the Reverse DNS Lookup.


Many times, you check the A records to see the IPs of a domain, but sometimes you need to verify if an IP
address is related to a specific domain. For that purpose, we need a reverse DNS lookup.

63
3) How to check DNS records of a domain using host command
host command is a simple utility for performing DNS lookup. It is normally used to convert names to IP
addresses and vice versa

1)To find out the IP address of google.com

2)To find out the hostname of the host with the IP address

64
3)To display MX records for google.com domain

$ host -n -t mx google.com

65
Linux Troubleshooting
commands
Module 1

66
System Health commands:
W

w is a command-line utility that displays information about currently logged in users and what each
user is doing. It also gives information about how long the system has been running, the current time,
and the system load average.

OUTPUT:

67
iostat stands for input-output statistics and often used to diagnose a performance issue with
storage devices. it is used to monitor CPU, Device & Network file system utilization report with
iostat.

Display disk I/O statistics

Display CPU statistics

68
free

If your Linux server is running out of memory or just want to find out how much memory available out of
available memory, then the free command will help you.

-g means to show the details in GB

69
Sar (System Activity Report) will be helpful to collect a number of a report including CPU, Memory,
and device load
-By executing sar command will show you system utilization for the entire day.

70
Top
command
top command is used to show the Linux processes. It provides a dynamic real-time view of the
running system. Usually, this command shows the summary information of the system and the list
of processes or threads which are currently managed by the Linux Kernel

The Default Display

The default display contains two areas of information: the summary area (or dashboard), and the
task area (or process list). By default, top updates its display every three seconds

71
OUTPUT:

72
The first line of numbers on the dashboard includes the time, how long your computer has been running, the
number of people logged in, and what the load average has been for the past one, five, and 15 minutes.

The second line shows the number of tasks and their states: running, stopped, sleeping, or Zombie

The third line displays the following central processing unit (CPU) values:


us: Amount of time the CPU spends executing processes for people in “user space.”
sy: Amount of time spent running system “kernel space” processes.
ni: Amount of time spent executing processes with a manually set nice value.
id: Amount of CPU idle time.
wa: Amount of time the CPU spends waiting for I/O to complete.
hi: Amount of time spent servicing hardware interrupts.
si: Amount of time spent servicing software interrupts.
st: Amount of time lost due to running virtual machines (“steal time”).

The fourth line shows the total amount (in kibibytes) ) of physical memory, and how much is free, used, and
buffered or cached

The fifth line shows the total amount (also in kibibytes) of swap memory, and how much is free, used, and
available.
73
The column headings in the process list are as follows:

• PID: Shows task’s unique process id.


• PR: Stands for priority of the task.
• SHR: Represents the amount of shared memory used by a task.
• VIRT: Total virtual memory used by the task.
• USER: Username of owner of task.
• %CPU: Represents the CPU usage.
• TIME+: CPU Time, the same as ‘TIME’, but reflecting more granularity through hundredths of a second.
• SHR: Represents the Shared Memory size (kb) used by a task.
• NI: Represents a Nice Value of task. A Negative nice value implies higher priority, and positive Nice value
means lower priority.
• %MEM: Shows the Memory usage of task
• TIME+: Total CPU time used by the task in hundredths of a second.
• COMMAND: The command name or command line (name + options).

74
To display process details for specific user

# top –u username

The status of the process can be one of the following:

• D: Uninterruptible sleep
• R: Running
• S: Sleeping
• T: Traced (stopped)
• Z: Zombie

Press Q to exit top.

75
References…
• https://www.tutorialspoint.com
• https://www.guru99.com/unix-linux-tutorial.html
• https://www.javatpoint.com/linux-tutorial

76
77

You might also like