Linux Network Administration Chapter 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

HND2

Network and Security

Linux Network Administration: NWS


TUTORIAL 1

Lecturer : Mavel TATKEU Email : [email protected]

Page 1 / 42
Linux: working with shell

Linux provides a large number of command line utilities for managing the complete operating system.
I- Files
In Linux and other UNIX-like operating systems is that “everything is a file”. It means you can see most of the
things under file systems. You can see some files represents network device, disk, hardware devices etc.
These are known as special files.

1) File Types in Linux:

Basically, there are three types of files. The first character in file permissions under ls -l commands shows
the type of file. See the below screenshot and find the type of file matching with table given below the image.

File Type Details

Regular file (-) Text files, image files, executable files


Directory file (d) Simple directory or folder contained files
Special files-
Block file (b)
Character device file (c)
Special files used by system.
Named pipe file (p)
Symbolic link file (l)
Socket file (s)
2) Linux ls command

The ls command is used to list files and directories in filesystem. Login to your Linux system and open shell.
Syntax
$ ls [OPTION] [FILE]

Page 2 / 42
Examples
Now type ls and press enter. This will show file names available in the current directory.
$ ls

a) Long Listing Files


You can use -l switch to view the long listing of files.
$ ls -l

You can also specify the filename to get details for a specific file.
ls -l myfile.txt
b) List Hidden Files
You can also use the -a switch with ls command to show hidden files as well.
ls -la
c) Show Human Readable File Size
Use -h switch to show the file size in human readable format. For example 10K, 12M, 2G
ls -lh
d) Show Inode Number
Use -i switch to show inode numbers of files.
ls -li
e) Recursively List Files
Use -R switch to list files in current directory and its subdirectories recursively.
ls -lR
3) Linux touch command
Linux touch command is used to create empty files or change time stamp for existing files.
Syntax:
$ touch
Example:
For this example, first, check the number of files available in the current directory. I have one file in our
directory as below
$ ls -l

-rw-r--r-- 1 root root 656 Dec 28 2015 testfile.doc


Check the modification date of existing file and create a new file myfile.txt using touch command. Also, try
touch command with the existing file.
$ touch myfile.txt
$ touch testfile.doc

Page 3 / 42
Again list the files in current directory. You can see a new empty file created and existing file modification
time is changed to current date/time.
$ ls -l

-rw-r--r-- 1 root root 0 Sep 5 14:37 myfile.txt


-rwxr-xr-x 1 root root 104 Sep 5 14:38 testfile.doc

4) Linux cat command


Linux cat command is used to display file content. You can also use this to create new files or copy file
contents to other files.
Syntax:
$ cat file_name
Examples:
a) Display File Content
For example use the following command to list content of /etc/passwd file.
$ cat /etc/passwd
Output:
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin

b) Display Multiple File Content
You can also display the multiple file content in single command.
$ cat /etc/passwd /etc/group
c) Display Line Numbers
Use -n switch to display the line numbers with results of cat command.
$ cat -n /etc/passwd
d) Create New File
You can also create create files with cat command. Type command line below (change filename as per yours)
$ cat > myfile
Write your content here
and here
[CTRL+C] to exit
e) Redirect file content to other file
You can use redirect operator with cat command to copy file content to other other.
Page 4 / 42
$ cat sourcefile > otherfile
You can also copy multiple file content to other file.
$ cat sourcefile1 sourcefile2 sourcefile3 > otherfile

5) Linux mkdir command


The mkdir command used for creating new directories (also known as folder) on Unix/Linux systems. This is
basic Linux command for creating the directory structure on a filesystem.
Syntax:
mkdir [OPTIONS] dir_name
Example
Let’s create a directory named testdir in the current directory. Run below from the command line.
mkdir testdir

The directory is created now. Use ls command to see the created directory.
Now create another directory inside some other directory by specifying the full path.
mkdir /var/www/testdir
In case any parent directory doesn’t exist, the above command will fail. You can use -p option to create

any parent directory if not exists.


mkdir -p /var/www/testdir
You can also specify the permission for the directory with mkdir command during the creation.
mkdir -m 777 testdir
mkdir -m 755 testdir
mkdir -m a=rwx testdir
mkdir -m u=rwx,g=rw,o=r testdir
More Examples
Here are some more examples of mkdir command, which is useful for creating the directory structure.
Create two directories under /tmp directory in single command
mkdir -p /tmp/test1 /tmp/test
Now try the below command. This will do the same as above command do.
mkdir -p /tmp/{test1,test2}

6) Linux systemctl command


The systemctl command is a new tool to control the systemd system and service. This is the replacement of
old SysV init system management. Most of modern Linux operating systems are using this new tool. If you
are working with CentOS 7, Ubuntu 16.04 or later or Debian 9 system. They have opted systemd now.
Syntax
systemctl [OPTION] [SERVICE]

Page 5 / 42
For this tutorial, All commands are written to show the service management of mysql service on Linux
system. Where you can use mysql or mysql.service as a service name.
a) Start and Stop Service
Use these options to start and stop any service using systemctl.
sudo systemctl start mysql.service
sudo systemctl stop mysql.service
 Start: To start stopped service
 Restart: To stop running service
b) Restart or Reload Service
Use this to reload or restart any service. It also provides reload-or-restart to restart service if reload is not
available for any service.
sudo systemctl reload mysql.service

sudo systemctl restart mysql.service

