Linux
Linux
COMPUTER SCIENCE
SEMESTER -II (CBCS)
LINUX
: Yuvraj Wagh
VPM R Z SHAH College.
: Priya Jadhav
N.G. Acharya and D.K.Marathe College.
Published by
Director
Institute of Distance and Open Learning, University of Mumbai,Vidyanagari, Mumbai - 400 098.
UNIT I
Unit I
1. Introduction 1
2. Installation 13
3. Linux Structure 22
Unit II
4. Graphical Desktop 36
5. Command Line 83
Unit III
7. Security 161
8. Networking 168
*****
Syllabus
Additional References:
1) Linux kernel Home: http://kernel.org
2) Open Source Initiative: https://opensource.org/
3) The Linux Foundation: http://www.linuxfoundation.org/
UNIT I
1
INTRODUCTION
Unit Structure
1.0 Objectives
1.1 Introduction
1.2 An Overview
1.2.1 History of Linux
1.2.2 Philosophy
1.2.3 Community
1.2.4 Distributions
1.3 How is the Linux operating system used?
1.4 How the Linux Operating System Works
1.5 Linux Kernel vs Distribution
1.6 Why learn Linux?
1.6.1 Importance of Linux in software ecosystem
1.6.2 web servers
1.6.3 Supercomputers
1.6.4 Mobile
1.6.5 Servers
1.7 Pros and Cons of Linux
1.8 Let us Sum Up
1.9 Unit End Questions
1.10 List of References
1.11 Bibliography
1.0 OBJECTIVES
Introducing various tools and techniques commonly used by Linux
programmers, system administrators and end users to achieve their day-to-
day work in Linux environment.
1.1 INTRODUCTION
Linux is similar to Unix. It is coming under OS (Open source) and
community-developed operating system. Various devices like computers,
servers, mainframes, mobile devices, and embedded devices. Linux is
highly configurable. It depends on a modular design which provides
flexibility to users to customize their own versions of Linux.
1
1.2 AN OVERVIEW Introduction
2
Linux o Dell begun laptop distribution with Ubuntu which was pre-installed
on it in 2007.
o Linux kernel version 3.0 was released in 2011.
o Linux-based android of Google insisted 75% of the market share of
the Smartphone, based on the number of phones exported in 2013.
o Ubuntu insisted on 20000000+ users in 2014.
1.2.2 Philosophy:
All operating systems have some philosophy. When Unix was being
developed in the late 1960s and early 1970s, the inventors were intent
upon building an operating system that was significantly different from the
operating systems that ante ceded. The idea of Unix was markedly
different from that of other operating systems. And the Linux philosophy
is relatively naturally deduced directly from the Unix philosophy.
1.2.3 Community:
A distribution is largely driven by its inventor and communities. Some
develop and fund their distributions on a levy base, Debian being a well-
known illustration. Others maintain a community interpretation of their
commercial distributions. Numerous Internet communities also give
support to Linux users. Utmost distributions and free software / open-
source projects have IRC chatrooms or newsgroups. Online forums are
another means for support, with notable exempli cations
being LinuxQuestions.org and the various distribution specific support and
community forums, such as ones for Ubuntu, Fedora, and Gentoo. Linux
distributions host mailing lists: commonly there will be a specific topic
such as usage or development for a given list.
1.2.4 Distributions:
Other operating systems like Microsoft combine each bit of coding
internally and release it as a single package. You have to choose from one
of the interpretations they offer.But Linux is different from them.
Different parts include kernel, shell utilities, X server, system
environment, graphical programs, etc. If you want, you can access the
codes of all these parts and assemble them yourself. But its not an easy
task seeking a lot of time and all the parts has to be assembled correctly.
1) Ubuntu:
3
Well known distribution Introduction
Easy to use
2) Linux Mint:
Based on Ubuntu
3) Debian:
User Friendly.
Red hat uses trademark law to prevent their software from being
redistributed.
5) Fedora:
Less stable
4
Linux
Debian It provides stability but not recommended to a new user.
CentOS If you want to use red hat but without its trademark.
OpenSUSE It works same as Fedora but slightly older and more stable.
Arch Linux It is not for the beginners because every package has to be
installed by yourself.
Server OS: web servers, database servers, file servers, email servers
and any other type of shared server. Designed to support high-volume
and multithreading applications, Linux is well-suited for all types of
server applications.
Headless server OS: for systems that do not require a graphical user
interface (GUI) or directly connected terminal and keyboard.
Headless systems are often used for remotely managed networking
server and other devices.
Embedded device or appliance OS: needs less computing function.
It is used as as embedded OS for a variety of application like
including household appliances, automotive entertainment systems
and network file system appliances.
Network OS: for routers, switches, domain name system servers,
home networking devices and more. For example, Cisco that uses the
Linux kernel.
Software development OS: for enterprise software development.
Although many development tools have been ported to Windows or
other OSes, Linux is home to some of the most widely used open-
source software development tools. For example, git for distributed
source control; vim and emacs for source code editing; and compilers
and interpreters for almost every programming language.
5
Cloud OS: for cloud instances like Linux for cloud servers, desktops Introduction
and other services.
1.6.3 Supercomputers:
Less overhead, i.e., way faster: Linux does not require extra software
to update or upgrade.
1.6.4 Mobile:
1.6.5 Servers:
Linux servers are very powerful of their outstanding characteristics like
security, stability, and flexibility. These Linux servers has in built web
servers and business applications which supports network administration
and web and database management services.
9
Following are the Key features of Linux servers: Introduction
Unsupported hardware.
Steep learning curve. Many users struggle to learn to use the Linux
desktop or Linux-based applications.
In some cases, the same Linux attribute can be either an advantage or
disadvantage. For example, having many options for customizing the
Linux OS is advantageous for manufacturers looking for an embedded OS,
but it is a disadvantage for enterprises that want a desktop OS that can be
used by a wide range of end users.
10
Linux
1.8 LET US SUM UP
Linux is an open-source operating system. As it is open source, it is
special and different from other operating systems, which means that you
can customize it by editing source code. It provides programming as well
as a graphical user interface. Linux is built by Linux Torvalds because
he wanted to create a free operating system kernel that anyone can use.
Linux is a collection of operating systems that are based on Linux kernel.
The first version of Linux was released in the year 1991. The Linux
system is most commonly used for servers; however, it is available in
desktop versions as well.
Ubuntu, Devian, and Fedora are some popular Linux distributions. Also,
we have SUSE Linux Enterprise Server (SLES) and RedHat
Enterprise Linux for the commercial distribution of Linux. As it is open
source, we can modify the source code and make variations in the
operating system.
11
1.9 LIST OF REFERENCES Introduction
1.10 BIBLIOGRAPHY
1. Linux Command Line and Shell Scripting Bible, 3rd Edition by
Richard Blum
2. Linux: The Complete Reference, Sixth Edition by Richard Petersen
3. How Linux Works, 2nd Edition: What Every Superuser Should
Know Second Edition by Brian Ward
4. The Linux Command Line: A Complete Introduction 1st Edition
by by William E. Shotts Jr.
5. Fundamentals of Linux by Pelz Oliver
6. https://www.javatpoint.com/linux-distributions
7. https://searchdatacenter.techtarget.com/definition/Linux-operating-
system
8. https://opensource.com/resources/linux
9. https://www.linuxfoundation.org/tools/participating-in-open-source-
communities/
10. https://www.tutorialspoint.com/operating_system/os_linux.htm
*****
12
2
INSTALLATION
Unit Structure
2.1 Introduction
2.2 Download the Linux distribution of your choice
2.3 Boot into the Live CD or Live USB
2.4 Try out the Linux distribution before installing
2.5 Start the installation process
2.6 Create a username and password
2.7 Set up the partition
2.8 Boot into Linux
2.9 Check your hardware
2.10 Start using Linux
2.11 Linux Structure
2.11.1 Linux operating system
2.11.2 Architecture of Linux system
2.12 Unit End Questions
2.13 List of References
2.14 Bibliography
2.0 INTRODUCTION
Linux is the foundation of thousands of open-source operating systems
designed to replace Windows and Mac OS. It is free to download and
install on any computer. Because it is open source, there are a variety of
different interpretation, or distributions, available developed by different
groups. Follow the guidelines for installing any version of Linux.
13
2.2 DOWNLOAD THE LINUX DISTRIBUTION OF Installation
YOUR CHOICE.
Still, consider trying a featherlight and easy to use distribution, similar as
Ubuntu or Linux Mint. Linux distributions (known as "distros") are
generally available for free to download in ISO format. You can find the
ISO for the distribution of your choice at the distribution’s website. This
format needs to be burned to a CD or USB stick before you can use it to
install Linux. This will produce a Live CD or Live USB.
A Live CD or Live USB is a fragment that you can boot into, and
frequently contains a interpretation of the operating system that can be
run directly from the CD or USB stick.
Install an image burning program or use your system’s built-in burning
tool if you are using Windows 7, 8, or Mac OS X. Pen Drive Linux and
UNetBootin are two popular tools for burning ISO files to USB sticks.
14
Linux This will load the Advanced Start-up Options, where you can boot from
CD.
For Windows 10 users,
go to advanced boot and then "Restart Now."
Once you're in the boot menu,
select CD or USB.
Once you’ve changed the settings, save and exit the BIOS setup or boot
menu.
15
Installation
2.5 START THE INSTALLATION PROCESS.
If you are trying distro, then it can be launched from the application on the
desktop. If it is not distro, we can start the installation from the boot menu.
16
Linux
2.7 SET UP THE PARTITION
Linux needs to be installed on a separate partition from any other OS on
your computer if you intend binary booting Linux with another OS. A
partition is a portion of the hard drive that is formatted specifically for that
operating system.
Ubuntu will set a partition automatically and Linux installation require at
least 20 GB
If partitions are not given by installation process, then check the
formatted as EX4. If the copy of Linux you are installing is the only
operating system on the computer, you will most likely have to
manually set your partition size.
17
2.9 CHECK YOUR HARDWARE Installation
Utmost H/W should work out of the box with your Linux distro, though
you may need to download some additional drivers to get everything
working.
Some hardware requires proprietary drivers to work correctly in
Linux. This is most common with graphics cards.
In Ubuntu, we can download proprietary drivers through the System
Settings menu.
Select the Additional Drivers option, and then select the graphics
driver from the list. Other distros have specific methods for obtaining
extra drivers.
You can find other drivers from this list as well, such as Wi-Fi
drivers.
18
Linux 2.11.1 Linux operating system:
An OS can be defined as an interface between the computer hardware and
the user. OS is a group of software that handles the resources of the
computer and provides basic services for computer programs.
It is an essential component of system software. The objective is to
provide a platform for the user to run any program efficiently. Linux is
one of the famous versions of the UNIX OS. It is coming under free open
source.
19
2. System Libraries: These libraries can be specified as some special Installation
functions. These are applied for implementing the operating system's
functionality and don't need code access rights of the modules of kernel.
3. System Utility Programs: It is responsible for doing specialized level
and individual activities.
4. Hardware layer: Linux operating system contains a hardware layer
that consists of several peripheral devices like CPU, HDD, and RAM.
5. Shell: It is an interface among the kernel and user. It can afford the
services of kernel. It can take commands through the user and runs the
functions of the kernel. The shell is available in distinct types of OSes.
These operating systems are categorized into two different types, which
are the graphical shells and command-line shells.
The graphical line shells facilitate the graphical user interface, while the
command line shells facilitate the command line interface. Thus, both of
these shells implement operations. However, the graphical user interface
shells work slower as compared to the command-line interface shells.
There are a few types of these shells which are categorized as follows:
o Korn shell
o Bourne shell
o C shell
o POSIX shell
20
Linux 4. Fundamentals of Linux by Pelz Oliver.
2.14 BIBLIOGRAPHY
1. Linux Command Line and Shell Scripting Bible, 3rd Edition by
Richard Blum.
2. Linux: The Complete Reference, Sixth Edition by Richard Petersen.
3. How Linux Works, 2nd Edition: What Every Superuser Should
Know Second Edition by Brian Ward.
4. The Linux Command Line: A Complete Introduction 1st Edition
by by William E. Shotts Jr.
5. Fundamentals of Linux by Pelz Oliver.
*****
21
3
LINUX STRUCTURE
Unit Structure
3.1 Introduction
3.2 What is Linux File System?
3.3 Linux File System Structure
3.4 Types of Linux File System
3.4.1 Ext, Ext2, Ext3 and Ext4 file system
3.4.2 JFS File System
3.4.3 ReiserFS File System
3.4.4 XFS File System
3.4.5 Btrfs File System
3.4.6 Swap File System
3.5 Linux Boot Process
3.5.1 BIOS
3.5.2 MBR
3.5.3 GRUB
3.5.4 Kernel
3.5.5 Init
3.5.6 Runlevel programs
3.6 Shutdown
3.7 Very basic instructions to Linux Process
3.7.1 List processes
3.7.2 Verbose list (processes)
3.7.3 Kill by PID
3.7.4 Kill by name/keyword
3.7.5 List background jobs and resume background jobs
3.7.6 Bring the most recent job to the foreground
3.7.7 Bring a specific job to the foreground
3.8 Packaging Systems
3.8.1 High and low-level package tools
3.9 Graphical Vs Command line
3.10 Unit End Questions
3.11 List of References
3.12 Bibliography
22
Linux
3.1 INTRODUCTION
A Linux file system is a structured collection of files, which may be in a
disk drive or a partition. Mostly a partition is a segment of memory and
contains some data. Our system may contain various partitions of the
memory. Generally, every partition contains a file system. Some reasons
for maintaining the file system are given below.
o Primarily the computer saves data to the RAM storage; it may lose the
data if it gets turned off.
o Data storage is preferred on hard drives as compared to standard
RAM as RAM costs more than disk space.
File system contains the following sections:
o The root directory (/)
o A specific data storage format (EXT3, EXT4, BTRFS, XFS and so
on)
o A partition or logical volume having a particular file system.
its subdirectories.
23
Linux Structure
24
Linux 3.4.1 Ext, Ext2, Ext3 and Ext4 file system:
Ext4 file system is the fastest file system and compatible. It is the default
file system in linux distribution.
JFS stands for Journaled File System, and it is developed by IBM for
AIX Unix. It is an alternative to the Ext file system. It can also be used in
place of Ext4, where stability is needed with few resources. It is a handy
file system when CPU power is limited.
XFS file system was considered as high-speed JFS, which is developed for
parallel I/O processing. NASA still using this file system with its high
storage server (300+ Terabyte server).
Btrfs stands for the B tree file system. It is used for fault tolerance, repair
system, fun administration, extensive storage configuration, and more. It is
not a good suit for the production system.
The swap file system is used for memory paging in Linux operating
system during the system hibernation. A system that never goes in
hibernate state is required to have swap space equal to its RAM size.
25
3.5 LINUX BOOT PROCESS Linux Structure
The following are the 6 high level stages of a typical Linux boot process.
3.5.1 BIOS:
BIOS stands for Basic Input/Output System.
Performs some system integrity checks.
Searches, loads, and executes the boot loader program.
It looks for boot loader in floppy, cd-rom, or hard drive. You can
press a key (typically F12 of F2, but it depends on your system)
during the BIOS startup to change the boot sequence.
Once the boot loader program is detected and loaded into the memory,
BIOS gives the control to it.
So, in simple terms BIOS loads and executes the MBR boot loader.
3.5.2. MBR:
MBR stands for Master Boot Record.
It is located in the 1st sector of the bootable disk. Typically, /dev/hda,
or /dev/sda
26
Linux MBR is less than 512 bytes in size. This has three components 1)
primary boot loader info in 1st 446 bytes 2) partition table info in next
64 bytes 3) mbr validation check in last 2 bytes.
It contains information about GRUB (or LILO in old systems).
So, in simple terms MBR loads and executes the GRUB boot loader.
3.5.3 GRUB
GRUB stands for Grand Unified Bootloader.
If you have multiple kernel images installed on your system, you can
choose which one to be executed.
GRUB displays a splash screen, waits for few seconds, if you don‟t
enter anything, it loads the default kernel image as specified in the
grub configuration file.
GRUB has the knowledge of the filesystem (the older Linux loader
LILO didn‟t understand filesystem).
Grub configuration file is /boot/grub/grub.conf (/etc/grub.conf is a
link to this). The following is sample grub.conf of CentOS.
#boot=/dev/sda
default=0
timeout=5
splashimage=(hd0,0)/boot/grub/splash.xpm.gz
hiddenmenu
title CentOS (2.6.18-194.el5PAE)
root (hd0,0)
kernel /boot/vmlinuz-2.6.18-194.el5PAE ro root=LABEL=/
initrd /boot/initrd-2.6.18-194.el5PAE.img
As you notice from the above info, it contains kernel and initrd image.
So, in simple terms GRUB just loads and executes Kernel and initrd
images.
3.5.4 Kernel:
Mounts the root file system as specified in the “root=” in grub.conf
Kernel executes the /sbin/init program
Since init was the 1st program to be executed by Linux Kernel, it has
the process id (PID) of 1. Do a „ps -ef | grep init‟ and check the pid.
initrd stands for Initial RAM Disk.
initrd is used by kernel as temporary root file system until kernel is
booted and the real root file system is mounted. It also contains
27
necessary drivers compiled inside, which helps it to access the hard Linux Structure
drive partitions, and other hardware.
3.5.5 Init:
Looks at the /etc/inittab file to decide the Linux run level.
Following are the available run levels
0 – halt
1 – Single user mode
2 – Multiuser, without NFS
3 – Full multiuser mode
4 – unused
5 – X11
6 – reboot
Init identifies the default initlevel from /etc/inittab and uses that to
load all appropriate program.
Execute „grep initdefault /etc/inittab‟ on your system to identify the
default run level
If you want to get into trouble, you can set the default run level to 0 or
6. Since you know what 0 and 6 means, probably you might not do
that.
Typically you would set the default run level to either 3 or 5.
28
Linux Run level 6 – /etc/rc.d/rc6.d/
Please note that there are also symbolic links available for these
directory under /etc directly. So, /etc/rc0.d is linked to /etc/rc.d/rc0.d.
Under the /etc/rc.d/rc*.d/ directories, you would see programs that
start with S and K.
Programs starts with S are used during startup. S for startup.
Programs starts with K are used during shutdown. K for kill.
There are numbers right next to S and K in the program names. Those
are the sequence number in which the programs should be started or
killed.
For example, S12syslog is to start the syslog deamon, which has the
sequence number of 12. S80sendmail is to start the sendmail daemon,
which has the sequence number of 80. So, syslog program will be
started before sendmail.
3.6 SHUTDOWN
The shutdown command brings down system in a secure way. All the
logged-in users are notified about the system shutdown.
Signal SIGTERM notifies all the processes that the system is going down,
so that processes can be saved and exit properly.
Command shutdown signals the init process to change the runlevel.
Runlevel 0 halts the system
Runlevel 6 reboots the system
Runlevel 1 is default state.
Five minutes before shutdown sequence starts, file /etc/nologin is created
when shutdown is scheduled for future which does not allow new user
logins.
If by any reason, command shutdown is stopped before signalling init, this
file is removed. It is also removed to change runlevel before signalling
init.
To run shutdown command root user access is required.
Here you will get information about the active processes on your system.
You will want to pay attention to the PID (unique process ID),
the TIME (amount of time that the process has been running), and
the CMD (the command executed to launch the process).
This would kill all sleep processes active on the system (the -9 option
works here as well). Here is an example:
[tcarrigan@client ~]$ ps
31
PID TTY TIME CMD Linux Structure
To do this, we are going to use the fg command. This brings the most
recently run job/process to the foreground. The following example is a
continuation of the above command. The sleep 500 process that is in the
background is now active in the background. Let's bring it into the light...
[tcarrigan@client ~]$ fg
sleep 500
This command brings us to our final command in this list.
32
Linux through central repositories (which can contain several thousands of
packages, each of which has been specifically built, tested, and maintained
for the distribution) or be available in source code that can be downloaded
and installed manually.
Because different distribution families use different packaging systems
(Debian: *.deb / CentOS: *.rpm / openSUSE: *.rpm built specially for
openSUSE), a package intended for one distribution will not be
compatible with another distribution. However, most distributions are
likely to fall into one of the three distribution families covered by the
LFCS certification.
LOW-LEVEL HIGH-LEVEL
DISTRIBUTION
TOOL TOOL
34
Linux 12. In CLI, spelling mistakes Whereas in GUI, spelling
and typing errors are not mistakes and typing errors are
avoided. avoided.
3.12 BIBLIOGRAPHY
1. Linux Command Line and Shell Scripting Bible, 3rd Edition by
Richard Blum
2. Linux: The Complete Reference, Sixth Edition by Richard Petersen
3. How Linux Works, 2nd Edition: What Every Superuser Should
Know Second Edition by Brian Ward
4. The Linux Command Line: A Complete Introduction 1st Edition
by by William E. Shotts Jr.
5. Fundamentals of Linux by Pelz Oliver
*****
35
UNIT II
4
GRAPHICAL DESKTOP
Unit Structure
4.1 Graphical Desktop
4.2 Session Management
4.3 Basic Desktop Operations
4.4 Network Management
4.5 Installing and Updating Software
4.6 Text editors: gedit, vi, vim, emacs, Graphics editors
4.7 Multimedia applications
X windows is designed for flexibility and there are various ways you can
configure it. on X windows you can run most of the different video cards
available & different graphics cards. The X Windows software is the core
element in presenting graphics. It provides an graphics operations.
To run X-windows, the X free 86 server for appropriate system video card
has to be installed and configuration information provided about your
monitor, mouse and keyboard. This information resides in the
configuration file called /etc/xF86 config. The file uses technical
information that is best generated by an X-windows.
There are two basic elements that control your video environment — the
video card in your PC and your monitor. The X Windows software is a
low-level program that works directly with the video card and monitor in
the PC, and controls how Linux applications can present fancy windows
and graphics on your computer.
36
Linux In the Linux world, there are only two software packages that can
implement it.
The XFree86 software package is the older of the two, and for a long time
was the only X Windows package available for Linux. As its name
implies, it‘s a free open source version of the X Windows software.
A new package called X.org has come onto the Linux scene. It too
provides an open source software implementation of the X Windows
system. Both packages work the same way, controlling how Linux uses
your video card to display content on your monitor. To do that, they have
to be configured for your specific system. During installation it
automatically happens.
The KDE desktop allows you to place both application and file icons on
the desktop area. If you single-click an application icon, the Linux system
starts the application. If you single-click on a file icon, the KDE desktop
attempts to determine what application to start to handle the file.
The bar at the bottom of the desktop is called the Panel. The Panel consists
of four parts:
37
Graphical Desktop
KDE Applications:
KDE Applications
Application Description
amaroK Audio file player
digiKam Digital camera software
K3b CD-burning software
Kaffeine Video player
Koffice E-mail client
Konqueror File and Web browser
Kontact Personal information manager
Kopete Instant messaging client
Application Description:
All of the Panel features are similar to what you would find in Windows.
Besides the desktop features, the KDE project has produced a wide area of
applications that run in the KDE environment.
38
Linux A desktop area for icons.
Two panel areas.
Drag-and-drop capabilities.
GNOME developers have also produced a host of graphical applications
that integrate with the GNOME desktop. As you can see, there are also
quite a few applications available for the GNOME desktop. Besides all of
these applications, most Linux distributions that use the GNOME desktop
also incorporate the KDE libraries, allowing you to run KDE applications
on your GNOME desktop.
Figure shows the standard GNOME desktop used in the Fedora Linux
distribution.
Other Desktops:
The downside to a graphical desktop environment is that they require a
fair amount of system resources to operate properly. In the early days of
Linux, a hallmark and selling feature of Linux was its ability to operate on
older, less powerful PCs that the newer Microsoft desktop products
couldn‘t run on. However, with the popularity of KDE and GNOME
desktops, this hallmark has changed, as it takes just as much memory to
run a KDE or GNOME desktop as the latest Microsoft desktop
environment.
39
programs in them (including more shells), kill the current window, view a Graphical Desktop
list of the active windows, copy text between windows, switch between
windows, etc.
Screen manages a session consisting of one or more windows each
containing a shell or other program. Furthermore, screen can divide a
terminal display into multiple regions, each displaying the contents of a
window. All windows run their programs completely independent of each
other. Programs continue to run when their window is currently not visible
and even when the whole screen session is detached from the user's
terminal. This is practical to prevent involuntary ssh timeout session.
1. Screen:
# screen
You can start a new window within the screen and also gives a name to
the window, for example aloft. It creates a session with identified by that
name. The name can be used to reattach at a later stage.
OnlyFans founder resigns from CEO position
# screen -S aloft
Note that you can do all your work as you are in the normal CLI
environment.
40
Linux Ctrl-a followed by a number from 0 to X: go the windows n° X.
Ctrl-a followed by ": choose the windows into which to move on.
Ctrl-a followed by k: close the current windows (kill)
5. Detaching session:
The best advantage of the screen command is the possibility to detach a
screen session. You can start a screen session on one computer at the
office, detach the session from the local terminal, go home, log into our
office computer remotely and reattach the screen session to our home
computer's terminal. During the intervening time, all jobs on your office
computer have continued to execute. This function is used to prevent the
lost of data which occur suddenly during dropped ssh connection.
To good understand what we are talking about, let us take an example. We
launch an installation process.
Now we will detach the screen with Ctrl-a followed by d. We can check
with the command below.
41
# screen -ls Graphical Desktop
6. Split windows:
To have a global view of your work, you can need to split your windows
instead of having multiple windows. Ctrl-a followed by S or | split your
screen horizontally or vertically. It is possible to repeat the operation with
no limit. To move another windows, use Ctrl-a followed by Tab.
42
Linux
When the cursor is on the bottom windows, you can create a new window
(Ctrl-a followed by c) or call an existing window (Ctrl-a followed by a
number).
3 Sockets in /var/run/screen/S-root.
Reconnect to your screen session and continue your work
# screen -d -r remote_ression
The screen command is most used for ssh session because it helps to
continue your work after a disconnection without losing the current
processes in progress.
Since screen takes over managing your remote programs, you can't use
your terminal emulator's scroll features while running screen. You must
use the Screen commands to access the scrollback buffer.
Press the Up and Down arrow keys or the PgUp and PgDn keys to scroll
through previous output.
You can see where is my cursor on the screenshot. Each virtual terminal
has its own scrollback buffer.
The screen -ls or screen -list commands only show you your own screen
sessions even for root. As far as I know that's as good as it gets for screen
itself.
If you want to see which screen sessions have been started by which users
look in each users directory in /var/run/screen/.
44
Linux
4.3 BASIC DESKTOP OPERATIONS
Desktop Browser Screen Layout
The Desktop Browser screen consists of a "[File] menu", "ribbon",
"windows", and "bars". Documents and folders can be searched on a
separate Search Screen.
[File] menu
Ribbon
Windows
Bars
Search Screen
[File] menu
The [File] menu contains the functions relating to Desktop Browser, such
as printing and scanning, and items regarding the configuration of all of
Desktop.
Ribbon:
The ribbon includes tabs with commands for performing operations on and
editing documents stored in libraries and commands for sending and
receiving faxes and printing materials.
Commands are grouped by function and located on tabs. You can switch
the displayed commands by clicking the tabs.
The following tabs are displayed on the ribbon of Desktop Browser by
default.
[Home]
[Fax]
[Print Meeting Materials]
45
You can also click the following areas of the Navigation Window to Graphical Desktop
display commands related to the area on a tab.
My Tray: Displays the [Edit] tab of the My Tray tool.
Checkout Folder: Displays the [Operations] tab of the document
management tool.
Document Server Library: Displays the [Operations] tab of the document
management tool.
Recycle Bin: Displays the [Manage] tab of the Recycle Bin tool.
NOTE:
You can hide or display the ribbon by clicking (Hide the Ribbon)/
(Display the Ribbon). For information on hiding/displaying the ribbon, see
the following.
Displaying/Hiding Ribbons
If you click (Open Manual), this manual is displayed.
When you use a wheel mouse, you can switch the tabs displayed on the
ribbon by rolling the wheel while above the ribbon.
Ribbons can be customized. For more information, see the following.
Customizing Ribbons
For information on the Navigation Window, see the following.
Navigation Window
46
Linux Windows
Areas of the Desktop Browser screen mainly used for displaying content
are called "windows".
This section describes the "windows" of Desktop Browser.
Navigation Window
File List View Window
Preview Window
Properties Window
You can resize Desktop Browser screen and other windows by
dragging with the mouse.
Navigation Window
The Navigation Window is used to organize multiple libraries and list
the folder structure inside libraries. It also enables you to list saved
search conditions.
The following content is displayed on the Navigation Window of
Desktop Browser.
[Libraries] tab: Displays a tree view of libraries, checkout folders, and
My Tray folders.
[Search Conditions] tab: Displays the saved search conditions.
47
File List View Window: Graphical Desktop
The File List View Window displays the content of the libraries and
folders selected on the Navigation Window. You can change the File List
View Window to the list view or thumbnail view.
You can also add memos to documents on the File List View Window.
NOTE
The list view can be displayed in ascending or descending order.
The thumbnail view can be changed to [Large Thumbnail], [Medium
Thumbnail], and [Small Thumbnail].
You can return the File List View Window to the previous display
with (Back), or move forward with (Forward) on the address
bar. For information on the address bar, see the following.
Address Bar
For more information on how to switch the display format of the File
List View Window, see the following.
Selecting from the File List View Window
Preview Window:
The Preview Window displays a preview of the document selected on the
File List View Window.
48
Linux
NOTE
You can switch between displaying/hiding the Preview Window. For more
information, see the following.
Displaying/Hiding the Preview Window
For information on operating the Preview Window, see the following.
Displaying Documents in the Preview Window
Properties Window:
The Properties Window displays the information (properties) of the
document or folder selected on the Navigation Window or File List View
Window.
49
NOTE Graphical Desktop
Bars
Areas of the Desktop Browser screen mainly used for operations and with
items arranged horizontally or vertically are called "bars".
This section describes the "bars" of Desktop Browser.
Address Bar
Simple Search Bar
Toolbar
Output Bar
Status Bar
Address Bar
The address bar shows the path of a selected library, My Tray, or folder.
You can also click (Back), (Forward), (Up), (Refresh),
or (Go) on the address bar to switch the view of the File List View
Window.
50
Linux
NOTE
Toolbar:
The toolbar enables you to set frequently used ribbon commands on the
toolbar.
51
NOTE Graphical Desktop
For information on the ribbon commands that can be set as buttons on the
toolbar, see the following.
Customizing Toolbars
Output Bar:
The output bar enables you to configure settings for linkage with
applications and devices and use them. You can also use it for specifying
shared folders and circulating documents.
NOTE
The output bar can be customized. For more information, see the
following.
Status Bar:
The status bar displays the number of files selected on the File List View
Window. If no files are selected, the status bar displays the total number of
folders and files displayed on the File List View Window.
52
Linux
Search Screen
The Search Screen displays the results of searching from the simple search
bar.
The Search Screen also provides the items for configuring detailed search
conditions, performing a search, and saving search conditions.
53
NOTE Graphical Desktop
To display the Search Screen always in front of the Desktop Browser
screen, click (Display in Front of Browser) to make it . Click it
again to cancel.
For information on searching for documents and folders in Desktop
Browser, see the following.
Searching for Documents/Folders
$ ping garnet
Output: no answer from garnet
Remote Access Permissions (rhosts): To control the access to our system
(from other users who are using TCP/IP) we use rhosts file. To achieve
communication between you and others the rhosts file on both system
(yours and others) should have each others system name and login name.
The rhosts file which is located in users home directory is a simple way to
54
Linux allow people access to your account without giving out your password. To
deny access to a user, simply delete the user‘s system name and login
name from your rhosts file
$ cat .rhosts
Output: garnet chris
Violet Robert
Remote Login: It is quite possible that we have no of account on different
systems in a network. If sitting on one system if we want to log into our
account on other system on a network then it can be done with rlogin
command. rlogin command takes system name as argument. $ rlogin
violet
As soon as we execute the rlogin command we are immediately prompted
for the password. During executing this command we have passed only the
system name but not the login name. This is because rlogin command
assumes that the login name on your local system is same as that login
name on the remote system.(login name on local system means the login
name of current system on which you are currently working). But suppose
that you are having different login name on remote system then we use the
following command.
$ rlogin system-name – l login-name: (-l option is used to specify the
login name on remote system is different from the current system).
$ rlogin violet – l robert: (The user logs into the system violet using login
name robert).
Remote file copy (rcp): The rcp command is used to copy files to and
from remote and local systems. rcp is a file transfer utility that operates
like the cp command but across the network. The rcp command requires
that the remote system have your local system name and login name in its
.rhosts file. The syntax is as follows:
55
$ rcp –r source-directory remote-system-name:copy-directory Graphical Desktop
TCP/IP commands:
(1) You can find out who is logged in, get information about a user an
another system.
$ rwho
56
Linux violet Rebert: tty I sept 10 10:34
garnet cris: tty 2 sept 10 29:22
(2) The ruptime command displays information about each system on
your network
$ ruptime
Violet up 11+04:10 8 users load 1:20 1:10 1:00 ruptime shows
whether a system is up or down, the number of users on the system,
and the average load on the system for the last 5, 10 and 15 minutes.
(3) The ping command detects whether or not a system is up and running.
The ping command takes as its argument the name of the system you
want to check.
57
In the next example, the user copies the file Wednesday from the remote Graphical Desktop
system violet to his own system and renames the file today.
$ rcp violet : Wednesday today.
(6) At times, you may need to execute a single command on a remote
system. The rsh command will execute a linux command on another
system and display the results on your own.
The rsh command takes two general arguments, a system name and a
Linux command.
58
Linux (2) Network Address:
You can easily figure out the network address using your host address. It
is a network part of your host address; with the host part set to 0.50 the
network address for the host address 199.35.209.72 is 199.35.209.0
Therefore system device the network address form the host address using
the netmask.
(6) Netmask:
The netmask is used to derive the address of the network you are
connected to. The netmask is determined using your host address as a
template. All the numbers in the network part of your host address are set
to 255, and the host part is set to 0. This, then is your netmask. So the
netmask for the host address is 199.35.209.72 is 255.255.0. The network
part 199.35.209, has been set to 255.255.255 and the host part, 72 has
59
been set to 0. Systems can then use your netmask to derive your network Graphical Desktop
address from your host address. They can determine what part of your host
address makes up your network address and what those numbers are.
File Function
/etc/hosts Associates hostnames with IP addresses
Associates domain names with network
/etc/networks
addresses
Contain commands to configure your
/etc/rc.d/init.d/inct
network interface when you boot up
/etc/HOSTNAME Holds the hostname of your system
/etc/host.conf Resolves options
/etc/resolu.conf Contains list of domain nameservers
60
Linux (9) Network Name: /etc/networks:
The /etc/networks file holds the domain names and IP addresses of
networks that you are connected to, not to domain names of particular
computers. Every IP address consists of a network part and a host part.
The network part is the network address you will find in the networks file.
You will always have an entry in this file for the network portion on your
computer‘s IP address. This is the network address of the network, your
computer is connected to.
/etc/HOSTNAME:
The /etc/HOSTNAME file holds your system‘s hostname. To change your
hostname, you change this entry. The netcfg program allows you to
change your hostname and will place the new name in /etc/HOSTNAME.
Instead of displaying this file to find your hostname, you can use the
hostname command.
$ hostname
turtle.trek.com
Ifconfig:
The ifconfig command takes as its arguments the name of an interface and
an IP address as well as options. Ifconfig then assigns the IP address to the
interface. Your system now knows that there is such an interface and that
it references a particular IP address. In addition, you can specify whether
the IP address is a host of network address. You can use a domain name
for the IP address, provided the domain name is listed along with its IP
address in the /etc/hosts file. The syntax for the ifconfig command is as
follows.
# ifconfig interface – host – net – flag address options.
The host – net – flag can be either – host or – net to indicate a host or
network IP address.
In the next example, the ifconfig command configures an Ethernet
interface.
61
# ifconfig etho 204.32.168.56 Graphical Desktop
The ifconfig command can have several options, which set different
features of the interface, such as the maximum number of bytes. It can
transfer (mtu) or the broadcast address. The up and down option activate
and deactivate the interface.
The ifconfig command is very useful for checking on the status of an
interface if you enter the ifconfig command along with the name of the
interface, information about that interface is displayed
# if config etho
Routing:
A packet that is part of transmission takes a certain route to reach its
destination. On a large network, packets are transmitted from one
computer to another until the destination computer is reached. The route
determines where the process starts and what computer your system needs
to send the packet to in order for it to reach its destination. On small
network routing may be static, that is, the route from one system to
another is fixed. One system knows how to reach another, moving through
fixed paths. However, on larger networks and on the Internet, routing is
dynamic. Your system knows the first computer to send its packet off to,
and then that computer takes it from there, passing it on to another that
then determines where to pass it on to. For dynamic routing, your system
needs to know very little. Static routing however can become very
complex, since you have to keep track of all the network connections.
Your routes are listed in your routing table in the /proc/net/route file. To
display the routing table, enter route with no arguments.
# route
kernel routing table:
Destination Gateway Fenmas flag metri Ref Use Ifac
k s c e
Loopback * 255.0.0 U 0 0 12 Lo
.0
Pongol.train.c 255.255.25 U 0 0 0 0 etho
om 5.0
Field Description
Destination Description IP address of the route
IP address or hostname of the gateway the route
Gateway
uses * indicates no gateway is used.
Genmask The network for the route
Type of route: U = up, H = host, G = Gateway, D =
Flags
dynamic, M = modifies.
62
Linux Metric Metric cost of route
Ref Number of routes that depend on this one
Window TCP window for Ax.25 networks.
Use Number of times used
Iface Type of interface this route uses
You should have at least one entry in the routing table for the loopback
interface. If not, you will have to route the loopback interface using the
route command. The IP address for an interface has to be added to the
routing table before you can use that interface. You add an address with
the route command and the add option.
Field Description
Proto Protocol used for the connection: TCP, UDP
Recu-Q Bytes received but not yet used by the system
Bytes sent to remote system, but not yet confirmed as
Send-Q
received.
Local
Local hostname and port number
Address
Foreign Remote hostname and port number assigned to a
Address connection, port number can be connection type, such
63
as telnet or ftp. Graphical Desktop
(State) State of connection to remote host
ESTABLISHD, connection established
SYN_SENT, trying to make connection
SYN_REC, connection being created
Fin_WAIT1, connection shutting down
CLOSED, connection closed
LISTEN, listening for remote connection
UNKNOWN, unknown state
Domain socket:
Proto protocol for socket, usually unix
RefCnt number of processes currently in socket
Flag
You can use netstat with the –r option to display the routing table, and
netstat with the –i option displays the us are for the different network
interfaces. The following table explains the coded information.
# netstat –i
kernel interface table:
Iface Mtu met Rx- Rx- Rx- Rx- Tx- Tx- Tx- Tx- flags
OK ERR DRP OUR OK ERR DRP OVR
LO 2000 0 0 0 0 0 58 0 0 0 BLRU
64
Linux Flags Interface Characteristics
A Receives packets for multicast addresses
B Receives broadcasts
D Debugging is on
I Loopback interface
M Promiscuous mode
N No trailers processed on packets
O Address resolution protocol is off
P Point-to-point interface
R Interface is running
U Interface is activated, up
65
administrator or another user can access someone else's computer Graphical Desktop
remotely. On the Web, HTTP and FTP protocols allow you to request
specific files from remote computers, but not to actually be logged on as a
user of that computer. With Telnet, you log on as a regular user with
whatever privileges you may have been granted to the specific application
and data on that computer.If you have an account on a host in local
network, you can use telnet with the hostname or IP address as argument:
$ telnet 192.168.35.12
Connected to 192.168.35.12
Login:
Now user can enter the Login name at this prompt and then the password
to gain access to the remote machine. After login you can work on any
command at remote location.
telnet> !ls –l
4.4.4 FTP:
ftp command can also be used with or without arguments.
ftp ip-address
After establishing a connection with the destination, ftp prompts for the
username and password. The local username is prompted as default and if
pressed enter, the system would have logged in as default. Termination of
ftp is done in two stages. Firstly one has to disconnect from the remote
machine with close and then quit ftp either with bye or quit. ftp has all the
basic facilities needed to handle files and directories On the remote
machine like pwd, ls, cd, mkdir, rmdir, chmod. User can delete single file
with delete and multiple files with mdelete or rename a file(rename).
Transferring files:
For the purpose of transfer files can be seen as belonging to two types-
ascii and binary. All executables, graphics, word processing and
multimedia files belong to binary type. Uploading of files is done with put
for single file and for multiple files mput. For downloading get for single
file and mget for multiple files.
ftp displays the ftp> prompt when used without argument. Then
connection can be established with open command.
ftp works in two stages. First it makes a connection with a remote
machine. This is done by invoking ftp with the hostname or later with the
open command. After the connection has been established, ftp asks for the
username and password. To login after this user command is used along
with the username.
66
Linux Anonymous ftp:
On the internet there are several sites which offer trial and public domain
software for downloading. Where a separate account is not there for every
user. These sites offer a special user account ―anonymous‖ that has to be
used for logging in. these sites are known as anonymous ftp sites. User can
only download files from an anonymous site.
67
Types of RPM Packages: Graphical Desktop
[name]-[version]-[release].[arch].rpm
Where,
[name] is the name of the program or package. The [name] is usually
assigned by the program‘s author. In our example, the developers decided
to name their product ―bash‖ for reasons that seemed amusing to them.
version] identifies which edition of the software this RPM contains. The
[version] number is assigned by the program‘s author. Using the number
allows one to determine which version of the author‘s sources were used
to generate the RPM.
[release] provides the edition number of the RPM file itself and not the
version of the author‘s source files. An updated RPM may be issued to
supply a patched version of the author‘s original software. The patch need
68
Linux not have come from the original developer, so the RPM [release] gets
incremented instead of the [version].
[arch] describes the contents of the RPM and tells whether this file
contains the product source (a ―.src.rpm‖), architecture-independent files
(a ―.noarch.rpm‖), or files which may only be installed on a particular host
type (a ―.sh.rpm‖ will work only on a STRONGHOLD embedded
processor).
Installing and Removing Files
Note: Usually only one or of an RPM may be installed at once.
Later versions are usually installed using the ―-U‖ (update) RPM function
instead of the ―-i‖ RPM function. Common exceptions to the only-one
RPM rule are the kernel RPM‘s. A system commonly has several versions
of kernels installed; RPM has a list of which RPM‘s may have multiple
versions installed. To delete one version when several are installed, you
must fully-specify the package name and version.
On the x86_64 architecture, it is common to have both the 32-bit ―.i386‖
and the 64-bit ―.x86_64‖ RPM packages installed tosupport both 32-bit
and 64-bit applications. Normally, RPM does not display the architecture
of a package on a query but you can manually display it.
Examples:
# rpm -ivh binutils-2.11.90.0.8-12.i386.rpm
# rpm -Uvh finger-0.17-9-i386.rpm
# rpm -Fvh ftp://updates.redhat.com/current/i386/*.rpm
# rpm -e diffutils
# rpm -e kernel-enterprise-2.4.9-e.12
69
Hint: Never, ever, use the ―-U‖ option to install a new kernel RPM. The ―- Graphical Desktop
U‖ update function first deletes the current RPM from the system and then
attempts to install the new RPM. Any problem that prevents the new RPM
from installing will leave the system unbootable. This is not what you
want, so always use the ―-i‖ switch to install a kernel RPM.
Examples:
# rpm -qa
# rpm -q kernel -i (information)
# rpm -q kernel -l (files contained in package)
# rpm -q kernel --requires (prereqs)
# rpm -q kernel --provides (capabilities provided by package)
# rpm -q kernel --scripts (scripts run during installation and removal)
# rpm -q kernel --changelog (revision history)
# rpm -q kernel -queryformat format (rpm --querytags for list of options)
70
Linux # rpm -Va (verify all)
# rpm -Vf (filename)
# rpm -Vp (package filename)
4.6.1 Gedit:
gedit is a full-featured text editor for the GNOME desktop environment.
You can use it to prepare simple notes and documents, or you can use
some of its advanced features, making it your own software development
environment.
Once gedit launches, you can start writing right away. To save your text,
just click the Save icon in the gedit toolbar.
71
Tab-related Shortcut keys: Graphical Desktop
72
Linux Shortcut keys for editing files:
Open the Replace tool by clicking Menu button ▸ Find and Replace… or
press Ctrl+H.
Enter the text that you wish to replace into the Find field.
Enter the new, replacement text into the Replace with field.
Once you have entered the original and replacement text, you can add
extra parameters to the search. You can also choose what you want to
replace:
To replace only the next match, click Replace.
To replace all occurrences of the searched-for text, click Replace All.
Print Preview:
Prior to printing your document, you can preview how the printed
document will look by using Print Preview. To preview the document:
Printing To Paper:
You can print your documents to paper using a local or remote printer. To
print a file:
You can preview the file using Print Preview and once you are satisfied
with the settings, click Print to send the file to printer.
Printing To File:
You can also use gedit to print to a file. To print your document to file of a
different format:
Printing is enabled for the following file formats, you may select from:
Portable Document Format (.pdf)
PostScript (.ps)
Scalable Vector Graphic (.svg)
To print the document to file, click Print
74
Linux Create a new file:
The easiest way to create a new file in gedit, is to click the Create a new
document button on the left side of the toolbar, or press Ctrl+T.
Any one of these actions will create a new file in the gedit window. If you
have other files open in gedit, the new file that you create will appear as a
new tab to the right of those files.
Save a file:
To save a file in gedit, click on the Save button on the right side of the
toolbar or just press Ctrl+S.
If you are saving a new file, a dialog will appear, and you can select a
name for the file, as well as the directory where you would like the file to
be saved.
75
Modes of vi editor: Graphical Desktop
1. Command Mode:
Command Mode is the first screen of VI editor. It is case sensitive. Any
character that is typed during this mode is treated as a command. These
are character are not visible on the window. We can cut, copy, paste or
delete a piece of text or even move through the file in this mode
[ESC] used to enter the Command Mode from another mode (Insert
Mode)
2. Insert Mode:
We can easily move from Command mode à Insert mode by pressing ‗i‘ or
‗Insert‘ key from the keyboard. Characters typed in this mode is treated as
input and add text to your file
Pressing ESC will take you from Insert Mode -> Command Mode
3. Escape Mode
Press [:] to move to the escape mode. This mode is used to save the files &
execution of the commands
76
Linux 2. Moving out of a file:
:q Quit out of a file
:q! Quit the file without saving the changes
:w Save the content of the editor
:wq Save the changes and quit the editor (*Combing the commands: q &:
w)
ZZ In command mode, this works similar to wq
3. Rename a File:
:w newFileName – This will rename the file that you are currently
working into ‗new filename‘. A command is used in Escape Mode.
77
o Open & places the text in a new line below the current line Graphical Desktop
O Open & places the text in a new line above the current line
4.1.6.3 Emacs:
GUI text editors and coding environments and are not used to a primarily
text-based program, running commands in the editor itself, and/or using
large amounts of keyboard shortcuts.
List of shortcuts
C-h C-h : help
C-g : quit
C-x b : switch buffers
C-x right : right-cycle through buffers
C-x left : left-cycle through buffers
C-x k : kill buffer
C-x 0 : close the active window
C-x 1 : close all windows except the active window
C-x 2 : split the active window vertically into two horizontal windows
C-x 3 : split the active window horizontally into two vertical windows
C-x o : change active window to next window
78
Linux C-x C-f : open file
C-x C-s : save file
C-x C-w : save file as
C-space : set region mark
C-w : kill region
C-k : kill region between point and end of current line
M-w : kill region without deleting
C-y : yank region from kill ring
M-y : move to previous item in the kill ring
M-Y : move to next item in the kill ring
C-_ : undo
C-s : search forwards
C-r : search backwards
M-% : query replace (‗space‘ to replace, ‗n‘ to skip, ‗!‘ to replace all)
M-q : wrap text
C-left : move one word left
C-right : move one word right
C-up : move one paragraph up
C-down : move one paragraph down
home : move to the beginning of the line
end : move to the end of the line
page up : move up a page
page down : move down a page
M- : move to end of buffer
Opening Emacs:
When you first open Emacs, you will see a window that looks something
like this.
79
Graphical Desktop
Features:
Remembers last played position
Supports all major video formats including MPEG, DivX, AVI,
Quicktime, WMV, FLV etc.
80
Linux Also support Bit torrent file download.
Features:
Remembers last played position
Supports all major video formats including MPEG, DivX, AVI,
Quicktime, WMV, FLV etc.
Also support Bit torrent file download
3) UMPlayer:
UMPlayer stands for Universal Media Player as it can play all kinds of
media formats and also platform independent. The user interface is
aesthetically pleasing, simple and easy to use. It is licensed under the
GNU license and is free to download. You can also watch YouTube
videos on the UMPlayer.
81
Graphical Desktop
Features:
Search and play YouTube Videos
Supports almost 270 media formats including AC3, AVI, WMV, Mp4,
MPEG, XVID etc.,
You can also record YouTube Videos using UMPlayer
Skinnable Interface
Remember media position
Localization support
4) DigiKam:
DigiKam is an advanced photo editing and management software
available for all major operating systems including Linux, Windows and
Mac OS. The people behind the creation of DigiKam are real professional
photographers who saw the need to developing an application that can
enable them to view, edit and organize their pictures and also tag and
share them with other people through social media.
*****
82
5
COMMAND LINE
Unit Structure
5.1 Command Line
5.2 Shell
5.3 Basic Commands
5.4 General Purpose Utilities
5.5 Installing Software
5.6 User management
5.7 Environment variables
5.8 Command aliases
5.9 Summary
5.10 Unit End Questions
5.11 List of References
The current directory (the tilde sign (~) is shorthand for the home
directory) i.e. Absoulte path of Home.
83
Directory: Command Line
$ psl = “”
Example 2:
$psl = “\w>”
~> cd/user/doc
/usr/doc>
~ (tilde) sign will indicate current working directory absolute path
Example 3:
$ psl = “\t\!”
This will display time & current history no. followed by
84
Linux ps2:
Ps2 is a Secondary prompt it appears when 1st prompt value of the
command is incomplete by pressing ctr +Z to exit command$ echo “This
is incomplete command (Enter)
You can change the secondary prompt
$ ps2 = „^‟
$ ps2 will change to „^‟
$ ps2 = “@”
$ echo”
@
@
To display the current settings for your prompts, use the echo command:
rich@1[~]$ echo $PS1
It displays the current primary prompt of the system.
(Eg. \u@\l[\W]\$)
rich@1[~]$ echo $PS2
It displays the secondary prompt of the system. (Eg. >)
rich@1[~]$
The shell uses special characters to signify elements within the command
line prompt. Following:
List shows the special characters that you can use in the prompt string.
Bash Shell Prompt Characters:
Character Description
\a The bell character
\d Current date in the format ‘‘Day Month Date’’
\e The ASCII escape character
\h The local hostname
\H The fully qualified domain hostname
\j The number of jobs currently managed by the
shell
\l The basename of the shell’s terminal device
name
\n The ASCII newline character
\r The ASCII carriage return
\s The name of the shell ie. Shell currently active
\t The current time in 24-hour HH:MM:SS format
85
\T The current time in 12-hour HH:MM:SS format Command Line
\@ The current time in 12-hour am/pm format
\u The username of the current user
\v The version of the bash shell
\V The release level of the bash shell
\w The current working directory
\W The basename of the current working directory
\! The bash shell history number of this
command ie. Current history number.
\# The command number of this command
\$ Use a dollar ($) sign if a normal user, or a
pound sign (#) if the root user
\nnn The character corresponding to the octal value
nnn
\\ A backslash
\[ Begins a control code sequence
\] Ends a control code sequence
Notice that all of the special prompt characters begin with a backslash (\).
The prompt contained both prompt characters and a normal character. You
can create any combination of prompt characters in your prompt. To create
a new prompt, just assign a new string to the PS1 variable:
[rich@testbox ~]$ PS1="[\t][\u]\$ "
[14:40:32][rich]$
This new shell prompt now shows the current time(\t), along with the
username(\u), along with that $ sign indicates the normal user. The new
PS1 definition only lasts for the duration of the shell session. When you
start a new shell, the default shell prompt definition is reloaded.
5.2 SHELL
The GNU/Linux shell is a special interactive utility.It is a program started
after you log on to the LINUX. It provides a command line interface or
shell between user & LINUX kernel. Hence it is called as fundamental
interface to O.S “Kernel”. The core of the shell is the command prompt.
The command prompt is the interactive part of the shell.
Typed „cmds are interpreted by the shell & send to the kernel which in
turns open, closes, reads or writes files. The shell runs like any other
program under the LINUX system. A shell is simply a macro processor
that executes commands that you enter at the command prompt. A Linux
shell is understood to be both a command interpreter and a programming
language. You can enter the commands at the command prompt (#) and
the shell will run them. If you have several commands that you need to
run, you can put them in a special text file called a script file and the shell
will run it also.
86
Linux There are quite a few Linux shells available to use on a Linux system.
Different shells have different characteristics, some being more useful for
creating scripts and some being more useful for managing processes. The
default shell used in all Linux distributions is the bash shell. The bash
shell was developed by the GNU project as a replacement for the standard
Unix shell, called the Bourne shell (after its creator).
Linux Shells:
There are no. of shells available for linux:
1. Bash shell (Bourne again shell)
2. C shell
3. Korn shell
4. Restricted shell
5. Bourne shell
6. Tcsh shell
7. A shell
8. Z shell
9. PDKSH shell (public domain kom shell)
2. C shell:
This is another and processor developed by William joy it gets it‟s
name from its programming language in syntax.
This C shell is not compatible with bourne shell.
The C shell was developed to provide a programming interface
similar to C programming language.
The name of executable file is esh.
87
The executable file name is ksh. Command Line
4. Restricted shell:
When you want use of O.S. to have limited access to LINUX serve to
restricted shell is used & it is typically used for guest users who are not
part of system &insurance installation where users must be restricted to
work only in their own limited environment. These are called rsh shells.
5. Bash shell:
Bash is known as Bourne again shell. It was written by Stephen
Bourne. It is an enhancement of Bourne shell since bourne shell is
default shell of Unix which is already registerd hence Linux O.S legally
can‟t use bourne shell of Unix. Hence this bourne shell is newly created
with modification in bourne shell of Unix hence it is called as bourne
again shell. It is a default shell of most Linux system. The Bash shell is
executed as /bin/bash.
A simple, lightweight shell that runs in low-memory environments.
6. Tcsh:
Tcsh stands for Tom‟s C shell. Also known as Tc shell. It is
enhancement of C shell. The symbolic link available for Tcsh shell on
Linux is csh. You can execute Tcsh shell by typing either csh or tcsh.
At cmd prompt. The C & Tc shell are not compatible with bourne
shell.
A shell that incorporates elements from the C programming language
into shell scripts
7. A shell:
The A shell (ash) was developed by “Kenneth alnquist”. It is light
weight bourne shell. It is usually suitable for computers that have very
limited memory. This is a light weight Bourne compatible shell.
88
Linux 8. Z shell:
The Z shell can be executed by zsh. It has best features of Tesh set
shell. Also it has features of korn shell& having large no. of utilities &
extensive documentation. It is designed for interactive use with a
powerful scripting language. An advanced shell that incorporates
features from bash, tcsh, and korn, providing advanced programming
features, shared history files, and themed prompts.
mv filename
Renames the file to a new filename
new_file_name
wc Word Count
89
5.4 GENERAL PURPOSE UTILITIES Command Line
90
Linux Firstly, any Linux user should be aware of such thing as software
repositories. Repository is storage for packages (both source and binary)
accessible via Internet to install any required software on your computer.
You can easily select which to use or even create your own one: the list of
connected repositories is stored here by default (examples for the most
popular utilities):
– YUM: in files repo in the directory /etc/yum.repos.d/;
– APT: in file /etc/apt/sources.list and in the files in the directory
/etc/apt/source.list.d/.
#1) Redhat RPM is common for Linux free software package management
tool developed by Red Hat. This method is popular because users don‟t
need to compile the code by themselves. The software is ready to be
installed and you can find a brief instruction below.
As for RPM, user needs to perform the extraction of files by already
defined options (such as destination, name etc.) which are hidden within
the responsible utilities (rpm, yum). Installing RPM packages is fairly
straight forward. To install such software package, you can run the
following command: rpm -i RPMPackage.rpm.
An alternative tool here is yum: the main difference is automatic upgrades
and package management (including necessary dependencies). YUM is
analog for APT (DEB packages) and manage repositories. Example: yum
install RPMPackage.rpm; yum update RPMPackage.rpm; yum remove
RPMPackage.rpm.
#2) Debian packages are almost the same as RPM but for usage in Debian
GNU/Linux systems. Obviously, the extension of such packages are *.deb.
To install such packages (whether source or binary) use APT (Advance
Packaging Tool). This is package management system for Debian and also
includes a lot of different tools. So, installing new software will be quite
simple as well: just run the command apt-get install DEBPackage.deb. Just
for understanding the common flow, here is an example: apt-get update
DEBPackage.deb; apt-get remove DEBPackage.deb.
#3) Tarballs is so-called archives distributed with the following extensions
“.tar.gz”, “.tar.bz2”, or “.zip” (there are even more regarding the type of
compression and archivers). Originally tarballs are used for programs
which are not compiled, i.e. they are presented as source code. That‟s why
there significant differences how to install software this way. The main
idea here: if you cannot find your program in the repositories, just
download the source code from any open source program website and then
install it according simple instruction below.
To extract data form such tarballs we should use the corresponding
commands. Some variants are below:
91
for files ending in .tar.bz2, run: tar -jxvf <TarBallName>, Command Line
Home directory- the dir where the user ends up on logging in. the
variable HOME is set by the login program by reading this field.
Login shell – the first program executed after logging in. this is
usually the shell. Login also set the variable shell by reading this
entry, and also fork-execs the shell process.
For every line in /etc/passwd, there‟s a corresponding entry in
/etc/shadow. The relevant line in this file could look something like this:
Oracle:sdfsdfsdfsd:12032::::::::
The password encryption is shown in the second field.
92
Linux /dev:
Devices are also files. One can open a device, read and write to it and then
close it like any other file. The functions for doing all this is built into the
kernel for each and every device of the system. The same device can often
be accessed with several different filenames. All device files are stored in
/dev or in its subdirectories. The device files can be grouped into mainly
depending on the first char of the permission field. It does have the
following dirs., cdrom, default floppy drive, first hard disk, printer, tape
drive and terminal.
There are two kinds of devices exist block devices and char devices. For
both these types of devices, the device file exist in the /dev dir.
$ cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
94
Linux (8) The date (stored as the number of days since January 1, 1970) since
the user account was disabled.
(9) A field reserved for future use.
Using the shadow password system, it can control how often a user must
change his or her password, and when to disable the account if the
password hasn‟t been changed.
95
(7) The system will create a file in the mail directory for the user account Command Line
to receive mail.
The next-to-the-last value is interesting. The useradd command allows an
administrator to create a default HOME directory configuration, then uses
that as a template to create the new user‟s HOME directory. This allows
you to place default files for the system in every new user‟s HOME
directory automatically. On my Linux system, the /etc/skel directory has
the following files:
# ls -al /etc/skel
total 48
drwxr-xr-x 2 root root 4096 2001-11-01 00:23 .
drwxr-xr-x 107 root root 12288 2007-09-20 16:53
..
-rw-r--r-- 1 root root 33 2007-02-12 10:18
.bash_logout
-rw-r--r-- 1 root root 176 2007-02-12 10:18
.bash_profile
-rw-r--r-- 1 root root 124 2007-02-12 10:18
.bashrc
The useradd command created the new HOME directory, using the files in
the /etc/skel directory.
96
Linux -M Don‟t create a user‟s HOME directory (used if the default setting is to
create one).
-n Create a new group using the same name as the user‟s login name.
-r Create a system account
-p passwd Specify a default password for the user account.
-s shell Specify the default login shell.
-u uid Specify a unique UID for the account.
Removing a user:
If you want to remove a user from the system, the userdel command is
what you need. By default, the userdel command only removes the user
information from the /etc/passwd file.
It doesn‟t remove any files the account owns on the system.
If you use the -r parameter, userdel will remove the user‟s HOME
directory, along with the user‟s mail directory. However, there may still be
other files owned by the deleted user account on the system. This can be a
problem in some environments.
Here‟s an example of using the userdel command to remove an existing
user account:
# /usr/sbin/userdel -r test
# ls -al /home/test
ls: cannot access /home/test: No such file or
directory
usermod:
The usermod command is the most robust of the user account modification
utilities. It provides options for changing most of the fields in the
/etc/passwd file. To do that you just need to use the command line
97
parameter that corresponds to the value you want to change. The Command Line
parameters are mostly the same as the useradd parameters (such as -c to
change the comment field, -e to change the expiration date, and -g to
change the default login group). However, there are a couple of additional
parameters that might come in handy:
chpasswd:
The chpasswd command reads a list of login name and password pairs
(separated by a colon) from the standard input, and automatically encrypts
the password and sets it for the user account.
98
Linux chsh, chfn, and chage:
The chsh, chfn, and chage utilities are specialized for specific functions.
The chsh commandallows you to quickly change the default login shell for
a user. You must use the full pathname for the shell, and not just the shell
name:
# chsh -s /bin/csh test
# chfn test:
Changing finger information for test.
Name []: Ima Test
Office []: Director of Technology
Office Phone []: (123)555-1234
Home Phone []: (123)555-9876
Finger information changed.
# finger test:
Login: test Name: Ima Test
99
Directory: /home/test Shell: /bin/csh Command Line
All of the finger information is neatly stored away in the /etc/passwd file
entry.
Finally, the chage command helps us manage the password aging process
for user accounts.
There are several parameters to set individual values, shown in Table 6-4.
The chage date values can be expressed using one of two methods:
d Set the number of days since the password was last changed.
W Set the number of days before the password expires that a warning
message appears.
101
5.7.1 Setting Environment Variables: Command Line
Once you start a bash shell (or spawn a shell script), you‟re allowed to
create local variables that are visible within your shell process. You can
assign either a numeric or a string value to an environment variable by
assigning the variable to a value using the equal sign:
$ test=testing
$ echo $test
testing
If you need to assign a string value that contains spaces, you‟ll need to use
a single quotation mark to delineate the beginning and the end of the
string:
$ test=testing a long string
-bash: a: command not found
$ test=’testing a long string’
$ echo $test testing a long string
Note: It’s extremely important that there are no spaces between the
environment variable name, the equal sign, and the value. If you put any
spaces in the assignment, the bash shell interprets the value as a
separate command:
$ test2 = test
-bash: test2: command not found
Once you set a local environment variable, it‟s available for use anywhere
within your shell process. However, if you spawn another shell, it‟s not
available in the child shell:
$ bash
$ echo $test
$ exit
exit
$ echo $test
testing a long string
$
The test environment variable is not available in the child shell (it contains
a blank value)
102
Linux Similarly, if you set a local environment variable in a child process, once
you leave the child process the local environment variable is no longer
available:
$ bash
$ test=testing
$ echo $test
testing
$ exit
exit
$ echo $test
After exporting the local environment variable test, I started a new shell
process and viewed the value of the test environment variable. This time,
the environment variable kept its value, as the export command made it
global.
Variable Description
CDPATH A colon-separated list of directories used as a
search path for the cd command.
HOME The current user‟s home directory.
IFS A list of characters that separate fields used by the
shell to split text strings.
MAILPATH A colon-separated list of multiple filenames for the
current user‟s mailbox. The
OPTARG The value of the last option argument processed by
the getopts command.
PATH A colon-separated list of directories where the shell
looks for commands.
PS1 The primary shell command line interface prompt
string.
PS2 The secondary shell command line interface
prompt string.
104
Linux MAIL The filename for the current user‟s mailbox. The
bash shell checks this file
For new bash shell checks each file in this list for new mail.
mail.
OPTIND The index value of the last option argument
processed by the getopts command
This shows that there are six directories where the shell looks for
commands. Each directory in the PATH is separated by a colon. There‟s
nothing at the end of the PATH variable indicating the end of the directory
listing.
PATH environment variable without having to rebuild it from scratch. The
individual directories listed in the PATH are separated by a colon. All you
need to do is reference the original PATH value, and add any new
directories to the string.
This looks something like this:
$ echo $PATH
/usr/kerberos/bin:/usr/lib/ccache:/usr/local/bin:
/bin:/usr/bin:/home
/rich/bin
$ PATH=$PATH:/home/rich/test
$ echo $PATH
/usr/kerberos/bin:/usr/lib/ccache:/usr/local/bin:
/bin:/usr/bin:/home
/rich/bin:/home/rich/test
$ myprog
The factorial of 5 is 120.
105
5.7.5 Locating System Environment Variables: Command Line
/etc/profile
$HOME/.bash profile
$HOME/.bash login
$HOME/.profile
The /etc/profile file is the main default startup file for the bash shell.
Whenever you log in to the Linux system, bash executes the commands in
the /etc/profile startup file.
The remaining three startup files are all used for the same function to
provide a user-specific startup file for defining user-specific environment
variables.
106
Linux Second, it provides a place for the user to enter personal aliases and
private script functions.
The common/etc/bashrc startup file is run by everyone on the system who
starts an interactive shell session.
Only the first value in the array appears. To reference an individual array
element, you must use a numerical index value, which represents its place
in the array. The numeric value is enclosed in square brackets:
$ echo ${mytest[2]} three
107
Change the value of an individual index position: Command Line
$ mytest[2]=seven
$ echo ${mytest[*]}
one two seven four five
$
use the unset command to remove an individual value within the array
$ unset mytest[2]
$ echo ${mytest[*]}
one two four five
$
$ echo ${mytest[2]}
$ echo ${mytest[3]}
four
This example uses the unset command to remove the value at index value
2. When you display the array, it appears that the other index values just
dropped down one. However, if you specifically display the data at index
value 2, you‟ll see that that location is empty.
Remove the entire array just by using the array name in the unset
command:
$ unset mytest
$ echo ${mytest[*]}
108
Linux alias which=’alias | /usr/bin/which --tty-only --
readalias--
show-dot --show-tilde’
Once you define an alias value, you can use it at any time in your shell,
including in shell scripts.
Command aliases act like local environment variables. They‟re only valid
for the shell process in which they‟re defined:
$ alias li=’ls -il’
$ bash
$ li
5.9 SUMMARY
This chapter consist of different types of shell in command line, How to
install rpm packages with the help of yum, different files when we create a
user, command with options, how to change password of the user using
passwd , different types of environment variables.
109
C shell Command Line
Korn shell
Restricted shell
Bourne shell
Tcsh shell
A shell
Z shell
2. How many GNU coreutils package are available? Explain any one of
them.
3. Differentiate rpm and yum.
4. Write the contain of /etc/passwd file.
5. Describe/etc/shadow file
6. Describe useradd Parameter
7. How to change password of the particular user.
8. Explain types of environment variables in the bash shell.
9. Explain how to setup and removing Environment Variables.
10. Describe default Shell Environment Variables.
11. How COMMAND ALIASES used in command line
*****
110
6
LINUX DOCUMENTATION
Unit Structure
6.0 Objectives
6.1 Linux Documentation
6.2 Man pages, GNU info,
6.3 Help command,
6.4 More documentation sources
6.5 File Operations
6.6 Filesystem
6.7 Filesystem architecture
6.8 File types
6.9 File attributes
6.10 Working with files
6.11 Backup, compression
6.12 Summary
6.13 Unit End Questions
6.0 OBJECTIVES
In this chapter In this chapter you will learn about:
Linux Documentation man pages, GNU info help command
More documentation sources, File Operations, Filesystem, Filesystem
Architecture, File types, File attributes, Working with
Files, Backup and compression
Options:
-d output short description for each topic
-m display usage in pseudo-manpage format
-s output only a short usage synopsis for each topic matching
112
Linux option: It is used when you just want to get an overview about any shell
built-in command i.e it only gives short description.
-m option: It displays usage in pseudo-manpage format.
-s option: It just displays only a short usage synopsis for each topic
matching.
Basic listing:
The ls command at its most basic form displays the files and directories
located in your current directory:
$ ls
4rich Desktop Download Music Pictures store store.zip test backup
Documents Drivers myprog Public store.sql Templates Videos.
$
Notice that the ls command produces the listing in alphabetical order (in
columns rather than rows). If you‟re using a terminal emulator that
supports color, the ls command may also show different types of entries in
different colors. The LS COLORS environment variable controls this
feature. Different Linux distributions set this environment variable
depending on the capabilities of the terminal emulator.
If you don‟t have a color terminal emulator, you can use the -F parameter
with the ls command to easily distinguish files from directories. Using the
-F parameter produces the following output:
$ ls -F
4rich/ Documents/ Music/ Public/ store.zip Videos/
backup.zip Download/ myprog* store/ Templates/
Desktop/ Drivers/ Pictures/ store.sql test
$
113
The -F parameter now flags the directories with a forward slash, to help Linux Documentation
identify them in the listing. Similarly, it flags executable files with an
asterisk, to help you find the files that can be run on the system easier.
The basic ls command can be somewhat misleading. It shows the files and
directories contained in the current directory, but not necessarily all of
them. Linux often uses hidden files to store configuration information. In
Linux, hidden files are files with filenames that start with a period.
These files don‟t appear in the default ls listing (thus they are called
hidden).
To display hidden files along with normal files and directories, use the -a
parameter.
Displaying File Information with different ls options:
The file type (such as directory (d), Ordinary file (-), character device (c),
or block device (b)
The permissions for the file:
(1) Read With this permission user can read the data or file, user can
not write into it.
(2) Write With this permission user can write the data or file.
(3) Execute With this permission user can execute the application.
The number of hard links to the file (Links of the file in same directory)
The username of the owner of the file.
The group name of the group the file belongs to.
The size of the file in bytes.
The time the file was modified last.
The file or directory namePart I.
The Linsux is divided into 3 groups owner, group and others.
116
Linux 1) Owner:
It is the user who creates a particulars file called as owner of that file. The
owner is a person who has all rights on the files created by him and also
decides the rights of other user associated to that file. The owner group is
abbrivated as „u‟
2) Group:
In a typical software development one large project is divided among
different members of a team. So software developers requires that file
belonging their project should not accessible to other users hence they will
apply right to group users. It is abbreviated as „g‟
3) Others:
All the users that are neither owner nor engaged to with a group is called
as other normally guest user Abbrivated d as „o‟.
Single-letter parameters.
117
The single-letter parameters are always preceded by a single dash. Full- Linux Documentation
word parameters are more descriptive and are preceded by a double dash.
Many parameters have both a single-letter and full-word version, while
some have only one type. These are some of parameters that are used with
ls command.
You can use more than one parameter at a time if you want to. A common
combination to use is the -a parameter to list all files, the -i parameter to
list the inode for each file, the -l parameter to produce a long listing, and
the -s parameter to list the block size of the files. The inode of a file or
directory is a unique identification number the kernel assigns to each
object in the filesystem. Combining all of these parameters creates the
easy-to-remember -sail parameter:
$ ls -sail
total 2360
301860 8 drwx------ 36 rich rich 4096 2007-09-03 15:12 .
65473 8 drwxr-xr-x 6 root root 4096 2007-07-29 14:20 ..
360621 8 drwxrwxr-x 2 rich rich 4096 2007-08-24 22:04 4rich
301862 8 -rw-r--r-- 1 rich rich 124 2007-02-12 10:18 .bashrc
361443 8 drwxrwxr-x 4 rich rich 4096 2007-07-26 20:31 .ccache
301879 8 drwxr-xr-x 3 rich rich 4096 2007-07-26 18:25 .config
301871 8 drwxr-xr-x 3 rich rich 4096 2007-08-31 22:24 Desktop
301870 8 -rw------- 1 rich rich 26 2001-11-01 04:06 .dmrc
301872 8 drwxr-xr-x 2 rich rich 4096 2001-11-01 04:06 Download
118
Linux 360207 8 drwxrwxr-x 2 rich rich 4096 2007-07-26 18:25 Drivers
301882 8 drwx------ 5 rich rich 4096 2007-09-02 23:40 .gconf
301883 8 drwx------ 2 rich rich 4096 2007-09-02 23:43 .gconfd
360338 8 drwx------ 3 rich rich 4096 2007-08-06 23:06 .gftp
File Handling:
The bash shell provides lots of commands for manipulating files on the
Linux filesystem. This section walks you through the basic commands you
will need to work with files from the CLI (command level interface) for
all your file-handling needs.
File:
(1) The file is container for storing information.
(2) A file‟s size is not stored in the file, nor even it‟s name. All file
attributes are kept in a separate area of the hard disk, not directly to
humans, but only to the kernel.
(3) UNIX treats directories and devices as file as well. A directory is
simply a folder where you store filenames and other directories. All
physical devices like the hard disk, memory, CD-ROM, printer and
modem are treated as files.
Creating files:
(1) Using cat to create a file:
Enter the command cat, followed by the > (the right chevron)
character and the filename(for e.g. kiran):
$ cat >file1:
This command is used to create a new file known as file1.
To save this file ctrl +d option is used, ctrl+d indicate end of file mark ie
eof mark.
To interrupt in between ctrl + z is used.
119
This command defines that redirect the contents from standard output ie. Linux Documentation
Console to the newly created file named as file1.
120
Linux $ touch test1
$ ls -l test1
-rw-r--r-- 1 rich rich 0 Sep 1 09:37 test1
$
The modification time of test1 is now updated from the original time. If
you want to change only the access time, use the -a parameter. To change
only the modification time, use the –m parameter. By default touch uses
the current time. You can specify the time by using the –t parameter with a
specific timestamp:
$ touch -t 200812251200 test1
$ ls -l test1
-rw-r--r-- 1 rich rich 0 Dec 25 2008 test1
$
Now the modification time for the file is set to a date significantly in the
future from the current time.
Copying files:
Copying files and directories from one location in the filesystem to
another is a common practice for system administrators. The cp command
provides this feature.
In it‟s most basic form, the cp command uses two parameters: the source
object and the destination object:
cp source destination
When both the source and destination parameters are filenames, the cp
command copies the source file to a new file with the filename specified
as the destination. The new file acts like a brand new file, with an updated
file creation and last modified times:
$ cp kiran newfile
$ ls -il
total 0
1954793 -rw-r--r-- 1 rich rich 0 Dec 25 2008 kiran
1954794 -rw-r--r-- 1 rich rich 0 Sep 1 09:39 newfile
$
The new file newfile shows a different inode number, indicating that it‟s a
completely new file.
121
You‟ll also notice that the modification time for the newfile file shows the Linux Documentation
time that it was created.
122
Linux cp Options:
(a) Interactive copying (-i) the –i(interactive) option warns the user
before overwriting the destination file. If unit1 exists, cp prompts for
a response:
$ cp –i chap01 unit1
(b) cp: overwrite unit1 (yes/no)? y
A y at this prompt overwrites the file, any other responses leaves it
uncopied.
Copying directory structures (-R) Many UNIX commands are capable of
recursive behavior. This means that the command can descend a directory
and examine all files in its subdirectories. The cp –R command behaves
recurvely to copy an entire directory structure.
cp –R progs newprogs newprogs must not exist
123
$ cp -p test1 test3 Linux Documentation
$ ls -il
total 4
1954886 drwxr-xr-x 2 rich rich 4096 Sep 1 09:42 dir1/
1954793 -rw-r--r-- 1 rich rich 0 Dec 25 2008 test1
1954794 -rw-r--r-- 1 rich rich 0 Sep 1 09:39 test2
1954888 -rw-r--r-- 1 rich rich 0 Dec 25 2008 test3
$
Now, even though the test3 file is a completely new file, it has the same
timestamps as the original test1 file.
The-R parameter is extremely powerful. It allows you to recursively copy
the contents of an entire directory in one command:
$ cp -R dir1 dir2
$ ls -l
total 8
124
Linux -rw-r--r-- 1 rich rich 0 Dec 25 2008 test3
$
TABLE 3-6
125
(copies file while copying it will prompt for coping and creates the backup Linux Documentation
file)
cp: overwrite „file2‟ ? y
$ ls file*
file2 file2~
~ This sign shows the backup file of file2.
Links In linux you can use links to give the same file with two entirely
different names or to pretend that the file is in one location in the file
system and in actual stored in an entirely different location.
Linking is useful when you have two different programs that look for the
same file in different places. So you need to make sure that the file is in
both locations.
There are two types of links:
(1) Hard Link.
(2) Soft Link.
126
Linux $ ln originalfile linkfile:
The link file should not be created first.
$ ln old new:
To check whether a link file is created properly or not
$ ls –I old new
old
new
since first field displays the inode number and second field display the
name of the file. If the inode number of both the file is same then it is sure
that both files are linked.
it will create a file new which is link file of the original file old.
$ ln today tom1
$ ln today tom2
$ ls –l today tom1
Long listing format shows the number of links for the file today and tom1
as 2.
You can only create a hard link between files on the same physical
medium. You can’t create a hard link between files under separate
mount points. In that case, you’ll have to use a soft link.
Symbol Link:
A symbol link is different from a hard link in that it is special file type that
contains the name of the original file some what link a shortcut in
windows.
127
$ ln –s original lnfile Linux Documentation
$ ln –s abc.doc /kk/xy.doc
It will create symbolic link of abc.doc in the specified directory to a file
xy.doc. In this xy.doc should be created first. The linking can identified by
red blinking on the path of abc.doc when ls–l ie. long lisitng is to be
shown. The symbolic link is identified by file type field of ls–l option
which is indicated by l (l in lower case).
The inode number of symbolic link files are not same.
Symbol Link to a directory
You can create a symbolic link to current directory to specified directory.
$ ln –s /home/chris/letter gifts
$ cd gifts
$ pwd
/home/chris/letter
If you want to display the name of symbolic link cwd variable is used.
cwd is a special system variable names of directory which is symbolic
link.
$ pwd
/home/chris/letter
$ cwd
/home/chris/gifts
Renaming files:
In the Linux world, renaming files is called moving. The mv command is
available to move both files and directories to another location:
$ mv test2 test6
$ ls -il test*
1954793 -rw-r--r-- 2 rich rich 6 Sep 1 09:51 test1
1954888 -rw-r--r-- 1 rich rich 0 Dec 25 2008 test3
1954793 -rw-r--r-- 2 rich rich 6 Sep 1 09:51 test4
1954891 lrwxrwxrwx 1 rich rich 5 Sep 1 09:56 test5 -> test1
1954794 -rw-r--r-- 1 rich rich 0 Sep 1 09:39 test6
$
Notice that moving the file changed the filename but kept the same inode
number and the timestamp value. Moving a file with soft links is a
problem:
$ mv test1 test8
$ ls -il test*
total 16
1954888 -rw-r--r-- 1 rich rich 0 Dec 25 2008 test3
1954793 -rw-r--r-- 2 rich rich 6 Sep 1 09:51 test4
1954891 lrwxrwxrwx 1 rich rich 5 Sep 1 09:56 test5 -> test1
1954794 -rw-r--r-- 1 rich rich 0 Sep 1 09:39 test6
1954793 -rw-r--r-- 2 rich rich 6 Sep 1 09:51 test8
[rich@test2 clsc]$ mv test8 test1
The test4 file that uses a hard link still uses the same inode number, which
is perfectly fine.
However, the test5 file now points to an invalid file, and it is no longer a
valid link.
You can also use the mv command to move directories:
129
$ mv dir2 dir4 Linux Documentation
Deleting files:
rm: Deleting Files
In Linux if you want to delete existing files. Whether it‟s to clean up a
filesystem or to remove a software package, there‟s always opportunities
to delete files.
Deleting is called removing. The command to remove files in the bash
shell is rm.
(1) The rm(remove ) command deletes one or more files.
(2) The following command deletes three files:
rm chap01 chap02 chap03
rm chap* could be dangerous to use!
(3) A file once deleted can‟t be recovered. rm won‟t normally remove a
directory, but it can remove files from one.
(4) You may sometimes need to delete all files in a directory as part of a
cleanup operation
The *, when used by itself, represents all files, you can then use rm like
this:
$ rm * All file gone!
$_
130
Linux
rm options:
131
$ Linux Documentation
Notice that the command prompts you to make sure that you‟re serious
about removing the file.
Once you remove a file it‟s gone forever. Now, here‟s an interesting tidbit
about deleting a file that has links to it:
$ rm test1
$ ls -l
total 12
drwxr-xr-x 2 rich rich 4096 Sep 1 09:42 dir1/
drwxr-xr-x 2 rich rich 4096 Sep 1 09:45 dir2/
-rw-r--r-- 1 rich rich 0 Dec 25 2008 test3
-rw-r--r-- 1 rich rich 6 Sep 1 09:51 test4
lrwxrwxrwx 1 rich rich 5 Sep 1 09:56 test5 -> test1
$ cat test4
hello
$ cat test5
cat: test5: No such file or directory
$
I removed the test1 file, which had both a hard link with the test4 file and
a soft link with the test5 file. Noticed what happened. Both of the linked
files still appear, even though the test1 file is now gone (although on my
color terminal the test5 filename now appears in red). When I look at the
contents of the test4 file that was a hard link, it still shows the contents of
the file.
When I look at the contents of the test5 file that was a soft link, bash
indicates that it doesn‟t exist any more.
Directory Handling:
Creating Directories:
(1) mkdir command is used to create a new directory.
Syntax is mkdir <dir-name>.
The command is followed by the names of the directories to be
created.
132
Linux Example: mkdir Kiran
Kiran directory is created in the current root path.
(2) Directories and subdirectories are created with the mkdir (make
directory) command.
(3) You can create a number of subdirectories with one mkdir command:
mkdir kiran chirag abc
(4) The system creates a new directory and assigns it a new inode
number.
(5) The following command creates a directory tree:
mkdir college college/kiran college/chirag
Deleting Directories:
The basic command for removing a directory is rmdir:
Syntax : rmdir <dir-name>
$ rmdir Kiran
133
Removes the directory Kiran. Linux Documentation
134
Linux $ cd /home/user/college
$ pwd
/home/user/college
$ rmdir kiran
The mkdir and rmdir commands work only in directories owned by the
user.
135
has the ability to peek inside of a file and determine just what kind of file Linux Documentation
it is:
$ file test1
test1: ASCII text
$ file myscript
myscript: Bourne shell script text executable
$ file myprog
myprog: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV),
dynamically linked (uses shared libs), not stripped
$ file Monday reports
monday: text
reports: directory
$ file today mydata
today: Ascii text
mydata: empty
The file command classifies files into three categories:
Data files: Files that contain nonprintable binary characters, but that
you can‟t run on the system.
The linux file commands helps you to determine for what a file is used. It
examines a few lines of files & tries to determine classification for it. The
file command is used to display the type of file.
The file cmd looks for a special keybwords or special numbers in those
first few lines only but it is not fully accurate. Hence OD‟ cmd is used to
examine the entire file byte by byte „OD‟ is the „octal dump‟ which
performs the dump of a file & it prints every bite in its octal
representation.
File <filename> [directory name]
File OD: it prints the contents of file byte by byte either in octal character
or a decimal or hexadecimal.
Options Descriptions
-c It O/Ps the character of byte value.
136
Linux
-d It O/Ps a decimal form of byte value.
-x It O/Ps hexadecimal form of byte value.
-o It O/Ps octal form of byte value.
Viewing the whole file:
If you have a large text file on your hands, you may want to be able to see
what‟s inside of it.
There are three different commands in Linux to view the files contents.
If you need to compress multiple blank lines into a single blank line, use
the -s parameter:
$ cat -s test1
hello
This is a test file.
That we‟ll use to test the cat command.
$
if you don‟t want tab characters to appear, use the -T parameter:
$ cat -T test1
hello
This is a test file.
That we‟ll use to^Itest the cat command.
$
The -T parameter replaces any tabs in the text with the ^I character
combination.
Using the more command to display a text file
For large files, the cat command is not advisable. The text in the file will
just quickly scroll off of the monitor without stopping more command will
this problem.
To view the file chap01, enter the command with the filename:
more chap01 Press q to exit
138
Linux You‟ll see the contents of chap01 on the screen, one page at a time. At
the bottom of the screen, you‟ll also see the filename and percentage
of the file that has been viewed:
– more – (17%)
Navigation:
Irrespective of version, more uses the spacebar to scroll forward a page at
a time. You can scroll by small and large increments of lines or screens.
To move forward one page, use f or the spacebar And to move back one
page, use b
This means you can use 10f for scrolling forward by 10 pages and
30b for scrolling back 30 pages just remember that the commands
themselves are not displayed on the screen – even for a moment.
Repeating the last command ( ) more has a repeat command, the dot
(same command used by vi), that repeats the last command you used.
If you scroll forward with 10f, you can scroll another 10 pages by
simply pressing a dot.
140
Linux
Examples:
head-15 myfile.txt: Would display the first fifteen lines of myfile.txt.
Tail Command:
141
Delivers the last part of the file. Linux Documentation
Syntax:
tail [+ number] [-l] [-b] [-c] [-r] [-f] [-c number |-n number] [file].
Examples:
tail myfile.txt
142
Linux The above example would list the last 10 (default) lines of the file
myfile.txt.
/Report / Letter
The tree can be shown by root at the top. Extending down from the root
are the branches. Each branch grows out of other branch but it can have
many lower branches it can said to be parent child structure. In the same
way each directory is a subdirectory of one other directory i.e. each
directory is a child of parent directory. Root is identified by a forward
slash (/), within the root directory number of system directories are built,
root directory also contain home directory which contains the info of all
users in the system and each user home directory i.e. Chirag in turn
contains the directory which the user has made for his use.
The Full Linux file structure.
143
/(Root) Linux Documentation
Chmod
User 3
spool
ABC
man
sbin
tom
Cat
CP
bin
LS
lib
Reports Letters
Home Directories:
When you log on to system you are placed within home directory. The
name given to this directory by system is the same as your login name.
You can crate files in home directory also you can create more directories.
You can change to these directories and stores file in them. Same is true
for users on the system i.e. each and every users will have his own
directory identified by login name and user in turn can create their own
directories and subdirectories.
Path Name:
The full name of the directory to identify that directory is the path name.
The hierarchically nested relationship among directories forms path and
these path can be used to identify and reference any directory or file. A
path exist from „/‟ i.e. root directly to home directory.
/root
robert ABC
Pathname:
/home/rober
reports Letters
Pathname:
/home/ABC/reports FILE
Pathname:
/home/ABC/letter/file
144
Linux While writing the pathname by listing of each directory the pathname is
separated by „/‟. When we are writing any path starts with “/” indicate root
directory receiving directory name
E.g. /home/abc/letters
Home Directory
Root Directory Home Directory Users Directory
(users)
Traversing Directories:
The change directory command (cd) is what you‟ll use to move your shell
session to another directory in the Linux filesystem.
The format of the cd command is:
cd destination
The cd command may take a single parameter, destination, which specifies
the directory name you want to go to. If you don‟t specify a destination on
the cd command, it will take you to your home directory.
The destination parameter, though, can be expressed using two different
methods:
An absolute filepath
A relative filepath
Relative Pathnames:
You would have noted that in a previous example, we didn‟t use an
absolute pathname to move the directory progs.
145
Relative pathname begins from your working directory working directory Linux Documentation
is the one you are currently in. Relative filepaths allow you to specify a
destination filepath relative to your current location, without having to
start at the root. A relative filepath doesn‟t start with a forward slash,
indicating the root directory. Instead, a relative filepath starts with either a
directory name (if you‟re traversing to a directory under your current
directory), or a special character indicating a relative location to your
current directory location. The two special characters used for this are:
/root
Manday ThankYou
Absoulte Pathname:
/home/chirs/reports/monday
F2 Abc
Absoulte Pathname:
[@root/chirs]/reports/monday
146
Linux can write $ cat ~/reports/Monday/F2. So it displays the contents of F2
Where tilde (~) indicates the path /home/chris.
147
(14) /tmp The temporary directory, where temporary Linux Documentation
work files can be created and destroyed.
(15) /mnt The mount directory, another common place
for mount points used for removable media.
(16) /Lib The library directory, where system and
application library files are stored.
(17) /boot The boot directory, where boot files are
stored.
The first field in the output listing is a code that describes the permissions
for the files and directories.
The first character in the field defines the type of the object, These are the
different options of file types.
for files
d for directories
l for links
c for character devices
148
Linux b for block devices
n for network devices
After that, there are three sets of three characters. Each set of three
characters defines an access permission triplet:
r for read permission for the object
w for write permission for the object
x for execute permission for the object
If a permission is denied, a dash appears in the location. The three sets
relate the three levels of security for the object:
The owner of the object
The group that owns the object
Everyone else on the system
FI-rwxrwxr-x 1 rich rich 4882 2007-09-18 13:58 myprog
rwx for the file owner (set to the login name rich)
rwx for the file group owner (set to the group name rich)
$ touch newfile
$ ls -al newfile
-rw-r--r-- 1 rich rich 0 Sep 20 19:16 newfile
$
The touch command created the file using the default permissions
assigned to my user account. The umask command shows and sets the
default permissions:
$ umask
149
0022 Linux Documentation
Unfortunately, the umask command setting isn‟t overtly clear, and trying
to understand exactly how it works makes things even muddier. The first
digit represents a special security feature called the sticky bit. The next
three digits represent the octal values of the umask for a file or directory.
To understand how umask works, you first need to understand octal mode
security settings. Octal mode security settings take the three rwx
permission values and convert them into a 3-bit binary value, represented
by a single octal value. In the binary representation, each position is a
binary bit. Thus, if the read permission is the only permission set, the
value becomes r--, relating to a binary value of 100, indicating the octal
value of 4.
Octal mode takes the octal permissions and lists three of them in order for
the three security levels (user, group, and everyone). Thus, the octal mode
value 664 represents read and write permissions for the user and group,
but read-only permission for everyone else.
The permission for a file is broken into three parts. Each group represents
a category and contains three slots representing the read, write and execute
permissions of the file.
The first group (rwx) has all three permissions. The file is readable, write
able and executable by the owner.
The second group (r-x) has a hyphen in the middle slot, which indicates
the absence of write permission by the group user of the file.
The third group (r--) has the write and execute bit absent. The file
permissions are also categorized for the kinds of user ie it can be other/
guest user.
r Read
w Write
x Execute
g group
o Other
u Owner
a All users
Syntax:
chmod category operation permission filenames
category can be user, group or other
operation can be assign or remove
permission can be read, write and execute
Example:
Chmod g+rw hello.txt
Chmod a-wx xyz.txt
152
Linux -x exclude the following names -i include only the following names.
-F fix zipfile (-FF try harder) -D do not add directory entries.
-A adjust self-extracting exe -J junk zipfile prefix (unzipsfx).
-T test zipfile integrity -X eXclude eXtra file attributes.
-y store symbolic links as the link instead of the referenced file.
-R PKZIP recursion (see manual).
$
The power of the zip utility is its ability to compress entire directories of
files into a single compressed file. This makes it ideal for archiving entire
directory structures:
$ zip -r testzip test
adding: test/ (stored 0%)
adding: test/test1/ (stored 0%)
adding: test/test1/myprog2 (stored 0%)
adding: test/test1/myprog1 (stored 0%)
adding: test/myprog.c (deflated 39%)
adding: test/file3 (deflated 2%)
adding: test/file4 (stored 0%)
adding: test/test2/ (stored 0%)
adding: test/file1.gz (stored 0%)
adding: test/file2 (deflated 4%)
adding: test/myprog.gz (stored 0%)
$
This example creates the zip file named testzip.zip, and recurses through
the directory test,
Adding each file and directory found to the zip file. Notice from the output
that not all of the files stored in the zip file could be compressed. The zip
utility automatically determines the best compression type to use for each
individual file.
When you use the recursion feature in the zip command, files are stored in
the same.
153
Directory structure in the zip file. Files contained in subdirectories are Linux Documentation
stored in the zip.
File within the same subdirectories. You must be careful when extracting
the files, the unzip command will rebuild the entire directory structure in
the new location.
File Compression:
If you are transferring the file across a N/W to save transmission time.
You can effectively reduce the size by creating a compressed copy of it.
Anytime you need file again decompress it.
$ gzip mydata
$ mydata.gz drip1
To compress a gzip file
$ gzip –d mydata.gz
To decompress a gzip
$ gunzip mydata.gz
$ ls
$ gzip 0-cmydata preface>mufiles.gz sends compressed version of a file to
standard o/p each file listed is separately compressed extension will be gz.
-h displays help help listing
-l file list
$ gzip -l myfiles.gz
-r dir name
-v file list
-num
You can also zip with bzipz (Burrows-wheeler block sorting text
compression algorithm)
The file created with extension .bzz bzip command compresses file in
block & enables you to specify their size.
$ bzipz mydata
$ ls
mydata bzz
154
Linux $ zip mydata
$ zip –r reports
$ ls
$ unzip mydata.zip
mydata.zip
Archiving (tar):
The tar command is used to store backup transport & archive files. A tar
file can be made on tape drive or on local hard disk. tar command serves
many file together in a single tape or disk archive & can single tape or
disk archive & can restore individual file from the archive i.e. tar file is a
single file that contains the contents of many file also store file attributes
like file access permission the user, group, size time. The files in tar file
are called the members of that archive.
The tar utility creates archive for files & directories with tar you can
archive specific files, update them in the archive & add new files as you
want to that archive. You can even archive entire directories with all their
files & subdirectories all of which can be restored from archive.
The tar utility was originally designed to create archives on tapes.
The term tar stands for tap archive, also you can create archives on any
device such as floppy disk or you can create an archive file to hold the
archive (for devices archiving is not possible in DOS only for files it is
possible)
The tar utility is ideal for making backups of your files or combining
several files into a single file for transmission across a N/W.
On Linux, tar is used to create archives on devices of files.
You can direct tar to archive files to a specific device or a file by using ’f ’
option with the name of device or file.
155
Linux Documentation
c creating a new archive file i.e. tar file display each file name is it
archive for verifying
f file i.e. specify the name of tar file or location where it is to be created.
In this example the directory mydir & its all subdirectories are saved in the
fie myarch.tar
Mydir
Command Execution
tar options : Back up files to tape device or
archive file
tar option archive : Backs up file to specific file or
name file list device specified as archive name,
filelist, can be filenm or directory
Options:
c : creates a new archive
156
Linux t : lists the names of files in an archive
r : append file to an archive
u : Update an archive with new & changed files,
adds only those files modified ֶ they were
archived or files not already present in archive
w : waits for a confirmation from the user before
archiving each file
x : extracts files from an archive
m : created a multiple volume archive that may be
stored on several floppy drives
f archive – : saves the tape archives to the file archive name
nm instead of the default tape device, when in this
option gives an archive name, the f option
saves the tar archive in file of that name which
is specified as archive name
f device –nm : Saves a tar archive to a device such as floppy
disk or tape /dev/fdo is the device name For
your floppy disk the default devices is held in
/etc/default/tar file
v : Displays each filename an it is archived
z : Compresses or decompresses archived files
using g zip
The user can extract the directories from the tape using X option. The xf
option extracts file from an archive file or device. The tar extension
operation generates all subdirectories.
xf option directs for to extract all the files & subdirectories form the tar
files.
myarch.tar
$ tar xvf myarch.tar
$ tar xvf myarch.tar
pathname denotes the relative pathnames. The above command creates the
root directory under the current directory if it does not already exist.
mydir/
mydir/reports
mydir/reports/weather
mydir/reports/Monday
mydir/reports/Friday
mydir/mymeeting
mydir/party
157
You can use r option to add files to an already created archive. The r Linux Documentation
option appends the files to the archive
$ tar rvf myarch.tar mydocs:
The user appends the files in the myarch.tar archive. Here the directory
mydocs & its files are added to the myarch.tar archive.
If you want to do change or update to the previously created archived, you
can use u option to instruct tar to update the archive with an modified file.
The tar command compares the time of the last update for each archive
file with those in users directory & copies into the archive any files that
have been changed since they were last archived.
Any newly created files in these directories are also added to the archive
suppose mydir directory you have added two or 3 files & you want to
update that in tar.
tar file will not store the leading slash (/) it removes the slash while
retrieving a file as the tar file does not store the absolute filename, it
restores the file with relation to your current directory & prevents
accidental overwriting of original data.
If you want absolute path to be stored use –p (capital P) option
# -tar - -absolute -paths -paths -cvf trial.tar/root/test/*
Or
158
Linux # -tar -p -cvf trial.tar/root/test/*
Storing the absolute pathnames we can created archive filename will long
names also instead of using only single character # tar –c –v -f
trial.tar/root/user/
Concatenating Tar.Archives
# tar –Af trial.tar script.tar
The above command adds all contents of script.tar archive to the trial.tar
archive. To backup the files to a specific device, specify the device as the
archive for a floppy disk, you can specify the floppy drive. Be sure use
Blank floppy otherwise any data previously placed on it will be erased by
this operation.
The user created an archive on floppy disk in the /dev/fdo device device &
copies into floppy disk all the files which all in mydir directory.
$ tar xf /dev/fdo
If the files you are archiving take up more space than would be available
on a device such as floppy disk, you can create a for archive that uses the
multiple labels. The m option instruct for to prompt you for a new storage
component when the current one is filled when archiving to a floppy drive
with m option tar prompts you to put in a new floppy disk when one
becomes full. You can then save your tar archive on several floppy disks.
The tar operation does not perform compression on archived files. if you
want to compress the archive files you can instruct tar to involve the gzip
utility to compress them with the lower case z option tar first uses gzip to
compress file before archiving them. The same z option involves gzip to
decompress them when extracting files.
6.12 SUMMARY
In this chapter we learn documentation and types of
compression utilities and file system architecture
List Of References:
1) Unix Concepts and Applications by Sumitabha Das.
2) Official Ubuntu Book, 8th Edition, by Matthew Helmke & Elizabeth K.
Joseph with Jose Antonio Rey and Philips Ballew, Prentice Hall
*****
160
UNIT III
7
SECURITY
Unit Structure
7.0 Objectives
7.1 Introduction
7.2 Understanding Linux Security
7.3 Uses of root
7.4 Sudo command
7.5 Working with passwords
7.6 Bypassing user authentication
7.7 Understanding ssh
7.7 Let Us Sum Up
7.8 Unit End Questions
7.9 List of References
7.0 OBJECTIVES
In this chapter you will learn about:
Basic of linux security under the use of sudo command and password
policies. Also the ssh-secure shell uses will enhance the linux
security.
7.1 INTRODUCTION
This chapter introduces linux security measures regarding network criteria
by using ssh command features. The password policies which are
modified by using user management command. The sudo command which
are helping to manage all linux security and password policies.
Security Requirements:
Authorization: Allowing authorized user to access data
Authenticity: Verifying them.
Confidentiality: Personal information not been compromised.
Integrity: Data not been changed or modified.
Availability: Ensure that data is available.
The user access levels also apply to any program that the user runs.
That is even if a user downloads and runs a malicious program, that
program inherits the user‟s permissions and so cannot do anything
that the user themselves could not do.
Each file has the system‟s file type identifier embedded in the file
itself instead of relying in an extension. Thus executables do not
necessarily have “.exe” at the end, and plain text files do not need
“.txt” at the end. Thus one cannot fools the system by making an
executable file with a “.pdf” extension, since even if the user naively
double-clicks on the PDF file to open it for reading the system will
know that it‟s really an executable program and refuse to run it.
Firewalls:
Firewalls are network packet filters that are capable of blocking
unwanted network traffic, while passing through allowed traffic.
162
Linux A firewall uses a set of rules which determines which traffic is
allowed to pass and in which direction. These are normally used to
separate internal networks from external ones.
Firewalls are often the first line defense against crackers and internet
worms, which can be blocked by denying the means of network
ingress.
Root user can start up or shut down the system and change operating
mode such as single user mode.
It can add or remove users, file systems, back up and restore files.
Set the limitations to the user account like creating number of files,
disk space allowed to user.
163
In Ubuntu Linux by default root account is not configured Security
Attribute Description
-v Prints version number and exist
-l List will print out the commands allowed the user on the
current host
-h Help prints a usage message and exist.
-b Background runs the given command in background
-K Sure kill removes the user‟s timestamp entirely
-u User option to run the specified command as a user other
than root
-s Shell option runs the shell specified
-e Edit option indicates that instead of running a command
user wish to edit one or more files.
Choose different password: If you have a fear that your password has
been hacked them immediately change it.
164
Linux Password Security:
Two implementation of ssh are ssh1 which uses original ssh protocol
and ssh2 uses rewritten version of ssh protocol.
When you connect through ssh, you are in shell session, a text based
interface where we can interact with server.
In ssh session, any commands that we type in local terminal are sent
through an encrypted ssh tunnel and executed on server.
Encryption:
Public key encryption in ssh authentication uses two keys: public key
and private key.
For eg. When host sends data to a user on another system, the host
encrypts the authentication data with public key previously received
from that user.
Authentication:
ssh authentication is first carried out with the host and then with users.
The remote user first encrypts a session identifier using its private
key.
ssh Tools:
166
Linux The following are the tools:
Application Description
Sshs ssh client
Sshd ssh server
Scp ssh copy command client
Sftp ssh ftp client
sftp-server ssh ftp server
ssh-keygen utility for generating keys
slogin remote login
ssh-agent ssh authentication agent
*****
167
8
NETWORKING
Unit Structure
8.0 Objectives
8.1 Introduction
8.2 Basic introduction to Networking
8.3 Network protocols
8.4 Transferring files
8.5 Networking GUI.
8.6 LET US SUM UP
8.7 Unit End Questions
8.8 List of References
8.0 OBJECTIVES
In this chapter you will learn about:
Basic networking concepts and networking protocol.
Transferring files through FTP, TELNET etc.
Networking GUI.
8.1 INTRODUCTION
This chapter introduces network concept through OSI layers and
protocols. The transferring files can be done by protocols like FTP,
TELNET etc. The interface for users provided by network command.
168
Linux
8.3 NETWORK PROTOCOLS
Protocols are set of rules used for communication.
The client contacts the source and opens a connection at port number
80.
Client request the web server for some service. The request may
consist of request header followed by data sent by the client.
Server waits for more requests and finally closes the connection.
169
Data transfer: It transfer data from one place to another. Networking
Tag Description
-p Use passive mode for data transfer
-i Interactive prompting during multiple file transfer
-e Disables command editing and history support
-d Enabling debugging
TCP/IP:
o TCP (Transmission Control Protocol) and IP (Internet Protocol)
are two different procedures that are often linked together. When
information is sent over the Internet, it is generally broken up into
smaller pieces or “packets”
o The use of packets facilitates speedy transmission since different parts
of message can be sent by different routes and then reassembled at the
destination.
o TCP is the means for creating the packets, putting them back together
in the correct order at the end, and checking to make sure that no
packets got lost in transmission. If necessary, TCP will request that a
packet be resent.
o Internet Protocol(IP) is the method used to route information to the
proper address. Every computer on the Internet has to have its own
unique address known as the IP address. Every packet sent will
contain an IP address showing where it is supposed to go.
UDP:
o This protocol is used together with IP when small amounts of
information are involved.
o It is simpler than TCP and lacks the flow-control and error-recovery
functions of TCP. Thus it uses fewer system resources.
ICMP:
o A different type of protocol is Internet Control Message Protocol
(ICMP).
o It defines a small number of messages used for diagnostic and
management purposes.
o It is also used by ping and traceroute.
170
Linux Mail Protocols POP3 and SMTP:
o Email has its set of protocols and there are a diversity of it, both for
sending mail and for receiving mail.
o The most common protocol for receiving mail is Post Office Protocol
(POP) which is now in version 3 called POP3.
o Both SMTP and POP3 use TCP for managing the transmission and
delivery of mail across the Internet.
o The most common protocol for sending mail is Simple Mail Transfer
Protocol (SMTP).
o For reading mail there is Interactive Mail Access Protocol (IMAP).
IP Address:
o Every host in the network has an address has an address called IP
address, used by other machines to communicate with it.
o It’s a series of four dots delimited numbers.
o The maximum value of each octect is 255.
o It uses Internet Protocol for communication. For example:
211.162.0.1
o TCP/IP application can address a host by its hostname as well as its IP
address:
telnet abc
ftp 211.162.0.1
o The network administrator makes the IP address unique in all
connected networks.
171
Networking
Domain Significance
Name
Int International organization
Edu Educational Institution
Gov Government
Com Commercial organization
Net Networking organization
In India
Biz Business
Browsers:
o Browsers are the most used applications as it’s important to choose
stable browser that suits all your needs.
o Browsers can be light weight, command line, free to cross platform
and extremely extensible one.
o Best browsers in Linux are Firefox, chrome, opera, Pale Moon.
o It’s a HTTP client which accepts a URL from URL window and gets
the resource from the server.
telnet:
o telnet is terminal network.
o Popular client server application process for terminal services.
o telnet use in time sharing system.
o Responsible for establishing connection to the remote system.
173
Networking
2) Remote Login:
a. Used as client server system
b. User logins from remote places so that remote terminal can access
application program of another machine.
c. Server can communicate with one or more client.
d. Whenever client needs services it runs, request for the services and
use it.
174
Linux o PING (packet Internet Groper) command is the best way to check
connectivity between two nodes in Local Area Network(LAN) or
Wide Area Network(WAN).
o Host name or IP address can be used along with ping command. Ping
uses the ICMP protocols mandatory.
o ECHO_REQUEST datagram to evoke an ICMP ECHO_RESPONSE
from a host or gateway.
Example:
1) Ping the host to see if it’s alive.
2) Increase ping Time Interval
Wait for 5 seconds before sending the next packet.
$ping –I 5 google.com
3) Send N packets and stop
$ping –c 4 google.com
4) Timeout –w
Ping –w option specifies the deadline to terminate the ping output. This
specifies the total number of seconds the ping command should send
packets to the remote host.
The following example will ping for 5 seconds. i.e ping command will exit
after 5 seconds irrespective of how many packets are sent or reciv
$ping –w 5 localhost
Traceroute:
o Prints the route that packets take to a network host.
o Attempts to trace the route an IP packet would follow to some intenet
host with time to live then listening for an ICMP “time exceeded”
reply from a gateway.
traceroute command uses various options:
Tag Description
-help Display a help message and exit
-d Enable socket level debugging
-f Specifies with what TTL to start
-v Print version information and exit
-e Show ICMP extensions
$traceroute google.com
175
Route: Networking
Tag Description
-A Use the specified address family
-F Operate on kernel’s forwarding Information base
routing table
-C Operate on kernel routing cache
-n Shows numerical addresses
-net Target is network
-del Delete route
-add Add a new route
Hostname:
o Hostname command shows or sets system hostname
o To display the system’s DNS name
o Hostname is usually set at system startup by reading the contents of
file which contains hostname.
o For example/etc/hostname
Tag Options
-a Displays the alias name of the host
-b Always set a hostname
-d Displays the name of the DNS domain
-F Read the hostname from the specified file
-i Display the network address of the host name
-f Display the FQDN (Fully Qualified Domain Name)
-s Display the short host name
-h Print a help message and exit
176
Linux Network manager does not have its own graphical user interface.
*****
177
9
BASIC SHELL SCRIPTING
Unit Structure
9.0 Objectives
9.1 Introduction
9.2 Features and capabilities,
9.3 Syntax
9.4 Modifying files
9.5 Sed
9.6 awk command
9.7 File manipulation utilities
9.8 Dealing with large files and Text
9.9 String manipulation
9.10 Boolean expressions
9.11 File tests
9.12 Case
9.13 Debugging
9.14 Regular expressions
9.15 Let Us Sum Up
9.16 Unit End Questions
9.17 List of References
9.0 OBJECTIVES
In this chapter you will learn about:
Basic of shell scripting through environment variables, conditional,
looping statements and commands.
9.1 INTRODUCTION
This chapter introduces shell scripting through variables, commands,
conditional and looping statements. The sed and awk commands are
supporting for file manipulation for analyzing data.
Shell script allows reading input and parsing the command line.
9.3 SYNTAX
Following is syntax basic structure of shell script:
#!/bin/bash (Shebang)
#(comments)
chmod +x scriptfilename (make script executable)
echo “ “ (to print message of variables contains)
./scriptfilename.sh (execute script)
Where,
#!/bin/bash:-It define which shell will be used to run the shell script.
#comments:-By using „#‟ symbol you can pass the comments.
chmod +x scriptfilename.sh:-It define file is executable and tell to Linux
that file is executable.
./scriptfilename.sh:-It define execute the script
Examples,
1) To check your current shell use following command as
echo $SHELL
179
#we learn shell scripting Basic Shell Scripting
Output:
Constructs:
Construct shell script you can use text editor such as vi or cat command.
vi command:
First type following vi command and rest of text as:
180
Linux
Output:
We learn basic shell scripting, following are screen snaps for creating first
shell script program.
cat command:
First type following cat command and rest of text as:
When you finished your writing script press CTRL+D to save and then by
using chmod command give executable permission to file.
Sometimes arguments are specified with shell procedure ten they are
assigned to special variable or propositional parameters.
1) $1,$2,$3 The positional parameters.
181
2) $* The complete set of positional parameters as single string. Basic Shell Scripting
Example:
When you finished your script press CTRL+D to save and By using
chmod command give executable permission to file.
Also for modifying file you sed command which modify each line of line
and replace specified parts of the line.
182
Linux
9.5 SED
“sed” means stream editor. Sed command allows:
1) Performing basic text transformations on an input stream.
2) To modify each line of a file
3) To replace specified parts of the line.
Example
Consider a file file.txt
If the file name “file.txt” and you want to change all occurrences of
VASHI to PAREL to the modified file to “file.txt then use the following
command.
Command:
Output:
Example:
If you only want see the lines containing “SA” you could use:
183
Basic Shell Scripting
Output:
Output:
Here the “s” specifies the substitution operation. The “/” are delimiters.
The “Unix” is the search pattern and the “Linux” is the replacement string.
Syntax:
awk „pattern {action}‟ input-filename > output-filename
This command is worked as taking each line of the input file. And if the
line contains the pattern then apply the action to the line and write the
resulting line to the output-file.
If the pattern is omitted, the action is applied to all line.
184
Linux Examples:
This statement takes the element of the 1st column of each line and writes
it as a line in the output file “outputfile.txt”. As shown above
2) $awk „{print $2,$3}” file.txt > opfile.txt:
185
In this command we pass the second, third column, with $2,$3. By default Basic Shell Scripting
columns are assumed to be separated by spaces or tabs, comma.
You can use regular expression as condition.
$cat awkfile.txt:
186
Linux
Command:
2. rev:
This command is used for reverse the characters in every line. Difference
between tac command and rev command is-
rev command reverse each character of the line
tac command reverse each line of the file.
Syntax: rev filename.txt
Example: Consider a file file.txt
187
Command: Basic Shell Scripting
By using rev command file.txt display reverse the characters in every line.
3. paste:
This command is used for merge file lines that means. This command
paste the line1 of file1, line1 of file2,.. line1 of fileN. It will repeat the
same for all lines. Each file‟s line is separated by tab.
Syntax: $paste filename1.txt filename2.txt filename3.txt
Example 1:
Consider a two file pastefile1.txt and pastefile2.txt are shown combined by
using cat commands:
188
Linux Example 2:
Let us consider a file with the sample contents as below:
4. join:
This command is used for join lines of two files which is based on a
common field, this can specify by using field.
Now by using join command you join this two file joinfile.txt joinfile1.txt
Command:
Output:
Example:
1. $sed –n –e 50p –e 100p –e 100p /var/log/file:
i) Here print the lines 50,100,1000 from the file.
190
Linux ii) You can view the content of var/log/file from line number 100 to
300:
Syntax: sed –n M, Np FILENAME
Where,
1. String:
This command is used to get the length of the given variable in your shell
script.
191
Syntax: $(#string) Basic Shell Scripting
Example:
Output:
2. Position:
This command is used to extract a substring from a string. Character
substring from $sting starting from $position
Syntax: $(string:position)
$(string:position:length)
Example:
Output:
192
Linux 3. Substring for shortest match:
To match shortest substring use following command:
Syntax:
1) ${string#substring}:
# - deletes the shortest match of $substring from front of $string
2) ${string%substring}:
% - deletes the shortest match of $substring from back of $string
Example:
Output:
Here first echo statement substring is „*‟ matches the substring starts with
dot and # strips from the front of the string, so it strips the substring is
“substrings”
Second echo statement substring „*‟ matches the substring starts with dot,
and % strips from back of the string, so it deletes the substring „.txt‟
Syntax:
1) ${string##substring}
## - deletes the longest match of $substring from front of $string.
2) ${string%%substring}
%% - deletes the longest match of $substring from back of $string
193
Example: Basic Shell Scripting
Output:
Here first echo statement ##* match for „*‟ longest match which matches
„file.substrings‟ so after striping it returns remaining txt.
Second echo statement %%* match for „*‟ longest match which matches
„subtrings.txt‟ so after striping it returns „file‟.
Example:
194
Linux
Output:
195
Following are some file test operators: Basic Shell Scripting
Example:
1. Shell script checks for existence of a regular file.
Output:
196
Linux
Output:
Here read, write and execute permission off-hence output is obtained with
every else statements.
9.12 CASE
197
Case statement is similar to switch statement used in C. By using case Basic Shell Scripting
statement user can test simple values for integers and characters and
testing can be done by string pattern that can contains wild card char
actors (special characters)
Syntax:
Case expression in
pattern1)
Statement to be executed if pattern1 matches
;;
Pattern2)
Statement to be executed if pattern2 matches
;;
esac
case required at least one pattern
Finally case statements expand the expression and try to it against each
pattern. Here expression is compared against every pattern until match is
found and then the statements following the pattern matching is executed.
When statement part is executed until;; (double semicolon) which
indicates that program flow should jump to the end of the entire case
statement. If there is no match, exit status of case is zero.
Example:
Once finished save it and exit.
For run above shell script use chmod com
mand as shown in below.
Command:
198
Linux
Output:
9.13 DEBUGGING
We know that with the x-option, run the entire script in debug mode.
Each command with its arguments is printed to standard output after the
commands have been expanded but before they are executed.
-x option is used to debug a shell script
Run the shell script using –x option
For e.g. $ -x scriptname.sh
Following are debugging options used for turn on or off with set
command.
set –x: it display command and their arguments as they are executed
set –v: it display shell input lines as they are read.
199
1) It is used to replaces any character Basic Shell Scripting
Examples:
1. Search for matches start of-
$ls –l | grep ^ -
$ls –l | grp ^ d
200
Linux
201
Basic Shell Scripting
202
Linux
203
***** Basic Shell Scripting
204