sudo systemctl reload-or-restart mysql.service


 Reload: Used to reload configuration of a running service
 Restart: Used to restart (Stop/Start) a running service
 reload-or-restart: Used to reload a service default, but if reload is not available for that service. It will restart it
c) Status of Service
Use this to check the status of any service.
sudo systemctl status mysql.service
 Status: Used to check current status of a service
d) Enable or Disable Service

Use this to enable or disable any service on your system. The enabled service autostarts on system boot. This
is the similar option for systemd than chkconfig for the SysV init.

sudo systemctl enable mysql.service

sudo systemctl disable mysql.service

Enable: Used to enable service to start on system boot


Disable: Used to disable service to not to start on system boot
e) Check Service is Enabled or Disabled
Use this to check if any service is currently active or enabled.
sudo systemctl is-active mysql.service
sudo systemctl is-enabled mysql.service
is-active:Usedtocheckifservicecurrentservicestatus
is-enabled:Usedtocheckifserviceisenabledtostartonsystemboot

Page 6 / 42
7) Linux cd command
The cd command stands for “change directory”. This command is used to leave current directory and
navigate to another directory on the system.
Syntax:

cd <Path to new dir>


a) Change to a New Directory
After login to the system, the user gets the home directory. Now you can navigate to another directory for
example /home/rahul/Workspace where my present directory is /home/rahul

cd Workspace

Use pwd to check your present working directory.

pwd

/home/rahul/Workspace

There are two ways to navigate between directories is the absolute path and relative path.

b) The Absolute Path vs Relative Path

- Absolute Path:
An absolute path is a complete path to the directory from the root directory (/). In simple terms, all the path
started with a slash (/) are an absolute path. For example:
• /var
• /var/www/html
• /home/rahul/Workspace
• /backup/db/daily

You can see all the above paths are started with a slash (/).

- Relative Path:

Any path which is not started with a slash (/) is a relative path. For example:

• Documents
• www/html
• Workspace/Linux/Guides
• www/tecadmin.net/

c) Change Directory with Absolute Path


Changing to directory /home/rahul/Workspace with absolute directory using the cd command.
Page 7 / 42
 cd/home/rahul/Workspace
Change Directory with Relative Path
Changing to the directory Linux/Guides with relative path using the cd command.
cd Linux/Guides
The cd Options
Use below options to understand the uses of cd command.

Option Description
cd . The single dot (.) denotes to current directory. This will keep you in current directory.
cd .. Change to parent directory.
cd ~ Change to home directory. As ~ denotes to home directory.
cd – Change to previos directory
cd /path/to/dir Change to specified directory

II- File permissions

This is a most important topic for the security of the files and directories on your Unix/Linux systems. This
tutorial covers the file permissions, how to check the current permissions on file and change it. To identify
the current permissions set on a file or directory. Run ls -l command on terminal.

There are 10 bits defined with file permissions. Each has a special meaning. Below is the preview of file
permissions defined for a file.

Every file on Linux has 3 types of members (owner, group, other) associated with them.
• The first bit shows the file type
• The 2, 3 and 4’th bit shows the permission of file owner
• The 5, 6 and 7’th bit shows the permission of group members
• The 8, 9 and 10’th bit shows the permission of other users

Page 8 / 42
1) Type of Roles and Permissions

To understand file permission you must know about Roles and Permission types. There are three types of
roles available in Linux systems (User, Group, and Others). Each role has 3 types of permissions (Read, Write,
and Execute).

a) Roles:
• User (Owner)
• Group (All group members)
• Other (All other users

b) Permissions:
• Read (r) – Member can read the file content or List files in a directory
• Write (w) – Member can write content to file or Create, list, rename, delete file in a directory
• Execute (x) – Member can execute any file like sheel script or enter to the directory, and access files and
directories
2) Ways to Change File Permissions in Linux

The chmod command allows users two ways to set permission on any file. Read below about both options:
a) Symbolic Notation
The symbolic notation used to set permission with alphabets as follwoing:
Roles Permissions
• u–User • r–readpermission
• g–Group • w–writepermission
• o–Other • x–executepermission

b) Octal Notation
The octal notation allows users to set permission in number formats. Each permission have the pre-defined
number as following
• Read (r) – 4
• Write (w) – 2
• Execute (x) – 1
Possible combinations as as follows:
7 - 4+2+1 (rwx) (Read + Write + Execute)
6 - 4+2 (rw-) (Read + Write)
5 - 4+1 (r-x) (Read + Execute)
4 - 4 (r--) (Read)
3 - 2+1 (-wx) (Write + Execute)
2 - 2 (-w-) (Write)
1 - 1 (--x) (Execute)
0 - 0 (---) (None)

Page 9 / 42
3) Linux chown command
Linux chown command is used for changing the owner or group owner of a file or directory.
Syntax:
chown <USER>[:<GROUP>] [FILE]...
a) Example:
Set the file owner of testfile.txt to user “rahul”.
chown rahul testfile.txt

Set the file owner of testfile.txt to user “rahul” and also set the group owner to “root”.

chown rahul:root testfile.txt


b) Change File Ownership Recursively

You can specify option -R to change owner and group recursively to all files in the specified directory and
subdirectory. For example, set Apache user permission to all files under /var/www/html directory.

chown -R www-data:www-data /var/www/data

4) Linux chgrp command

Linux chgrp command is used for changing the group of the file or directory.
Syntax:
chown <GROUP> [FILE]...
a) Example:
Set the file group of testfile.txt to group “staff”. Now all the member users of staff group have privileges on
file as a group user.
chgrp staff testfile.txt
b) Change File Ownership Recursively

You can specify option -R to change group recursively to all files in the specified directory and subdirectory.
For example, set the group staff to all files under /home/rahul directory.

chgrp -R staff /home/rahul

4) Linux chmod command

Linux chmod command is used to change access permissions of files and directories. In this article, you will
learn how to change permissions of any file or directory with chmod command. We have already described
the Linux file permissions.

Page 10 / 42
Syntax:
chmod [PERMISSIONS] [FILE]...

a) Example:
chmod 755 filename

You can use -R to change permissions recursively.

chmod -R 755 /var/www/html

There are two ways available to change file permissions on Linux. First is Symbolic Notation and second is
octal notation. Both are described below:

b) Using Symbolic Notation:

Just for the reminder, the following symbols are used for file permissions. Here roles
are User(u) , Group(g) , Others(o) and the permissions are Read(r) , Write(w) , Execute(x) .

You can combine any symbols to set permission together like User+Group (ug), User+Group+Other (ugo),
User+Other(uo).

Similarly, you can do the same with permissions like Read+Write (rw), Read+Execute (rx),
Read+Write+Execute (rwx).

User => Read + Execute

chmod u+rx filename

User + Group => Read + Execute

chmod u+rx,g+rx filename

chmod ug+rx filename

User => All, Group => Read + Execute, Other => Read

chmod u+rwx,g+rx,o+r filename

User => All, Group + Others => Read + Execute

chmod u+rwx,go+rx filename

All permission to everyone (not recommended)

chmod ugo+rwx filename

Page 11 / 42
c) Using Octal Notation:

Using the octal notation you can set permissions in number between 0-7. Each number is calculated with the
sum of read (4), write (2) and execute (1).

For example, if you set permission 6, it means 4+2 (read + write). If you set permission 5 means 4+1 (read +
execute).

The permissions are set in a sequence user, group, others. For example if you set permission 754, it means
user => 7, group => 5 and other => 4.

Let’s have some examples.

User => read+write+execute, Group => read+execute, Other => read

chmod 754 filename

Here:

• 7 is for user is combined with read-4 + write-2 + execute-1


• 5 is for group is combined with read-4 + execute-1
• 4 is for other is read-1 only.

User => read+write, Group => read+write, Other => read

chmod 664 filename


5) Linux chattr command

The chattr command change file attributes on a Linux file system. It provides the higher level of security on
files and directories. You can also use this security to prevent important files from accidental deletion.

Syntax:
chattr [ -RVf ] [ -v version ] [ mode ] files...

You can add any attribute to file using + symbol or use – symbol to remove the attribute from the file.

a) Make File/Directory immutable

Use +i option with chattr on file to make file unchangeable, This will not allow making any changes in the file
even to root user.

$ chattr +i testfile.txt

Page 12 / 42
$ chattr +i testdir
b) Enable Append Mode Only
Use +a option to set the file to append mode only. You can not option this for editing. We can only append
content to file.

$ chattr +a myfile.txt

c) Remove Attributes

You can use – option with attribute to remove it from files. Use -R to run command recursively on the
directory as well.

$ chattr -i testfile.txt

$ chattr -a myfile.txt

$ chattr -R -ai testdir

III- Linux filters


1) Linux cut command
The Linux cut command is a text processing command. This command is used to extract the specific column
from a file. You need to define the column number and column delimiter with command.
Syntax:
cut -d<delemeter> -f<field1,field2,...> filename

• -d This defines the deleter as coloumn seprator. Defaut column seprater is single space or tab.
• -f Specify fields (column numbers) to fetch.
a) Example
Grep all usernames with there home directory created on a Linux system. The /etc/passwd file contained all
users on a Linux system with other details. First filed of the file contains the username and 6’th filed contain
the home directory of that user.

Page 13 / 42
cut -d":" -f1,6 /etc/passwd

Fetch the column number 1,2,3,4 and 6. Here you can define a range using hyphen like 1-4.

cut -d":" -f1-4,6 /etc/passwd

You can also define multiple ranges with the single command.

cut -d":" -f1-3,5-7 /etc/passwd


2) Linux tee command
The Linux tee command is used to route output data to multiple outputs. Tee can display output on STDOUT
as well ass write to file at a time.

a. Example
The following command will display list of files in current directory on screen as well as write in list.txt file.

ls | tee list.txt
b. Append Data to File

The default tee overwrites the file content. You can use -a to append data to file.

ls | tee –a list.txt
c. Write data to Multiple File
You can also write the output to multiple files in a single command. The example is below

ls | tee list1.txt list2.txt


3) Linux grep command

The Linux grep command stands for “Global Regular Expression Print“. The grep command-line utility is used
for searching content from files based on a pattern or regular expression.

Synatx:

grep "PATTERN" [FILE]


Example:
Search all users under /etc/passwd have the bash shell.

grep "bash" /etc/passwd

Grep command can also take the output of another command as input using pipes. For example:

cat /etc/passwd | grep "bash"

Page 14 / 42
a) Case Sensitive Search
Grep uses -i option to run a case-sensitive search.

grep -i "SearchPattern" filename


b) Search Recursively in Directory Tree
Using the -r switch grep to search for pattern recursively for all files under the specified directory and their
subdirectories.
grep -r "SearchPattern" /home/rahul
c) Print Matching Filename Only

The default grep prints the matching content on the output with the respective file names. You can hide the
content and display only filename in grep output.
Use -l to print pattern matching filenames.
grep -rl "SearchPattern" /home/rahul

Use -L to revert the output. This will print only those file where no match found.

grep -rL "SearchPattern" /home/rahul


d) Print Before/After Lines of Matching Pattern

This is a useful feature of grep command. You can print the defined number of lines just before line matches
the pattern or just after lines of matches pattern.
Use -A followed by number of lines to print lines before the matching pattern line.
grep -A2 "SearchPattern" myfile.csv

Use -B followed by number of lines to print lines after the matching pattern line.

grep -B2 "SearchPattern" myfile.csv

Use -C followed by number of lines to print lines before and after the matching pattern line.

grep -B2 "SearchPattern" myfile.csv


4) Linux wc command

The Linux wc command is used to count the number of lines, words, and byte (character) in a file or input
stream.
Syntax:
wc [OPITON] [FILE}

Page 15 / 42
Example:
Use -l to count the number of lines in a file
wc -l myfile.txt

Use -w to count the number of words in a file

wc -w myfile.txt

Use -c to count the number of bytes in a file. You can use this to count character in a file

wc -c myfile.txt
a) Use wc with Piped Input

You can also use wc with piped input in Linux and count the lines, words, and characters in an input data.

cat myfile.txt | wc -lwc

Another example of wc command to count the number of lines in the output of the previous command.

find . -name "*.log" | wc -l

IV- Deleting Files


In Linux, a shell pattern is a string that consists of the following special characters, which are referred to
as wildcards ormetacharacters:
* – matches zero or more characters
? – matches any single character
[seq] – matches any character in seq
[!seq] – matches any character not in seq

There are three possible methods we shall explore here, and these include:

1) Delete Files Using Extended Pattern Matching Operators

The different extended pattern matching operators are listed below, where pattern-list is a list containing
one or more filenames, separated using the | character:
*(pattern-list) – matches zero or more occurrences of the specified patterns
?(pattern-list) – matches zero or one occurrence of the specified patterns

+(pattern-list) – matches one or more occurrences of the specified patterns


@(pattern-list) – matches one of the specified patterns
!(pattern-list) – matches anything except one of the given patterns

To use them, enable the extglob shell option as follows:


Page 16 / 42
# shopt -s extglob

1. To delete all files in a directory except filename, type the command below:

$ rm -v !("filename")

2. To delete all files with the exception of filename1 and filename2:

$ rm -v !("filename1"|"filenam

3. The example below shows how to remove all files other than all .zip files interactively:

$ rm -i !(*.zip)

4. Next, you can delete all files in a directory apart from all .zip and .odt files as follows, while displaying

what is being done:

$ rm -v !(*.zip|*.odt)

Once you have all the required commands, turn off the extglob shell option like so:

$ shopt -u extglob

2) Delete Files Using Linux find Command

Under this method, we can use find command exclusively with appropriate options or in conjunction
with xargs command by employing a pipeline as in the forms below:

$ find /directory/ -type f -not -name 'PATTERN' -delete

Page 17 / 42
$ find /directory/ -type f -not -name 'PATTERN' -print0 | xargs -0 -I {} rm {}

$ find /directory/ -type f -not -name 'PATTERN' -print0 | xargs -0 -I {} rm [options] {}

5. The following command will delete all files apart from .gz files in the current directory:

$ find . -type f -not -name '*.gz'-delete

6. Using a pipeline and xargs, you can modify the case above as follows:

$ find . -type f -not -name '*gz' -print0 | xargs -0 -I {} rm -v {}

7. Let us look at one additional example, the command below will wipe out all files excluding .gz , .odt ,
and .jpg files in the current directory:

$ find . -type f -not \(-name '*gz' -or -name '*odt' -or -name '*.jpg' \) -delete

3) Delete Files Using Bash GLOBIGNORE Variable

This last approach however, only works with bash. Here, the GLOBIGNORE variable stores a colon-
separated pattern-list (filenames) to be ignored by pathname expansion.
To employ this method, move into the directory that you wish to clean up, then set
the GLOBIGNORE variable as follows:

$ cd test

$ GLOBIGNORE=*.odt:*.iso:*.txt

In this instance, all files other than .odt , .iso , and .txt files with be removed from the current directory.

Now run the command to clean up the directory:


$ rm -v *

Page 18 / 42
Afterwards, turn off GLOBIGNORE variable:
$ unset GLOBIGNORE

Delete Files Using Bash GLOBIGNORE Variable

Page 19 / 42
The Essential Toolkit for the Terminal
There are a countless number of commands in Linux. We are bound to use a number of them on a daily
routine or numerous times to perform common tasks than others.

We will introduce you a list of most frequently used Linux commands with their examples for easy learning.
You can find the actual description of each Linux command in their manual page which you can access like
this:

$ man command-name

adduser/addgroup Command

The adduser and addgroup commands are used to add a user and group to the system respectively
according to the default configuration specified in /etc/adduser.conf file.
$ sudo adduser tecmint

agetty Command

agetty is a program which manages physical or virtual terminals and is invoked by init. Once it detects a
connection, it opens a tty port, asks for a user’s login name and calls up the /bin/login command. Agetty is
a substitute of Linux getty:
$ agetty -L 9600 ttyS1 vt100

alias Command

alias is a useful shell built-in command for creating aliases (shortcut) to a Linux command on a system. It is
helpful for creating new/custom commands from existing Shell/Linux commands (including options):
$ alias home='cd /home/tecmint/public_html'

The above command will create an alias called home for /home/tecmint/public_html directory, so
whenever you type home in the terminal prompt, it will put you in
the /home/tecmint/public_html directory.
anacron Command
anacron is a Linux facility used to run commands periodically with a frequency defined in days, weeks and
months.
Unlike its sister cron; it assumes that a system will not run continuously, therefore if a scheduled job is due
when the system is off, it’s run once the machine is powered on.

Page 20 / 42
apropos Command
apropos command is used to search and display a short man page description of a command/program as
follows.
$ apropos adduser

apt Command
apt tool is a relatively new higher-level package manager for Debian/Ubuntu systems:
$ sudo apt update

apt-get Command

apt-get is a powerful and free front-end package manager for Debian/Ubuntu systems. It is used to install
new software packages, remove available software packages, upgrade existing software packages as well
as upgrade entire operating system.
$ sudo apt-get update

aptitude Command

aptitude is a powerful text-based interface to the Debian GNU/Linux package management system.
Like apt-get and apt; it can be used to install, remove or upgrade software packages on a system.
$ sudo aptitude update

arch Command

arch is a simple command for displaying machine architecture or hardware name (similar to uname -m):
$ arch

arp Command

ARP (Address Resolution Protocol) is a protocol that maps IP network addresses of a network neighbor with
the hardware (MAC) addresses in an IPv4 network.
You can use it as below to find all alive hosts on a network:

$ sudo arp-scan --interface=enp2s0 --localnet

at Command
at command is used to schedule tasks to run in a future time. It’s an alternative to cron and anacron,
however, it runs a task once at a given future time without editing any config files:
Page 21 / 42
For example, to shutdown the system at 23:55 today, run:

$ sudo echo "shutdown -h now" | at -m 23:55

atq Command
atq command is used to view jobs in at command queue:
$ atq

atrm Command
atrm command is used to remove/deletes jobs (identified by their job number) from at command queue:
$ atrm 2

awk Command
Awk is a powerful programming language created for text processing and generally used as a data
extraction and reporting tool.
$ awk '//{print}'/etc/hosts

batch Command
batch is also used to schedule tasks to run a future time, similar to the at command.

basename Command
basename command helps to print the name of a file stripping of directories in the absolute path:
$ basename bin/findhosts.sh

bc Command
bc is a simple yet powerful and arbitrary precision CLI calculator language which can be used like this:
$ echo 20.05 + 15.00 | bc

bg Command
bg is a command used to send a process to the background.
$ tar -czf home.tar.gz .

$ bg

Page 22 / 42
$ jobs

bzip2 Command
bzip2 command is used to compress or decompress file(s).
$ bzip2 -z filename #Compress

$ bzip2 -d filename.bz2 #Decompress

cal Command
The cal command print a calendar on the standard output.
$ cal

cat Command
cat command is used to view contents of a file or concatenate files, or data provided on standard input,
and display it on the standard output.
$ cat file.txt

chgrp Command
chgrp command is used to change the group ownership of a file. Provide the new group name as its first
argument and the name of file as the second argument like this:
$ chgrp tecmint users.txt

chmod Command
chmod command is used to change/update file access permissions like this.
$ chmod +x sysinfo.sh

chown Command
chown command changes/updates the user and group ownership of a file/directory like this.
$ chmod -R www-data:www-data /var/www/html

cksum Command
cksum command is used to display the CRC checksum and byte count of an input file.
$ cksum README.txt

Page 23 / 42
clear Command
clear command lets you clear the terminal screen, simply type.
$ clear

cmp Command
cmp performs a byte-by-byte comparison of two files like this.
$ cmp file1 file2

comm Command
comm command is used to compare two sorted files line-by-line as shown below.
$ comm file1 file2

cp Command
cp command is used for copying files and directories from one location to another.
$ cp /home/tecmint/file1 /home/tecmint/Personal/

date Command
date command displays/sets the system date and time like this.
$ date

$ date --set="8 JUN 2017 13:00:00"

dd Command
dd command is used for copying files, converting and formatting according to flags provided on the
command line. It can strip headers, extracting parts of binary files and so on.
The example below shows creating a boot-able USB device:

$ dd if=/home/tecmint/kali-linux-1.0.4-i386.iso of=/dev/sdc1 bs=512M; sync

df Command
df command is used to show file system disk space usage as follows.
$ df -h

Page 24 / 42
diff Command
diff command is used to compare two files line by line. It can also be used to find the difference between
two directories in Linux like this:
$ diff file1 file2

dir Command
dir command works like Linux ls command, it lists the contents of a directory.
$ dir

dmidecode Command
dmidecode command is a tool for retrieving hardware information of any Linux system. It dumps a
computer’s DMI (a.k.a SMBIOS) table contents in a human-readable format for easy retrieval.
To view your system hardware info, you can type:

$ sudo dmidecode --type system

du Command
du command is used to show disk space usage of files present in a directory as well as its sub-directories as
follows.
$ du /home/aaronkilik

echo Command
echo command prints a text of line provided to it.
$ echo “This is TecMint - Linux How Tos”

eject Command
eject command is used to eject removable media such as DVD/CD ROM or floppy disk from the system.
$ eject /dev/cdrom

$ eject /mnt/cdrom/

$ eject /dev/sda

env Command
env command lists all the current environment variables and used to set them as well.

Page 25 / 42
$ env

exit Command
exit command is used to exit a shell like so.
$ exit

expr Command
expr command is used to calculate an expression as shown below.
$ expr 20 + 30

factor Command
factor command is used to show the prime factors of a number.
$ factor 10

find Command
find command lets you search for files in a directory as well as its sub-directories. It searches for files by
attributes such as permissions, users, groups, file type, date, size and other possible criteria.
$ find /home/tecmint/ -name tecmint.txt

free Command
free command shows the system memory usage (free, used, swapped, cached, etc.) in the system including
swap space. Use the -h option to display output in human friendly format.

$ free -h

grep Command
grep command searches for a specified pattern in a file (or files) and displays in output lines containing that
pattern as follows.
$ grep ‘tecmint’ domain-list.txt

groups Command
groups command displays all the names of groups a user is a part of like this.
$ groups

Page 26 / 42
$ groups tecmint

gzip Command
Gzip helps to compress a file, replaces it with one having a .gz extension as shown below:

$ gzip passwds.txt

$ cat file1 file2 | gzip > foo.gz

gunzip Command
gunzip expands or restores files compressed with gzip command like this.
$ gunzip foo.gz

head Command
head command is used to show first lines (10 lines by default) of the specified file or stdin to the screen:
# ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head

history Command
history command is used to show previously used commands or to get info about command executed by a
user.
$ history

hostname Command
hostname command is used to print or set system hostname in Linux.
$ hostname

$ hostname NEW_HOSTNAME

hostnamectl Command
hostnamectl command controls the system hostname under systemd. It is used to print or modify the
system hostname and any related settings:
$ hostnamectl

$ sudo hostnamectl set-hostname NEW_HOSTNAME

Page 27 / 42
hwclock
hwclock is a tool for managing the system hardware clock; read or set the hardware clock (RTC).
$ sudo hwclock

$ sudo hwclock --set --date 8/06/2017

hwinfo Command
hwinfo is used to probe for the hardware present in a Linux system like this.
$ hwinfo

id Command
id command shows user and group information for the current user or specified username as shown below.
$ id tecmint

ifconfig Command
ifconfig command is used to configure a Linux systems network interfaces. It is used to configure, view and
control network interfaces.
$ ifconfig

$ sudo ifconfig eth0 up

$ sudo ifconfig eth0 down

$ sudo ifconfig eth0 172.16.25.125

ionice Command
ionice command is used to set or view process I/O scheduling class and priority of the specified process.
If invoked without any options, it will query the current I/O scheduling class and priority for that process:

$ ionice -c 3 rm /var/logs/syslog

iostat Command
iostat is used to show CPU and input/output statistics for devices and partitions. It produces useful reports
for updating system configurations to help balance the input/output load between physical disks.
$ iostat

Page 28 / 42
ip Command
ip command is used to display or manage routing, devices, policy routing and tunnels. It also works as a
replacement for well known ifconfig command.
This command will assign an IP address to a specific interface (eth1 in this case).

$ sudo ip addr add 192.168.56.10 dev eth1

iptables Command
iptables is a terminal based firewall for managing incoming and outgoing traffic via a set of configurable
table rules.
The command below is used to check existing rules on a system (using it may require root privileges).

$ sudo iptables -L -n -v

iw Command
iw command is used to manage wireless devices and their configuration.
$ iw list

iwlist Command
iwlist command displays detailed wireless information from a wireless interface. The command below
enables you to get detailed information about the wlp1s0 interface.
$ iwlist wlp1s0 scanning

kill Command
kill command is used to kill a process using its PID by sending a signal to it (default signal for kill is TERM).
$ kill -p 2300

$ kill -SIGTERM -p 2300

killall Command
killall command is used to kill a process by its name.
$ killall firefox

kmod Command
kmod command is used to manage Linux kernel modules. To list all currently loaded modules, type.
$ kmod list

Page 29 / 42
last Command
last command display a listing of last logged in users.
$ last

ln Command
ln command is used to create a soft link between files using the -s flag like this.

$ ln -s /usr/bin/lscpu cpuinfo

locate Command
locate command is used to find a file by name. The locate utility works better and faster than
it’s find counterpart.
The command below will search for a file by its exact name (not *name*):

$ locate -b '\domain-list.txt'

login Command
login command is used to create a new session with the system. You’ll be asked to provide a username and
a password to login as below.
$ sudo login

ls Command
ls command is used to list contents of a directory. It works more or less like dir command.
The -l option enables long listing format like this.

$ ls -l file1

lshw Command
lshw command is a minimal tool to get detailed information on the hardware configuration of the machine,
invoke it with superuser privileges to get a comprehensive information.
$ sudo lshw

Page 30 / 42
lscpu Command
lscpu command displays system’s CPU architecture information (such as number of CPUs, threads, cores,
sockets, and more).
$ lscpu

lsof Command
lsof command displays information related to files opened by processes. Files can be of any type, including
regular files, directories, block special files, character special files, executing text reference, libraries, and
stream/network files.
To view files opened by a specific user’s processes, type the command below.

$ lsof -u tecmint

lsusb Command
lsusb command shows information about USB buses in the system and the devices connected to them like
this.
$ lsusb

man Command
man command is used to view the on-line reference manual pages for commands/programs like so.
$ man du

$ man df

md5sum Command
md5sum command is used to compute and print the MD5 message digest of a file. If run without
arguments, debsums checks every file on your system against the stock md5sum files:
$ sudo debsums

mkdir Command
mkdir command is used to create single or more directories, if they do not already exist (this can be
overridden with the -p option).
Page 31 / 42
$ mkdir tecmint-files

OR

$ mkdir -p tecmint-files

more Command
more command enables you to view through relatively lengthy text files one screenful at a time.
$ more file.txt

mv Command
mv command is used to rename files or directories. It also moves a file or directory to another location in
the directory structure.
$ mv test.sh sysinfo.sh

nano Command
nano is a popular small, free and friendly text editor for Linux; a clone of Pico, the default editor included in
the non-free Pine package.
To open a file using nano, type:

$ nano file.txt

nc/netcat Command
nc (or netcat) is used for performing any operation relating to TCP, UDP, or UNIX-domain sockets. It can
handle both IPv4 and IPv6 for opening TCP connections, sending UDP packets, listening on arbitrary TCP
and UDP ports, performing port scanning.
The command below will help us see if the port 22 is open on the host 192.168.56.5.

$ nc -zv 192.168.1.5 22

Page 32 / 42
netstat Command
netstat command displays useful information concerning the Linux networking subsystem (network
connections, routing tables, interface statistics, masquerade connections, and multicast memberships).
This command will display all open ports on the local system:

$ netstat -a | more

nice Command
nice command is used to show or change the nice value of a running program. It runs specified command
with an adjusted niceness. When run without any command specified, it prints the current niceness.
The following command starts the process “tar command” setting the “nice” value to 12.
$ nice -12 tar -czf backup.tar.bz2 /home/*

nmap Command
nmap is a popular and powerful open source tool for network scanning and security auditing. It was
intended to quickly scan large networks, but it also works fine against single hosts.
The command below will probe open ports on all live hosts on the specified network.

$ nmap -sV 192.168.56.0/24

nproc Command
nproc command shows the number of processing units present to the current process. It’s output may be
less than the number of online processors on a system.
$ nproc

openssl Command
The openssl is a command line tool for using the different cryptography operations of OpenSSL’s crypto
library from the shell. The command below will create an archive of all files in the current directory
and encrypt the contents of the archive file:
$ tar -czf - * | openssl enc -e -aes256 -out backup.tar.gz

Page 33 / 42
passwd Command
passwd command is used to create/update passwords for user accounts, it can also change the account or
associated password validity period. Note that normal system users may only change the password of their
own account, while root may modify the password for any account.
$ passwd tecmint

pidof Command
pidof displays the process ID of a running program/command.
$ pidof init

$ pidof cinnamon

ping Command
ping command is used to determine connectivity between hosts on a network (or the Internet):
$ ping google.com

ps Command
ps shows useful information about active processes running on a system. The example below shows
the top running processes by highest memory and CPU usage.
# ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head

pstree Command
pstree displays running processes as a tree which is rooted at either PID or init if PID is omitted.
$ pstree

pwd Command
pwd command displays the name of current/working directory as below.
$ pwd

Page 34 / 42
rdiff-backup Command
rdiff-backup is a powerful local/remote incremental backup script written in Python. It works on any POSIX
operating system such as Linux, Mac OS X.
Note that for remote backups, you must install the same version of rdiff-backup on both the local and
remote machines. Below is an example of a local backup command:

$ sudo rdiff-backup /etc /media/tecmint/Backup/server_etc.backup

reboot Command
reboot command may be used to halt, power-off or reboot a system as follows.
$ reboot

rename Command
rename command is used to rename many files at once. If you’ve a collection of files with “.html”
extension and you want to rename all of them with “.php” extension, you can type the command below.
$ rename 's/\.html$/\.php/' *.html

rm command
rm command is used to remove files or directories as shown below.
$ rm file1

$ rm -rf my-files

rmdir Command
rmdir command helps to delete/remove empty directories as follows.
$ rmdir /backup/all

scp Command
scp command enables you to securely copy files between hosts on a network, for example.
$ scp ~/names.txt [email protected]:/root/names.txt

Page 35 / 42
shutdown Command
shutdown command schedules a time for the system to be powered down. It may be used to halt, power-
off or reboot the machine like this.
$ shutdown --poweroff

sleep Command
sleep command is used to delay or pause (specifically execution of a command) for a specified amount of
time.
$ check.sh; sleep 5; sudo apt update

sort Command
sort command is used to sort lines of text in the specified file(s) or from stdin as shown below
$ cat words.txt

split Command
split as the name suggests, is used to split a large file into small parts.
$ tar -cvjf backup.tar.bz2 /home/tecmint/Documents/*

ssh Command
ssh (SSH client) is an application for remotely accessing and running commands on a remote machine. It is
designed to offer a secure encrypted communications between two untrusted hosts over an insecure
network such as the Internet.
$ ssh [email protected]

stat Command
stat is used to show a file or file system status like this ( -f is used to specify a filesystem).

$ stat file1

su Command
su command is used to switch to another user ID or become root during a login session. Note that
when su is invoked without a username, it defaults to becoming root.
Page 36 / 42
$ su

$ su tecmint

sudo Command
sudo command allows a permitted system user to run a command as root or another user, as defined by
the security policy such as sudoers.
In this case, the real (not effective) user ID of the user running sudo is used to determine the user name
with which to query the security policy.
$ sudo apt update

$ sudo useradd tecmint

$ sudo passwd tecmint

sum Command
sum command is used to show the checksum and block counts for each each specified file on the command
line.
$ sum output file.txt

tac Command
tac command concatenates and displays files in reverse. It simply prints each file to standard output,
showing last line first.
$tac file.txt

tail Command
tail command is used to display the last lines (10 lines by default) of each file to standard output.
If there more than one file, precede each with a header giving the file name. Use it as follow (specify more
lines to display using -n option).

$ tail long-file

OR

Page 37 / 42
$ tail -n 15 long-file

talk Command
talk command is used to talk to another system/network user. To talk to a user on the same machine, use
their login name, however, to talk to a user on another machine use ‘user@host’.
$ talk person [ttyname]

OR

$ talk‘user@host’ [ttyname]

tar Command
tar command is a most powerful utility for archiving files in Linux.
$ tar -czf home.tar.gz .

tee Command
tee command is used to read from standard input and prints to standard output and files as shown below.
$ echo "Testing how tee command works" | tee file1

tree Command
The tree command is a tiny, cross-platform command-line program used to recursively list or display the
content of a directory in a tree-like format.
$ tree

time Command
time command runs programs and summarizes system resource usage.
$ time wc /etc/hosts

top Command
top program displays all processes on a Linux system in regards to memory and CPU usage and provides a
dynamic real-time view of a running system.

Page 38 / 42
$ top

touch Command
touch command changes file timestamps, it can also be used to create a file as follows.
$ touch file.txt

tr Command
tr command is a useful utility used to translate (change) or delete characters from stdin, and write the
result to stdout or send to a file as follows.
$ cat domain-list.txt | tr [:lower:] [:upper:]

uname Command
uname command displays system information such as operating system, network node hostname kernel
name, version and release etc.
Use the -a option to show all the system information:

$ uname

uniq Command
uniq command displays or omits repeated lines from input (or standard input). To indicate the number of
occurrences of a line, use the -c option.

$ cat domain-list.txt

uptime Command
uptime command shows how long the system has been running, number of logged on users and the system
load averages as follows.
$ uptime

users Command
users command shows the user names of users currently logged in to the current host like this.
$ users

Page 39 / 42
vim/vi Command
vim (Vi Improved) popular text editor on Unix-like operating systems. It can be used to edit all kinds of plain
text and program files.
$ vim file

w Command
w command displays system uptime, load averages and information about the users currently on the
machine, and what they are doing (their processes) like this.
$w

wall Command
wall command is used to send/display a message to all users on the system as follows.
$ wall “This is TecMint – Linux How Tos”

watch Command
watch command runs a program repeatedly while displaying its output on fullscreen. It can also be used to
watch changes to a file/directory. The example below shows how to watch the contents of a directory
change.
$ watch -d ls -l

wc Command
wc command is used to display newline, word, and byte counts for each file specified, and a total for many
files.
$ wc filename

wget Command
wget command is a simple utility used to download files from the Web in a non-interactive (can work in the
background) way.
$ wget -c http://ftp.gnu.org/gnu/wget/wget-1.5.3.tar.gz

Page 40 / 42
whatis Command
whatis command searches and shows a short or one-line manual page descriptions of the provided
command name(s) as follows.
$ whatis wget

which Command
which command displays the absolute path (pathnames) of the files (or possibly links) which would be
executed in the current environment.
$ which who

who Command
who command shows information about users who are currently logged in like this.
$ who

whereis Command
whereis command helps us locate the binary, source and manual files for commands.
$ whereis cat

xargs Command
xargs command is a useful utility for reading items from the standard input, delimited by blanks (protected
with double or single quotes or a backslash) or newlines, and executes the entered command.
The example below show xargs being used to copy a file to multiple directories in Linux.
$ echo /home/aaronkilik/test/ /home/aaronkilik/tmp | xargs -n 1 cp -v /home/aaronkilik/bin/sys_info.sh

yes Command
yes command is used to display a string repeatedly until when terminated or killed using [ Ctrl + C ] as

follows.
$ yes "This is TecMint - Linux HowTos"

Page 41 / 42
youtube-dl Command
youtube-dl is a lightweight command-line program to download videos and also extract MP3 tracks from
YouTube.com and a few more sites.
The command below will list available formats for the video in the provided link.

$ youtube-dl --list-formats https://www.youtube.com/watch?v=iR

zcmp/zdiff Command
zcmp and zdiff minimal utilities used to compare compressed files as shown in the examples below.
$ zcmp domain-list.txt.zip basic_passwords.txt.zip

$ zdiff domain-list.txt.zip basic_passwords.txt.zip

zip Command
zip is a simple and easy-to-use utility used to package and compress (archive) files.
$ tar cf - . | zip | dd of=/dev/nrst0 obs=16k

$ zip inarchive.zip foo.c bar.c --out outarchive.zip

$ tar cf - .| zip backup -

zz Command
zz command is an alias of the fasd commandline tool that offers quick access to files and directories in
Linux. It is used to quickly and interactively cd into a previously accessed directory by selecting the
directory number from the first field as follows.
$ zz

That’s it for now! As we mentioned before, there are a countless number of commands in Linux. The list is
possibly longer than we can offer. Use the feedback form below to share any useful and frequently used
commands missing in this list.

Page 42 / 42

You might also like