Linux - Manual CSP3213
Linux - Manual CSP3213
Program 1
Linux Foundation
Since its inception in 1991, Linux has grown to become a major force in computing.
The Linux Foundation is a nonprofit organization that sponsors the work of Linux
creator Linus Torvalds. It was founded in 2000 and its mission is to promote, protect, and
advance Linux. The Linux Foundation is supported by leading technology companies and
thousands of individual members from around the world and marshalls the resources of its
members and the open source development community to ensure that Linux remains free
and technically advanced.
The Linux Foundation is active on many fronts.
Produces technical events throughout the world.
Manages kernel.org where the official versions of the Linux kernel are released.
Linux Foundation Events: The Linux Foundation hosts conferences and other events
throughout the world which bring community members together in person. These events:
Provide an open forum for development of the next kernel release.
Connect end users, system administrators, and kernel developers in order to grow
Linux use in the enterprise.
Linux Foundation Training: Build the critical skills that individuals and organizations need to
get the most out of Linux and continue with self-directed learning. It is for the community
Fedora Family
Fedora is the community distribution that forms the basis of Red Hat Enterprise
Linux (RHEL), CentOS, Scientific Linux, and Oracle Linux .Fedora contains significantly more
software than Red Hat’s enterprise version. One reason for this is that a diverse community
is involved in building Fedora; it is not just a company.
Once installed, CentOS is also virtually identical to Red Hat Enterprise Linux, which is the
most popular Linux distribution in enterprise environments.
Key Facts of the Fedora Family
The Fedora family is upstream for CentOS, RHEL, and Oracle Linux.
It supports hardware platforms such as x86, x86-64, Itanium, PowerPC, and IBM
System z.
SUSE Family
The relationship between SUSE, SUSE Linux Enterprise Server (SLES), and openSUSE is similar
to the one described between Fedora, Red Hat Enterprise Linux, and CentOS. In
this openSUSE 12.3 as the reference distribution for the SUSE family is available to end
users at no cost. The two products are extremely similar, and material that
covers openSUSE can typically be applied to SLES with no problem.
Key Facts About The SUSE Family
SUSE Linux Enterprise Server (SLES) is upstream for openSUSE.
It uses the RPM-based zypper package manager (we cover in more detail later) to
install, update, and remove packages in the system.
It includes the YaST (Yet another System Tool) application for system administration
purposes.
Debian Family
The Debian distribution is upstream for several other distributions including Ubuntu, and
Ubuntu is upstream for Linux Mint and others. It is commonly used on both servers and
desktop computers. Debian is a pure open source project and focuses on one key aspect,
that is, stability. It also provides the largest and most complete software repository to its
users.
Ubuntu aims at providing a good compromise between long term stability and ease of use.
Since Ubuntu gets most of its packages from Debian’s stable branch, Ubuntu also has access
to a very large software repository.
Key Facts About the Debian Family
The Debian family is upstream for Ubuntu, and Ubuntu is upstream for Linux
Mint and others.
It uses the DPKG-based apt-get package manager (we cover in more detail later) to
install, update, and remove packages in the system.
While choosing a Linux distribution system, you will notice that the technical differences
are mainly about package management systems, software versions, and file locations. Once
you get a grasp of those differences it becomes relatively painless to switch from one Linux
distribution to another.
Linux History
Linux is a free open source computer operating system initially developed for Intel x86-
based personal computers. It has been subsequently ported to many other hardware
platforms. However Linux evolved from a student project into a massive effort with an
enormous impact on today's world.
Linus Torvalds was a student in Helsinki, Finland, in 1991 when he started a project: writing
his own operating system kernel. He also collected together and/or developed the other
essential ingredients required to construct an entire operating system with his kernel at the
center. This soon became known as the Linux kernel.
In 1992, Linux was re-licensed using the General Public License (GPL) by GNU (a project of
the Free Software Foundation (FSF) which promotes freely available software) which made
it possible to build a worldwide community of developers. By combining the kernel with
other system components from the GNU project, numerous other developers created
complete systems called Linux Distributions in the mid-90’s.
The Linux distributions created in the mid-90’s provided the basis for fully free computing
and became a driving force in the open source software movement. In 1998, major
companies likeIBM and Oracle announced support for the Linux platform and began major
development efforts as well.
Today, Linux powers more than half of the servers on the Internet, the majority of smart-
phones (via the Android system which is built on top of Linux), and nearly all of the world’s
most powerful supercomputers.
Linux Philosophy
Linux borrows heavily from the UNIX operating system because it was written to be a free
and open source version of UNIX. Files are stored in a hierarchical file system, with the top
node of the system being root or simply "/". Whenever possible, Linux makes its
components available via files or objects that look like files. Processes, devices, and network
sockets are all represented by file-like objects, and can often be worked with using the same
utilities used for regular files.
Linux is a fully multitasking (a method where multiple tasks are performed during the same
period of time), multiuser operating system, with built-in networking and service processes
known as daemons in the UNIX world.
One of the most powerful online user communities is linux.com. This site is hosted by
the Linux Foundation and serves over one million unique visitors every month. It has active
sections on:
News
Terminology
Kernel: Interface between the hardware and the user applications. It is the core part of the
system.
Distribution: Collection of software making up a Linux-based OS.
Boot Loader: Program that boots the operating system.
Service: Program that runs as a background process.
File system: Method for storing and organizing files.
X window System: Toolkit for developing graphical subsystem on nearly all linux systems.
Desktop Environment: GUI on top of the operating system.
Command Line: Interface for typing commands on top of the OS.
Shell: Command line interpreter that interprets the commands and instructs the kernel to
perform required tasks and commands.
Linux distributions
Linux kernel is the core of a computer operating system. A full Linux distribution consists of
the kernel plus a number of other software tools for file-related operations, user
management, and software package management. Each of these tools provides a small part
of the complete system. Each tool is often its own separate project, with its own developers
working to perfect that piece of the system.
Learning Outcome: This experiment will introduce the students to LINUX Operating system,
its terminology, philosophy and various distribution families and their distributions.
Viva Questions
Briefly describe why Ubuntu is suitable distribution for installation in your practice labs?
Step 1: Select and insert the media that you’ll use to boot the Red Hat Enterprise Linux 5
installation program. It can be the first Red Hat Enterprise Linux 5 CD, a boot CD created
from the boot.iso file from the /images directory of the first installation CD, or a boot USB
key created from the diskboot.img file from the same directory.
Step 2: Power on your system. Press the appropriate key, typically ESC, F12, or DEL, to
access the boot menu shown here. If a boot menu isn’t available, you’ll need to adjust the
boot sequence in the computer BIOS, which you can then use to boot directly from your
selected media. Set your computer’s BIOS to boot from the first installation CD or USB
drive. Details vary by PC. Make sure your BIOS saves your changes before you reboot.
Step 3: Type linux askmethod when you see the boot: prompt. Graphical Installation ,
Choose a language and select OK. Select a keyboard and select OK. Select CD Rom and
select OK. If you don’t have an installation number, select the Skip Entering Installation
Number radio button.
Step 4: If there are existing partitions on the installed hard drives, you’ll get the chance to
confirm that you want to remove said partitions (this step isn’t final). If you’re configuring a
dual-boot with another operating system, don’t delete the partitions! Instead, click Back and
select Create A Custom Layout. However, dual-boot configuration, especially with Microsoft
Windows, is preferable.
Step 5: Set the time zone for your system. If you don’t have another operating system on this
computer, keep the System Clock Uses UTC option active. Then click Next.
Step 6: Type in and confirm the root password for your system. Click Next.
Step 7: There are two package customization screens available. Everyone sees the screen
shown next. (The choices are slightly different for Red Hat Enterprise Linux 5 Client.) You
can accept the defaults, select available options, and/or select Customize Now. It’s usually
best to customize modestly (I’ve selected the Customize Now option), based on the
requirements on your particular Installation and Configuration exam. Click Next. (If you
don’t select Customize Now, skip the next step.).
Step 8: The next screen congratulates you for completing the installation. The next step is to
reboot your computer into RHEL. Click Reboot.
Learning Outcome:
Unix/Linux and customizations and configurations are learned.
Viva questions
Give the customizations and configurations for one more distribution form fedora family.
Installation
File system, is the embodiment of a method of storing and organizing arbitrary collections of
data in a human-usable form.
Windows Linux
BIOS
Starting an x86-based Linux system involves a number of steps. When the computer is
powered on, the Basic Input/Output System (BIOS) initializes the hardware, including the
screen and keyboard, and tests the main memory. This process is also called POST (Power
On Self Test).
The BIOS software is stored on a ROM chip on the motherboard. After this, the remainder of
the boot process is completely controlled by the operating system.
Fig:Boot Process
Like other operating systems, Linux distributions are provided on optical media such as CDs
or DVDs. USB media is also a popular option. Most Linux distributions support booting a
small image and downloading the rest of the system over the network; these small images
are usable on media or as network boot images, making it possible to install without any
local media at all.
Many installers can do an installation completely automatically, using a configuration file to
specify installation options. This file is called a Kickstart file for Fedora-based systems,
anAutoYAST profile for SUSE-based systems, and a preseed filefor the Debian-based
systems.
Each distribution provides its own documentation and tools for creating and managing
these files.
The actual installation process is pretty similar for all distributions.
After booting from the installation media, the installer starts and asks questions about how
the system should be set up. (These questions are skipped if an automatic installation file is
provided.) Then, the installation is performed.
Learning Outcomes:
Identify Linux file systems.
Viva Questions
Define BIOS
What do you mean by POST?
What is the first sector of Hard disk known as?
Why is boot program always stored on a firmware?
Identify Linux file systems.
Identify the differences between partitions and file systems.
Describe the boot process.
Know how to install Linux on a computer.
Name different flash storage file systems?
Name different database file systems?
Name conventional file systems?
Program 4:
History
The original author of the GNU C Compiler (GCC) is Richard Stallman, the founder of the
GNU Project. The GNU Project was started in 1984 to create a complete Unix-like operating
system as free software.
The first release of GCC was made in 1987. This was a significant breakthrough, being the
first portable ANSI C optimizing compiler released as free software. Since that time GCC has
become one of the most important tools in the development of free software.
Over time GCC has been extended to support many additional languages, including Fortran,
ADA, Java and Objective-C. The acronym GCC is now used to refer to the "GNU Compiler
Collection". Its development is guided by the GCC Steering Committee, a group composed of
representatives from GCC user communities in industry, research and academia.
Features of GCC:
1. GCC is a portable compiler--it runs on most platforms available today, and can produce
output for many types of processors. In addition to the processors used in personal
computers, it also supports microcontrollers, DSPs and 64-bit CPUs.
2. GCC is not only a native compiler--it can also cross-compile any program, producing
executable files for a different system from the one used by GCC itself. This allows software
to be compiled for embedded systems which are not capable of running a compiler. GCC is
written in C with a strong focus on portability, and can compile itself, so it can be adapted to
new systems easily.
3. GCC has multiple language frontends, for parsing different languages. Programs in each
language can be compiled, or cross-compiled, for any architecture. For example, an ADA
program can be compiled for a microcontroller, or a C program for a supercomputer.
4. GCC has a modular design, allowing support for new languages and architectures to be
added. Adding a new language front-end to GCC enables the use of that language on any
architecture, provided that the necessary run-time facilities (such as libraries) are available.
Similarly, adding support for a new architecture makes it available to all languages.
5. GCC is free software, distributed under the GNU General Public License (GNU GPL).(1) This
means you have the freedom to use and to modify GCC, as with all GNU software. If you
need support for a new type of CPU, a new language, or a new feature you can add it
yourself, or hire someone to enhance GCC for you. You can hire someone to fix a bug if it is
important for your work.
Introduction to commands in gcc compiler and shell programming
Learning Outcome:
Compilation of program in gcc compiler
Viva Questions
Write a program to print your name and compile and execute the program using gcc
compiler.
Study basic and user status Unix/Linux Commands: man, help, history, who, whoami, id,
uname, tty, usermod
It is an online help facility; man displays the documentation, called man documentation of
practically every command in the system.
A man page is divided into a number of mandatory and optional sections, of which three are
always there Name, Synopsis, and Description.
Name: One-line introduction to the command.
Synopsis: Syntax used by the command.
Description: Provides details related to the command.
Synopsis:
If a command argument is enclosed in rectangular brackets, then it is optional; otherwise,
the argument is required.
The ellipsis implies that there can be more instances of the preceding word.
If there is a | character in any of the areas, it means that only one of the options shown on
the either side of the pipe can be used.
EXIT STATUS:
Exit status list possible error conditions and their numeric representations.
2. help
bash has a built-in help facility available for each of the shell built-ins. To use it, type “help”
followed by the name of the shell built-in or, you may add the -m option to change the
format of the output.
--help
Many executable programs support a “--help” option that displays a description of the
command's supported syntax and options.
3. History: Executing command from terminal will show you a complete list of last executed
commands with line numbers.
With ‘export’ command with variable will display history command with corresponding
timestamp when the command was executed.
$ export HISTTIMEFORMAT='%F %T '
-q, --count
all login names and number of users logged on
-s, --short
print only name, line, and time (default)
-t, --time
print last system clock change
-u, --users
list users logged in
--message
same as -T
--version
output version information and exit
Synopsis
id [OPTION]... [USERNAME]
Synopsis:
uname [OPTION]...
Description:
Print certain system information. With no OPTION, it is the same as -s.
-a, --all
print all information, in the following order:
-s, --kernel-name
print the kernel name
-n, --nodename
print the network node hostname
-r, --kernel-release
print the kernel release
-v, --kernel-version
print the kernel version
-m, --machine
print the machine hardware name
-p, --processor
print the processor type
-i, --hardware-platform
print the hardware platform
-o, --operating-system
print the operating system
--help
display this help and exit
9. usermod: used to modify or change any attributes of a already created user account via
command line.
Options:
-c: We can add comment field for the user account.
-d: To modify the directory for an existing user account.
-e: Using this option we can make the account expiry in specific period.
-g: Change the primary group for a User.
-G: To add a supplementary groups.
-a: To add anyone of the group to a secondary group.
-l: To change the login name from tecmint to tecmint_admin.
-L: To lock the user account. This will lock the password so we can’t use the account.
-m: moving the contents of the home directory from existing home dir to new dir.
-p:To Use un-encrypted password for the new password. (NOT Secured).
-s: Create a Specified shell for new accounts.
-u: Used to Assigned UID for the user account between 0 to 999.
-U: To unlock the user accounts. This will remove the password lock and allow us to use the
user account.
Learning Outcome:
Viva Questions
Activity to be performed
Access the man pages and practice all the options for all the commands you have learned in
this program.
Aim: System Configuration from the Graphical Interface: System, Display, Time and Date
Settings, Network Manager, Installing and Updating Software.
System Settings:
The System Settings panel allows you to control most of the basic configuration options and
desktop settings such as specifying the screen resolution, managing network connections, or
changing the date and time of the system.
- Ubuntu: they are located in the panel on the left of the screen.
System Display
The Displays panel under System Settings contains the most common settings for
changing the desktop appearance. These settings function independently of the specific
display drivers you are running.
If your system uses a proprietary driver such as those from nVidia or AMD, you will probably
have a configuration program for that driver that is not included in System Settings. This
program may give more configuration options, but may also be more complicated, and
might require sysadmin (root) access. If possible, you should configure the settings in
the Displays panel rather than the proprietary configuration program.
The X server, which actually provides the GUI, uses the /etc/X11/xorg.conf file as its
configuration file if it exists. In modern Linux distributions, this file is usually present only in
unusual circumstances, such as when certain less common graphic drivers are in use.
Changing this configuration file directly is usually for more advanced users.
The Date and Time Settings window can be accessed from the System Settings window.
Alternatively, you can right-click Date and Time on the top panel to access the Date and
Time Settings window.
The Network Time Protocol (NTP) is the most popular and reliable protocol for setting the
local time via Internet servers. Most Linux distributions include a working NTP setup which
refers to specific time servers run by the distribution. This means that no setup, beyond "on
or off", is required for network time synchronization. If desired, more detailed configuration
is possible by editing the standard NTP configuration file (/etc/ntp.conf) for Linux NTP
utilities.
Network Manager:
All Linux distributions have network configuration files, but file formats and locations can
differ from one distribution to another. Hand editing of these files can handle quite
complicated setups, but is not very dynamic or easy to learn and use. The Network
Manager utility was developed to make things easier and more uniform across distributions.
It can list all available networks (both wired and wireless), allow the choice of a wired,
wireless or mobile broadband network, handle passwords, and set up Virtual Private
Networks (VPNs). Except for unusual situations, it’s generally best to let the Network
Manager establish your connections and keep track of your settings.
Each package in a Linux distribution provides one piece of the system, such as the
Linux kernel, the C compiler, the shared software code for interacting with USB devices, or
the Firefox web browser.
Packages often depend on each other; for example, because Firefox can communicate using
SSL/TLS, it will depend on a package which provides the ability to encrypt and decrypt SSL
and TLS communication, and will not install unless that package is also installed at the same
time.
One utility handles the low-level details of unpacking a package and putting the pieces in
the right places. Most of the time, you will be working with a higher-level utility which
knows how to download packages from the Internet and can manage dependencies and
groups for you.
dpkg is the underlying package manager for these systems; it can install, remove, and build
packages. Unlike higher-level package management systems, it does not automatically
download and install packages and satisfy their dependencies.
Steps:
Learning Outcome:
Apply system, display, and date and time settings using the System Settings panel.
Track the network settings and manage connections using Network Manager in Linux.
VIVA QUESTIONS
No GUI overhead.
You can initiate graphical apps directly from the command line.
xterm
rxvt
konsole
terminator
Launching Terminal Windows
Virtual Terminals
One virtual terminal (usually number one or seven) is reserved for the graphical
environment, and text logins are enabled on the unused VTs.Ubuntu uses VT 7,
but CentOS/RHEL andopenSUSE use VT 1 for the graphical display.
An example of a situation where using the VTs is helpful when you run into problems with
the graphical desktop. In this situation, you can switch to one of the text VTs and
troubleshoot.
To switch between the VTs, press CTRL-ALT-corresponding function key for the VT. For
example, press CTRL-ALT-F6 for VT 6. (Actually you only have to press ALT-F6 key
combination if you are in a VT not running X and want to switch to another VT.)
Most input lines entered at the shell prompt have three basic elements:
Command
Options
Arguments
The command is the name of the program you are executing. It may be followed by one or
more options (or switches) that modify what the command may do. Options usually start
with one or two dashes, for example,-p or--print, in order to differentiate them
from arguments, which represent what the command operates on.
However, plenty of commands have no options, no arguments, or neither. You can also type
other things at the command line besides issuing commands, such as setting environment
variables.
When administering a multiuser system, you have the option of notifying all users prior to
shutdown as in:
Locating Applications
$ which diff
If which does not find the program, whereis is a good alternative because it looks for
packages in a broader range of system directories:
$ whereis diff
The core parts of a Linux distribution and most of its add-on software are installed via
the Package Management System. Each package contains the files and other instructions
needed to make one software component work on the system. Packages can depend on
each other. For example, a package for a Web-based application written in PHP can depend
on the PHP package.
There are two broad families of package managers: those based on Debian and those which
use RPM as their low-level package manager. The two systems are incompatible, but
provide the same features at a broad level.
Both package
management systems
provide two tool levels: a
low-level tool (such
as dpkg or rpm), takes
care of the details of
unpacking individual
packages, running
scripts, getting the
software installed
correctly, while a high-
level tool (such as apt-
get, yum, or zypper)
works with groups of
packages, downloads packages from the vendor, and figures out dependencies.
Most of the time users need work only with the high-level tool, which will take care of
calling the low-level tool as needed. Dependency tracking is a particularly important feature
of the high-level tool, as it handles the details of finding and installing each dependency for
you. Be careful, however, as installing a single package could result in many dozens or even
hundreds of dependent packages being installed.
Advanced Packaging Tool (apt) is the underlying package management system that
manages software on Debian-based systems. While it forms the backend for
graphical package managers, such as the Ubuntu Software Center and synaptic, its
native user interface is at the command line, with programs that include apt-
get and apt-cache.
Learning Outcome:
Learned using command line for the purpose we used GUI in Program 6
Viva Questions
What is zypper?
What is yum?
Show all available packages.
Give the full form for apt.
Give command to install a package?
Give command to update a package?
Give command to remove a package?
Give command to remove package dependencies?
1) cat-It issued to create a file, copy, display contents and concatenating two files.
Syntax: cat filename
$cat>filename
$ cat> f1 // Creates file f1
$ cat f1 // Displays contents of file f1
$ cat f1>f2 // Copies contents of f1 to f2
$ cat f1 f2>f3 // concatenates contents of fi and f2 to file f3
2. cp - to copy the contents of one file to another file.
Learning Outcome:
Viva Questions
Copy the contents of file abc ti file xyz
Create a file by your name and file should contain you personal information
Remove the file abc?
What is cp command used for?
What is the command for renaming?
What is the purpose of rm command?
Rename a file f1 to f1.c.
What functions are performed using cat command
Create a file by your name and the file should contain your name, ID and section, copy the
file to a file having your ID as the name. Then remove the file of your name.
1. Tar- is archiving utility in Linux. With tar command we can archive multiple files and
directories into a single file, extension of that file is “.tar”. gzip and bzip compression
techniques can be used with tar command.
Syntax : # tar [options] [name of tar file to be created] [list of files & directories to be
included]
Options:
-A, --catenate, --concatenate ----> append tar files to an archive
-c, --create ----> create a new archive
-d, --diff, --compare ---> find differences between archive and file system
--delete ---> delete from the archive (not on mag tapes!)
-r, --append ---> append files to the end of an archive
-t, --list ----> list the contents of an archive
--test-label ---> test the archive volume label and exit
-u, --update ---> only append files newer than copy in archive
-x, --extract, --get ----> extract files from an archive
2. gzip- Gzip reduces the size of the named files using Lempel-Ziv coding (LZ77). Whenever
possible, each file is replaced by one with the extension .gz, while keeping the same
ownership modes, access and modification times. (The default extension is -gz for
VMS, z for MSDOS, OS/2 FAT, Windows NT FAT and Atari.) If no files are specified, or if a
file name is "-", the standard input is compressed to the standard output. Gzip will only
attempt to compress regular files. In particular, it will ignore symbolic links.
Example:
gzip myfile
Compresses the file myfile, making it myfile.gz.
Note. When doing this the original file will no longer exist on the drive.
3. compress : Reduces the size of the file. and adds the extension .Z
Learning Outcome:
VIVA QUESTIONS
Access the man pages for all archiving commands and practice the commands with all
options given.
Aim: Directory oriented commands: cd, pwd, mkdir, rmdir, ls and its options.
1. cd Change directory.
Usage: cd
Options: -l list all files in long format. (permissions, users, filesize,date, and time are
displayed).
-a list all files including those beginning with a “.”
-F list files distinguishing directories/ executables* symbolic links@
-R recursively list subdirectories encountered.
Learning Outcome:
Viva Questions
Create a directory by your section name; the directory must contain files of all the
students by their name. Give the snapshot of the output screen which shows the
permissions these files and the section directory has.
Aim: Searching: Search file or directory in directory structure using find and locate
command with various options, wildcards *,?, []
The locate utility program performs a search through a previously constructed database of
files and directories on your system, matching all entries that contain a specified character
string. This can sometimes result in a very long list.
To get a shorter more relevant list we can use the grep program as a filter; grep will print
only the lines that contain one or more specified strings as in:
which will list all files and directories with both "zip" and "bin" in their name .
locate utilizes the database created by another program, updatedb. Most Linux systems run
this automatically once a day. However, you can update it at any time by just
running updatedb from the command line as the root user.
You can search for a filename containing specific characters using wildcards.
Wildcard Result
[set] Matches any character in the set of characters, for example [adf] will
match any occurrence of "a", "d", or "f"
To search for files using the ? wildcard, replace each unknown character with ?, e.g. if you
know only the first 2 letters are 'ba' of a 3-letter filename with an extension of .out, type ls
ba?.out .
To search for files using the * wildcard, replace the unknown string with *, e.g. if you
remember only that the extension was.out, type ls *.out
find is extremely useful and often-used utility program in the daily life of a Linux system
administrator. It traverses down the filesystem tree from any particular directory (or set of
directories) and locates files that match specified conditions. The default pathname is
always the present working directory.
For example, administrators sometimes scan for large core files (which contain diagnostic
information after a program fails) that are more than several weeks old in order to remove
them. It is also common to remove files in /tmp (and other temporary directories, such as
those containing cached files) that have not been accessed recently. Many distros use
automated scripts that run periodically to accomplish such house cleaning.
When no arguments are given, find lists all files in the current directory and all of its
subdirectories. Commonly used options to shorten the list include -name (only list files with
a certain pattern in their name), -iname (also ignore the case of file names), and -
type (which will restrict the results to files of a certain specified type, such as d for
directory, l for symbolic link or f for a regular file, etc).
Here, -ctime is when the inode meta-data (i.e., file ownership, permissions, etc) last
changed; it is often, but not necessarily when the file was first created. You can also search
for accessed/last read (-atime) or modified/last written (-mtime) times. The number is the
number of days and can be expressed as either a number (n) that means exactly that value,
+n which means greater than that number, or -n which means less than that number. There
are similar options for times in minutes (as in -cmin, -amin, and -mmin).
$ find / -size 0
Note the size here is in 512-byte blocks, by default; you can also specify bytes (c), kilobytes
(k), megabytes (M), gigabytes (G), etc. As with the time numbers above, file sizes can also be
exact numbers (n), +n or -n. For details consult the man page for find.
Learning Outcome:
Viva Questions
List all the files that have been accessed and modified in past two days.
1. In Ubuntu desktop, the USB pen drive will be detected and mounted automatically. In
ubuntu server command line terminal, a message will appear to notice you that some
information about the USB pen drive that has been plug in or alternatively you can
use fdisk command to check whether USB has been mounted or not.
Then you can get mount location by using mount command
2. If Step 1 didn't work for you, then run dmesg command to identify the correct device
name corresponding to the USB pen drive
$ dmesg
$ mkdir -p /media/usb
OR
1. First make sure that USB device is not mounted, if it is then unmount it.
Caution: Enter your device name correctly otherwise it will wip out your entire data.
Mount/Unmount CD/DVD
In order to use a CD-ROM under Linux (or any Unix-like operating system), you must
first mount it. Mounting a CD-ROM (or any other physical media, such as a floppy disk, a ZIP
disk or a hard drive) tells the operating system which block device to use and where that
device is to appear within the directory tree — the mount point. Once you have finished
using the CD-ROM, you must unmount it.
The block device device specifies the physical device or bus the CD-ROM is attached to. On
most Linux systems, you can use /dev/cdrom, which would be a symbolic link to something
like /dev/hdc for an ATAPI CD-ROM, selected as a master device, on the secondary IDE
cable.
The mount point dir specifies where the contents of the CD-ROM are to appear. In Linux and
other Unix-like operating systems, every file and directory that can be accessed appears in a
single directory tree starting from “/”, the root directory. The mount point dir, then, is
simply a directory within that directory tree.
You can use any directory that you like for the mount point dir, as long as that directory
exists and is empty. The convention under Linux is to use either /mnt/cdrom or/cdrom.
So, for a typical Linux system, the command you would use to mount a CD-ROM would be:
Once you have mounted the CD-ROM, you can access files and directories on that CD-ROM
as if they were part of your directory tree — as, in fact, they now are. For example, if you
mounted the CD-ROM on /mnt/cdrom, you can view the file you are now reading (stored on
the CD-ROM as unsw/common/cdrom-mounting.html) by typing something like:
$ more /mnt/cdrom/unsw/common/cdrom-mounting.html
Of course, if you used a different mount point than /mnt/cdrom, substitute that mount
point as appropriate. For example, if you used /cdrom, you would type:
$ more /cdrom/unsw/common/cdrom-mounting.html
To free you from the hassles of mounting and unmounting CD-ROMs in the Laboratory, you
can access the contents of this Companion CD-ROM by using ~course/cdrominstead
of /mnt/cdrom. For example, if you are studying ELEC2041, you can
use ~elec2041/cdrom on the Laboratory computers — and you don’t have to mount or
unmount any CD-ROMs:
$ more ~elec2041/cdrom/unsw/common/cdrom-mounting.html
Once you have finished using the CD-ROM, you need to unmount it. The operating system
makes you do this so that it can check that nothing is, in fact, using the CD-ROM when you
try to eject it.
To unmount the CD-ROM, you need to enter the following command as the root superuser:
# umount dir
The directory dir is the mount point that you used for mounting the CD-ROM in the first
place (eg, /mnt/cdrom). And please note that the command is umount, notunmount: the
first “n” is missing!
Learning Outcome:
Viva Questions
Program 13
Aim: GCC: Working with GCC compiler, debugging, time-stamping, compiling object files
etc.
Compilation Steps
Compiling a Program
$ gcc -Wall main.c hello_fn.c -o newhello
Creating object files from source files using compile only option -c
$ gcc -Wall -c main.c
#include <math.h>
#include <stdio.h>
void main (void){
double x = sqrt (2.0);
printf ("The square root of 2.0 is %f\n", x);
}
$ gcc -Wall calc.c /usr/lib/libm.a -o calc
$ gcc -Wall calc.c -lm -o calc
$ gcc -Wall -lm calc.c -o calc (incorrect order)
$ gcc -Wall calc.c -lm -o calc (correct order)
Compiling with optimization
$ gcc -Wall -O0 test.c -lm
Timestamp
$ time ./a.out
real 0m13.388s
user 0m13.370s
sys 0m0.010s
Learning Outcome:
Debugging with gcc compiler
Time-stamping with gcc
Compiling object files with gcc
VIVA QUESTIONS
What do you mean by timestamp?
Write a command to compile the file file1
Write a command to execute the file file1
Create the source file from object files
Why do you need a compiler?
How will you change the name of the object file being created at the time of
compilation?
What do you mean by assembling?
What are linkers?
Program 14
Aim: Create the following file hierarchy using mkdir and touch command. (The bold letters
depicts directories)
Chitkara
Rajpura Baddi
$ mkdir chitkara
$ cd chitkara
$ mkdir Rajpura
$ mkdir Baddi
$ cd Rajpura
$ touch Student.txt
$ cd Baddi
$ touch faculty.txt
$ touch mgt.txt
Learning Outcome:
Creating file and directory hierarchy structure.
Viva Questions
What is the difference between cat and touch command.
Explain the touch command
What is the cd command used for?
What is the mkdir command used for?
What is the difference between directory and files?
Give the command to change the permissions of directories.
Give the command to change the permissions of files.
How will you check who is the owner of directory rajpura.
How will you check who is the owner of directory baddi.
Program 15
Aim: File system: Introduction to file system, File system Architecture, Comparing Files
and File Types.
In Linux (and all UNIX-like operating systems) it is often said “Everything is a file”, or at
least it is treated as such. This means whether you are dealing with normal data files and
documents, or with devices such as sound cards and printers, you interact with them
through the same kind of Input/output (I/O) operations. This simplifies things: you open a
“file” and perform normal operations like reading the file and writing on it.
On many systems (including Linux), the file system is structured like a tree. The tree is
usually portrayed as inverted, and starts at what is most often called the root
directory, which marks the beginning of the hierarchical filesystem and is also sometimes
referred to as the trunk, or simply denoted by /. The root directory is not the same as the
Each user has a home directory, usually placed under /home. The/root (slash-root) directory
on modern Linux systems is no more than the root user's home directory.
The /home directory is often mounted as a separate filesystem on its own partition, or even
exported (shared) remotely on a network through NFS.
Sometimes you may group users based on their department or function. You can then
create subdirectories under the /home directory for each of these groups. For example, a
school may organize /home with something like the following:
/home/faculty/
/home/staff/
/home/students/
In this section, you will learn to identify and differentiate between the different directories
available in Linux.
The /bin directory contains executable binaries, essential commands used in single-user
mode, and essential commands required by all system users, such as given in the table
below.
Usage
ps Produces a list of processes along with status information for the system.
Commands that are not essential for the system in single-user mode are placed in
the /usr/bindirectory, while the /sbin directory is used for essential binaries related to
system administration, such as ifconfig and shutdown. There is also a /usr/sbin directory for
less essential system administration programs.
The /dev directory contains device nodes, a type of pseudo-file used by most hardware
and software devices, except for network devices. This directory is:
The /var directory contains files that are expected to change in size and content as the
system is running (varstands for variable) such as the entries in the following
directories:
The /var directory may be put in its own filesystem so that growth of the files can be
accommodated and the file sizes do not fatally affect the system. Network services
directories such as /var/ftp (the FTP service) and /var/www (the HTTP web service) are also
found under /var.
The /etc directory is the home for system configuration files. It contains no binary programs,
although there are some executable scripts. For example, the file resolv.conf tells the
system where to go on the network to obtain host name to IP address mappings (DNS). Files
likepasswd,shadow and group for managing user accounts are found in the /etc directory.
System run level scripts are found in subdirectories of /etc. For example, /etc/rc2.d contains
links to scripts for entering and leaving run level 2. The rc directory historically stood for Run
Commands. Some distros extend the contents of /etc. For example, Red Hat adds
thesysconfig subdirectory that contains more configuration files.
2. initramfs: the initial ram filesystem, required for booting, sometimes called initrd, not
initramfs
3. config: the kernel configuration file, only used for debugging and bookkeeping
Each of these files has a kernel version appended to its name. The Grand Unified
Bootloader (GRUB) files are also found under the /boot directory.
/lib contains libraries (common code shared by applications and needed for them to
run) for the essential programs in /bin and /sbin. These library filenames either start
with ld or lib, for example, /lib/libncurses.so.5.7.
Kernel modules (kernel code, often device drivers, that can be loaded and unloaded without
re-starting the system) are located in /lib/modules/<kernel-version-number>.
The /media directory is typically located where removable media, such as CDs, DVDs and
USB drives are mounted. Unless configuration prohibits it, Linux automatically mounts the
removable media in the /media directory when they are detected.
Comparing Files
Now that you know about the filesystem and its structure, let’s learn how to manage files
and directories.
diff is used to compare files and directories. This often-used utiility program has many
useful options (see man diff) including:
In this section, you will learn additional methods for comparing files and how to
apply patches to files.
You can compare three files at once usingdiff3, which uses one file as the reference
basis for the other two. For example, suppose you and a co-worker both have made
modifications to the same file working at the same time independently. diff3 can show the
differences based on the common file you both started with. The syntax fordiff3 is as
follows:
Many modifications to source code and configuration files are distributed utilizing patches,
which are applied, not suprisingly, with the patch program. A patch file contains
the deltas (changes) required to update an older version of a file to the new one. The patch
files are actually produced by running diff with the correct options, as in:
Distributing just the patch is more concise and efficient than distributing the entire file. For
example, if only one line needs to change in a file that contains 1,000 lines, the patch file
will be just a few lines long.
The first usage is more common as it is often used to apply changes to an entire directory
tree, rather than just one file as in the second example. To understand the use of the -
p1 option and many others, see the man page for patch.
In Linux, a file's extension often does not categorize it the way it might in other
operating systems. One cannot assume that a file named file.txt is a text file and not an
executable program. In Linux a file name is generally more meaningful to the user of the
system than the system itself; in fact most applications directly examine a file's contents to
see what kind of object it is rather than relying on an extension. This is very different from
the way Windows handles filenames, where a filename ending with .exe, for example,
represents an executable binary file.
The real nature of a file can be ascertained by using the file utility. For the file names given
as arguments, it examines the contents and certain characteristics to determine whether
the files are plain text, shared libraries, executable programs, scripts, or something else.
Learning Outcome:
Viva Questions
Create a file by your section name having name of all the students of your section, create
another file by your subsection name having name of ll the students in your subsection.
Compare the two files using all the comparison commands.
Program 16
Aim: Text Editors: Basic Editors: nano and gedit, More Advanced Editors: vi and emacs.
Most nano commands are invoked by holding down the Ctrl key (that is, the control key),
and pressing one of the other keys. In this text, the control key is referred to using ^. For
example, ^X means ``hold down the CTRL key and press the x key''. Most of the important
commands are listed at the bottom of your screen.
^G nano help
^R read an existing file into nano (inserted at the current cursor position)
^T opens a browser that allows you to select a file name from a list of files and directories
Navigation
When searching, you will be prompted for the text to search for. It searches from the
current cursor position, wrapping back up to the top if necessary.
Editing
Insert new text at the current cursor position just by typing the text in.
Delete commands:
Repeatedly use ^K until all of the text you want to move has been deleted.
Move to the line that you want to insert the text at, and use ^U.
Note that pressing ^U more than once will cause multiple copies to be inserted. This is
particularly useful if you want to copy text:
Repeatedly use ^K until all of the text you want to copy has been deleted.
Press ^U immediately to put a copy back in its original location.
Move to the line that you want to copy the text to, and use ^U.
^O save contents without exiting (you will be prompted for a file to save to)
^X exit nano (you will be prompted to save your file if you haven't)
when saving a file, opens a browser that allows you to select a file name from a list of
^T files and directories.
Gedit :
gedit - simple text editor for GNOME
The gedit application is a simple text editor. You can use gedit to create and edit text files.
You can use gedit plugins to perform a variety of tasks related to text-editing from within
the gedit window. Light-weight text editor Gedit has all the basic features you come to
expect from a simple text editor, but Gedit has a native graphic user interface (GUI). Gedit
also has command line arguments available to users to quickly and easily view and edit files
from a terminal. Overall, Gedit is an easy to use text editor with utilizing the powerful
capabilities of the GNOME desktop. Gedit has a versatile plug-in architecture to extend its
capablilties. This allows you to perform functions you don't normally expect from a text
editor, such as piping the output of a shell command to the screen. The plug-in architecture
also lets you email people, browse the internet, or produce a diff from gedit.
SYNTAX
gedit [--help] [--debug[-section]] [--new-window] [--new-document] [--quit] [filename(s)...]
DESCRIPTION
--debug[-section]
Runs gedit in debug mode. In debug mode function names are dumped to the
console when they are invoked. Specific sections for debugging are allowed. The
sections are: window, commands, document, file, plugins, prefs, print, search, undo,
view and recent. Run `gedit --help' for more information.
--new-window
--new-document
--quit
Quit an existing instance of gedit.
filename(s)...
Specifies the file to open when gedit starts - if this is not specified, gedit will load a
blank file with an Untitled label. Multiple files can be loaded if they are separated by
spaces. gedit also supports handling of remote files. For example, you can pass the
location of a webpage to gedit, like "http://www.gnome.org", or load a file from a
FTP server, like "ftp://ftp.gnome.org/robots.txt".
PIPES
Gedit accepts pipes, so it can be run after another command to load the output into gedit.
For example :
ls -l | gedit
What is vi?
The default editor that comes with the UNIX operating system is called vi (visual editor).
[Alternate editors for UNIX environments include pico and emacs, a product of GNU.]
1. Command mode commands which cause action to be taken on the file, and
2. Insert mode in which entered text is inserted into the file.
In the command mode, every character typed is a command that does something to the text
file being edited; a character typed in the command mode may even cause the vi editor to
enter the insert mode. In the insert mode, every character typed is added to the text in the
file; pressing the <Esc> (Escape) key turns off the Insert mode.
While there are a number of vi commands, just a handful of these is usually sufficient for
beginning vi users. To assist such users, this Web page contains a sampling of
basic vi commands. The most basic and useful commands are marked with an asterisk (* or
star) in the tables below. With practice, these commands should become automatic.
NOTE: Both UNIX and vi are case-sensitive. Be sure not to use a capital letter in place of a
lowercase letter; the results will not be what you expect.
To Start vi
To use vi on a file, type in vi filename. If the file named filename exists, then the first page
(or screen) of the file will be displayed; if the file does not exist, then an empty file and
screen are created into which you may enter text.
* vi filename edit filename starting at line 1
vi -r filename recover filename that was being edited when system crashed
To Exit vi
Usually the new or modified file is saved when you leave vi. However, it is also possible to
quit vi without saving the file.
Note: The cursor moves to bottom of screen whenever a colon (:) is typed. This type of
command is completed by hitting the <Return> (or <Enter>) key.
* :x<Return> quit vi, writing out modified file to file named in original invocation
:wq<Return> quit vi, writing out modified file to file named in original invocation
:q<Return> quit (or exit) vi
* :q!<Return> quit vi even though latest changes have not been saved for this vi call
Screen Manipulation
The following commands allow the vi editor screen (or window) to move up or down
several lines and to be refreshed.
^f move forward one screen
^b move backward one screen
^d move down (forward) one half screen
^u move up (back) one half screen
^l redraws the screen
^r redraws the screen, removing deleted lines
Unlike PC editors, you cannot replace or delete text by highlighting it with the
mouse. Instead use the commands in the following tables.
Perhaps the most important command is the one that allows you to back up
and undo your last action. Unfortunately, this command acts like a toggle, undoing
and redoing your most recent action. You cannot go back more than one step.
* u UNDO WHATEVER YOU JUST DID; a simple toggle
The main purpose of an editor is to create, add, or modify text for a file.
The following commands allow you to insert and add text. Each of these commands
puts the vi editor into insert mode; thus, the <Esc> key must be pressed to terminate
the entry of text and to put the vi editor back into command mode.
* i insert text before cursor, until <Esc> hit
I insert text at beginning of current line, until <Esc> hit
* a append text after cursor, until <Esc> hit
A append text to end of current line, until <Esc> hit
* o open and put text in a new line below current line, until <Esc> hit
* O open and put text in a new line above current line, until <Esc> hit
Changing Text
Deleting Text
Being able to determine the line number of the current line or the total number of
lines in the file being edited is sometimes useful.
:.= returns line number of current line at bottom of screen
:= returns the total number of lines at bottom of screen
provides the current line number, along with the total number of lines,
^g
in the file at the bottom of the screen
Emacs editor
Emacs is another editor available in UNIX. Like vi, emacs is a screen editor.
Unlike vi, emacs is not an insertion mode editor, meaning that any character typed
in emacs is automatically inserted into the file, unless it includes a command prefix.
Commands in emacs are either control characters (hold down the <Ctrl> key while
typing another character) or are prefixed by one of a set of reserved
characters: <Esc> or <Ctrl>-X. The <Esc> key can be typed by itself (because it really
is a character) and then followed by another character; the <Ctrl>key must be held
down while the next character is being typed. The conventions for describing these
characters (since it takes too long to type out the whole thing)
are ESC means <Esc> and C- means <Ctrl>.
One other distinction between emacs and vi is that emacs allows you to edit several
files at once. The window for emacs can be divided into several windows, each of
which contains a view into a buffer. Each buffer typically corresponds to a different
file. Many of the commands listed below are for reading files into new buffers and
moving between buffers.
To use emacs on a file, type
emacs filename
If the file named filename exists, then the first screen's worth of the file is displayed;
if it doesn't exist, a help message is displayed.
The easiest way to learn emacs is to start it up and go through the on-line tutorial. To
access the on-line tutorial, type ESC help-with-tutorial immediately after you have
started emacs. The tutorial directs you further in learning the basic commands. One
notational point you should know is that the tutorial uses M- to mean ESC.
To give you a head start, the following table lists the basic commands you need to
know to use emacs to edit a file. An asterisk (* or star) to the left of a command
indicate it is one to learn immediately.
Help Commands
Depending on the terminal, some of the cursor movement can be handled by the
arrow keys.
* C-a move cursor to (at) beginning-of-line
C-e move cursor to end-of-line
* C-f move cursor forward one character
* C-b move cursor backward one character
* C-n move cursor to next line
* C-p move cursor to previous line
C-v scroll file forward by one screenful
ESC v scroll file backward by one screenful
* ESC < go to beginning-of-buffer
* ESC > go to end-of-buffer
ESC f move cursor forward one word
ESC b move cursor backward one word
Search Commands
Learning Outcome:
Knowledge of Basic and Advanced editors
Viva Questions
What is gedit?
How will you start and exit the vi editor?
What is the significance of pipe | operator?
Why do we need an editor?
Name a terminal based editor.
Is nano a terminal based editor or not?
Enlist a difference between gedit and vi editor.
Give the command to quit and save a file using vi editor.
Enlist atleast 5 differences between all the editors mentioned in the above program.
Program 17
DESCRIPTION
NOTE: your shell may have its own version of echo which will supercede the version
described here. Please refer to your shell's documentation for details about the options it
supports.
SYNOPSIS
DESCRIPTION
host is a simple utility for performing DNS lookups. It is normally used to convert names to
IP addresses and vice versa. When no arguments or options are given, host prints a short
summary of its command line arguments and options.
name is the domain name that is to be looked up. It can also be a dotted-decimal IPv4
address or a colon-delimited IPv6 address, in which case host will by default perform a
reverse lookup for that address. server is an optional argument which is either the name or
IP address of the name server that host should query instead of the server or servers listed
in /etc/resolv.conf.
The -a (all) option is equivalent to setting the -v option and asking host to make a query of
type ANY.
When the -C option is used, host will attempt to display the SOA records for
zone name from all the listed authoritative name servers for that zone. The list of name
servers is defined by the NS records that are found for the zone.
Verbose output is generated by host when the -d or -v option is used. The two options are
equivalent. They have been provided for backwards compatibility. In previous versions, the -
doption switched on debugging traces and -v enabled verbose output.
List mode is selected by the -l option. This makes host perform a zone transfer for
zone name. The argument is provided for compatibility with older implemementations. This
option is equivalent to making a query of type AXFR.
The -n option specifies that reverse lookups of IPv6 addresses should use the IP6.INT
domain and "nibble" labels as defined in RFC1886. The default is to use IP6.ARPA and binary
labels as defined in RFC2874.
The -N option sets the number of dots that have to be in name for it to be considered
absolute. The default value is that defined using the ndots statement in /etc/resolv.conf, or
1 if no ndots statement is present. Names with fewer dots are interpreted as relative names
and will be searched for in the domains listed in the search or domain directive
in /etc/resolv.conf.
The number of UDP retries for a lookup can be changed with the -
R option. number indicates how many times host will repeat a query that does not get
answered. The default number of retries is 1. If number is negative or zero, the number of
retries will default to 1.
Non-recursive queries can be made via the -r option. Setting this option clears the RD ---
recursion desired --- bit in the query which host makes. This should mean that the name
server receiving the query will not attempt to resolve name. The -r option enables host to
mimic the behaviour of a name server by making non-recursive queries and expecting to
receive answers to those queries that are usually referrals to other name servers.
By default host uses UDP when making queries. The -T option makes it use a TCP connection
when querying the name server. TCP will be automatically selected for queries that require
it, such as zone transfer (AXFR) requests.
The -t option is used to select the query type. type can be any recognised query type:
CNAME, NS, SOA, SIG, KEY, AXFR, etc. When no query type is specified, host automatically
selects an appropriate query type. By default it looks for A records, but if the -C option was
given, queries will be made for SOA records, and if name is a dotted-decimal IPv4 address or
colon-delimited IPv6 address, host will query for PTR records.
SYNOPSIS
DESCRIPTION
Nslookup is a program to query Internet domain name servers. Nslookup has two modes:
interactive and non-interactive. Interactive mode allows the user to query name servers for
information about various hosts and domains or to print a list of hosts in a domain. Non-
interactive mode is used to print just the name and requested information for a host or
domain.
ARGUMENTS
a)when no arguments are given (the default name server will be used),
b)when the first argument is a hyphen (-) and the second argument is the host name or
Internet address of a name server.
Non-interactive mode is used when the name or Internet address of the host to be looked
up is given as the first argument. The optional second argument specifies the host name or
address of a name server.
The options listed under the ``set '' command below can be specified in the .nslookuprc file
in the user's home directory if they are listed one per line. Options can also be specified on
the command line if they precede the arguments and are prefixed with a hyphen. For
example, to change the default query type to host information, and the initial timeout to 10
seconds, type:
DESCRIPTION
ipcalc provides a simple way to calculate IP information for a host. The various options
specify what information ipcalc should display on standard out. Multiple options may be
specified. An IP address to operate on must always be specified. Most operations also
require a netmask or a CIDR prefix as well.
OPTIONS
-b, --broadcast
Display the broadcast address for the given IP address and netmask.
-h, --hostname
Display the hostname for the given IP address.
-m, --netmask
Calculate the netmask for the given IP address. It assumes that the IP address is in a
complete class A, B, or C network. Many networks do not use the default netmasks,
in which case an inappropriate value will be returned.
-p, --prefix
Show the prefix for the given mask/IP address.
-n, --network
Display the network address for the given IP address and netmask.
-s, --silent
Don't ever display error messages.
SYNOPSIS
ping uses the ICMP protocol's mandatory ECHO_REQUEST datagram to elicit an ICMP
ECHO_RESPONSE from a host or gateway. ECHO_REQUEST datagrams (``pings'') have an IP
and ICMP header, followed by a struct timeval and then an arbitrary number of ``pad'' bytes
used to fill out the packet.
OPTIONS
-a
Audible ping.
-A
Adaptive ping. Interpacket interval adapts to round-trip time, so that effectively not
more than one (or more, if preload is set) unanswered probes present in the
network. Minimal interval is 200msec for not super-user. On networks with low rtt
this mode is essentially equivalent to flood mode.
SYNOPSIS
[ -w waittime ] [ -z pausemsecs ]
host [ packetlen ]
DESCRIPTION
The Internet is a large and complex aggregation of network hardware, connected together
by gateways. Tracking the route one's packets follow (or finding the miscreant gateway
that's discarding your packets) can be difficult. Traceroute utilizes the IP protocol `time to
live' field and attempts to elicit an ICMP TIME_EXCEEDED response from each gateway
along the path to some host.
-f
Set the initial time-to-live used in the first outgoing probe packet.
-F
Set the "don't fragment" bit
-d
Enable socket level debugging.
-g
Specify a loose source route gateway (8 maximum).
--route , -r
--groups , -g
--interface=iface , -i
--masquerade , -M
Learning Outcome:
Viva Questions
Print the list of open sockets and all the masquerade connections for the network you are
connected to.
Program 18
Aim: Communication-oriented commands: whois, finger, ifconfig, telnet, wget, ip, route,
iptables, write, mesg, mail
Syntax:
whois -t TYPE
whois -v TYPE
whois -q keyword
Description:
whois searches for an object in a WHOIS database. WHOIS is a queryand response protocol
that is widely used for querying databases that store the registered users of an
Internetresource, such as a domain name or an IPaddress block, but is also used for a wider
range of other information.
Most modern versions of whois try to guess the right server to ask for the specified object. If
no guess can be made, whois will connect to whois.networksolutions.com for NIC handles
or whois.arin.net for IPv4addresses and network names.
Options:
2. finger
SYNOPSIS:
DESCRIPTION:
-s
Finger displays the user's login name, real name, terminal name and write status (as a
``*'' after the terminal name if write permission is denied), idle time, login time, office
location and office phone number.
Login time is displayed as month, day, hours and minutes, unless more than six months
ago, in which case the year is displayed rather than the hours and minutes.
Unknown devices as well as nonexistent idle and login times are displayed as single
asterisks.
-l
Produces a multi-line format displaying all of the information described for the -s
option as well as the user's home directory, home phone number, login shell, mail
status, and the contents of the files ``.plan '' ``.project '' ``.pgpkey '' and ``.forward ''
from the user's home directory.
If write permission is denied to the device, the phrase ``(messages off)'' is appended to
the line containing the device name. One entry per user is displayed with the -l option;
if a user is logged on multiple times, terminal information is repeated once per login.
Mail status is shown as ``No Mail.'' if there is no mail at all, ``Mail last read DDD MMM
## HH:MM YYYY (TZ)'' if the person has looked at their mailbox since new mail arriving,
or ``New mail received ...'', `` Unread since ...'' if they have new mail.
-p
Prevents the -l option of finger from displaying the contents of the ``.plan '' ``.project ''
and ``.pgpkey '' files.
-m
Prevent matching of user names. User is usually a login name; however, matching will
also be done on the users' real names, unless the -m option is supplied. All name
matching performed by finger is case insensitive.
If no options are specified, finger defaults to the -l style output if operands are provided,
otherwise to the -s style. Note that some fields may be missing, in either format, if
If no arguments are specified, finger will print an entry for each user currently logged into
the system.
Finger may be used to look up users on a remote machine. The format is to specify a user as
``user@host'' or ``@host '' where the default output format for the former is the -l style,
and the default output format for the latter is the -s style. The -l option is the only option
that may be passed to a remote machine.
3. ifconfig
ifconfig stands for "interface configuration". It is used to view and change the configuration
of the network interfaces on your system.
ifconfig
...will display information about all network interfaces currently in operation. The output will
resemble the following:
Here, eth0, lo and wlan0 are the names of the active network interfaces on the system.
eth0 is the first Ethernet interface. (Additional ethernet interfaces would be named
eth1, eth2, etc.) This type of interface is usually a NICconnected to the network by a
category 5cable.
lo is the loopback interface. This is a special network interface that the system uses
to communicate with itself.
wlan0 is the name of the first wireless network interface on the system. Additional
wireless interfaces would be named wlan1, wlan2, etc.
These are the traditional naming conventions for network interfaces under Linux; other
operating systems may have different names. For instance, under many BSDoperating
systems, ethernet interfaces are named em0, em1, etc. Check your configuration, or consult
your documentation, to determine the exact names of your own interfaces.
If you'd like to view the configuration of all network interfaces on the system (not just the
ones that are currently active), you can specify the -a option, like this:
ifconfig -a
This will produce output similar to simply running ifconfig, but if there are any inactive
interfaces on the system, their configuration will also be displayed.
4. telnet
Syntax:
telnet [-468ELadr] [-S tos] [-b address] [-e escapechar] [-l user] [-n tracefile] [host [port]]
The telnet command is used for interactivecommunication with another host using the
TELNET protocol. It begins in command mode, where it prints a telnet command prompt
("telnet>").
Options:
-4 Force IPv4 address resolution.
Specifies a port number or service name to contact. If not specified, the telnet port
Port
(23) is used.
Examples
telnet myhost.com
Attempts to open a connection to the remote host myhost.com on port 5555, using the
login name myusername. If successful, the host will prompt for myusername's password.
telnet
Opens a local telnet> prompt, where you can enter any of the commands listed above. For
example, entering the following command at the prompt:
5. wget
wget stands for "web get". It is a command-lineutilitywhich downloads files over a network.
Description:
wget is a free utility for non-interactive download of files from the web. It supports HTTP,
HTTPS, and FTP protocols, as well as retrieval through HTTP proxies.
wget is non-interactive, meaning that it can work in the background, while the user is not
logged on. This allows you to start a retrieval and disconnect from the system, letting
wgetfinish the work. By contrast, most web browsersrequire constant user interaction,
which make transferring a lot of data difficult.
wget can follow links in HTMLand XHTML pages and create local versions of remote
websites, fully recreating the directorystructure of the original site. This is sometimes called
"recursive downloading.'' While doing that, wget respects the Robot Exclusion Standard
(robots.txt). wget can be instructed to convert the links in downloaded HTML files to the
local files for offline viewing.
wget has been designed for robustness over slow or unstable network connections; if a
download fails due to a network problem, it will keep retrying until the whole file has been
retrieved. If the server supports regetting, it will instruct the server to continue the
download from where it left off.
Overview
The simplest way to use wget is to simply provide it with the location of a file to download
over HTTP. For example, to download the file http://website.com/files/file.zip, this
command:
wget http://website.com/files/file.zip
Examples
wget http://www.computerhope.com/
Download the default homepage file (index.htm) from www.computerhope.com. The file
will be saved to the working directory.
Download the file archive.zip from www.example.org, and limit bandwidth usage of the
wget -c http://www.example.org/files/archive.zip
Download archive.zip from example.org, and if a partial download exists in the current
directory, resume the download where it left off.
wget -b http://www.example.org/files/archive.zip
Download archive.zip in the background, returning you to the command prompt in the
interim.
Uses "web spider" mode to check if a remote file exists. Output will resemble the following:
Stop downloading archive.zip once 5megabytes have been successfully transferred. This
transfer can then later be resumed using the -c option.
6. ip
Syntax:
OPTIONS:
-s, -stats, - Output more information. If the option appears twice or more, the amount of
statistics information increases. As a rule, the information is statistics or some time values.
Specify maximum number of loops the 'ip addr flush' logic will attempt before giving
-l, -loops
up. The default is 10. Zero ("0") means loop until all addresses are removed.
followed by protocol family identifier: inet, inet6, bridge, ipx, dnet or link, enforce
the protocol family to use. If the option is not present, the protocol family is guessed
-f, -family from other arguments. If the rest of the command line does not give enough
information to guess the family, ip falls back to the default one, usually inet or any.
link is a special family identifier meaning that no networking protocol is involved.
output each record on a single line, replacing line feeds with the '\' character. This is
-o, -oneline
convenient when you want to count records with wc or to grep the output.
-r, -resolve use the system's name resolver to print DNS names instead of host addresses.
7. route
Running route at the command line without any options will display the routing table
entries:
route
This shows us how the system is currently configured. If a packet comes into the system and
has a destination in the range 192.168.2.0 through 192.168.2.255, then it is forwarded to
the gateway *, which is 0.0.0.0 — a special address which represents an invalid or non-
existant destination. So, in this case, our system will not route these packets.
If the destination is not in this IP address range, it is forwarded to the default gateway (in
this case, 192.168.1.2, and that system will determine how to forward the traffic on to the
next step towards its destination.
SYNOPSIS:
DESCRIPTION:
Iptables is used to set up, maintain, and inspect the tables of IPv4 packet filter rules in the
Linux kernel. Several different tables may be defined. Each table contains a number of built-
in chains and may also contain user-defined chains.
Each chain is a list of rules which can match a set of packets. Each rule specifies what to do
with a packet that matches. This is called a `target', which may be a jump to a user-defined
chain in the same table.
OPTIONS:
The options that are recognized by iptables can be divided into several different groups.
COMMANDS
These options specify the desired action to perform. Only one of them can be specified on
the command line unless otherwise stated below. For long versions of the command and
option names, you need to use only enough letters to ensure that iptables can differentiate
it from all other options.
iptables -t nat -n -L
Please note that it is often used with the -n option, in order to avoid long reverse DNS
lookups. It is legal to specify the -Z (zero) option as well, in which case the chain(s) will
be atomically listed and zeroed. The exact output is affected by the other arguments
given. The exact rules are suppressed until you use
iptables -L -v
PARAMETERS
The following parameters make up a rule specification (as used in the add, delete, insert,
replace and append commands).
-4, --ipv4
This option has no effect in iptables and iptables-restore.
-6, --ipv6
If a rule using the -6 option is inserted with (and only with) iptables-restore, it will be
silently ignored. Any other uses will throw an error. This option allows to put both IPv4
and IPv6 rules in a single rule file for use with both iptables-restore and ip6tables-
restore.
-p, --protocolprotocol
The protocol of the rule or of the packet to check. The specified protocol can be one of
tcp, udp, udplite, icmp, esp, ah, sctp or the special keyword "all", or it can be a
numeric value, representing one of these protocols or a different one. A protocol
name from /etc/protocols is also allowed. A "!" argument before the protocol inverts
the test. The number zero is equivalent to all. "all" will match with all protocols and is
taken as default when this option is omitted.
-s, --sourceaddress[/mask][,...]
Source specification. Address can be either a network name, a hostname, a network IP
address (with /mask), or a plain IP address. Hostnames will be resolved once only,
before the rule is submitted to the kernel. Please note that specifying any name to be
resolved with a remote query such as DNS is a really bad idea. The mask can be either
a network mask or a plain number, specifying the number of 1's at the left side of the
network mask. Thus, a mask of 24 is equivalent to 255.255.255.0. A "!" argument
before the address specification inverts the sense of the address. The flag --src is an
alias for this option. Multiple addresses can be specified, but this will expand to
multiple rules (when adding with -A), or will cause multiple rules to be deleted (with -
D).
-d, --destinationaddress[/mask][,...]
Destination specification. See the description of the -s (source) flag for a detailed
description of the syntax. The flag --dst is an alias for this option.
-m, --matchmatch
Specifies a match to use, that is, an extension module that tests for a specific property.
The set of matches make up the condition under which a target is invoked. Matches
are evaluated first to last as specified on the command line and work in short-circuit
fashion, i.e. if one extension yields false, evaluation will stop.
-j, --jumptarget
This specifies the target of the rule; i.e., what to do if the packet matches it. The target
OTHER OPTIONS
-v, --verbose
Verbose output. This option makes the list command show the interface name, the
rule options (if any), and the TOS masks. The packet and byte counters are also listed,
with the suffix 'K', 'M' or 'G' for 1000, 1,000,000 and 1,000,000,000 multipliers
respectively (but see the -x flag to change this). For appending, insertion, deletion and
replacement, this causes detailed information on the rule or rules to be printed. -v
may be specified multiple times to possibly emit more detailed debug statements.
-w, --wait
Wait for the xtables lock. To prevent multiple instances of the program from running
concurrently, an attempt will be made to obtain an exclusive lock at launch. By default,
9. write
Syntax
Description
The writeutility allows you to communicate with other users, by copying lines from your
terminal to theirs.
When you run the write command, the user you are writing to gets a message of the format:
Any further lines you enter will be copied to the specified user's terminal. If the other user
wants to reply, they must run write as well.
When you are done, type an end-of-file or interruptcharacter. The other user will see the
message ‘EOF’ indicating that the conversation is over.
You can prevent people (other than the super-user) from writing to you with the mesg
command.
If the user you want to write to is logged in on more than one terminal, you can specify
which terminal to write to by specifying the terminal name as the second operand to the
write command. Alternatively, you can let write select one of the terminals; it will pick the
one with the shortest idle time. This is so that if the user is logged in at work and also dialed
up from home, the message will go to the right place.
The traditional protocol for writing to someone is that the string ‘-o’, either at the end of a
line or on a line by itself, means that it is the other person's turn to talk. The string ‘oo’
means that the person believes the conversation to be over.
Options
user The user to write to.
The specific terminal to write to, if the user is logged in to more than one
tty
session.
Examples
write hope
Write a message to the user hope. After entering this command, you will be placed on a
blank line, where everything you type will be sent to the other user (line by line). Typing the
interrupt character (CTRL-C, by default) will return you to the command prompt, and end
the write session.
10.mesg
The mesg command allows you control write access to your terminal by other users.
Syntax:
mesg [n|y]
Description:
The write command allows other users to send a message to your terminal session; the
mesg command is used to toggle these messages on or off.
Options
Prevents the display of terminal messages from other users. This is like using a "do not disturb"
n
sign.
Examples:
mesg y
mesg n
mesg
11. mail
Syntax
mail [OPTION...] [address...]
Options
-a, --append=HEADER: VALUE Append given header to the message being sent.
-e, --exist Return true if mail exists.
-E, --exec=COMMAND Execute COMMAND.
-f, --file[=URL] Operate on given mailbox URL. The default mailbox is ~/mbox.
-F, --byname Save messages according to sender.
-H, --headers Write a header summary and exit.
-i, --ignore Ignore interrupts.
-n, --norc Do not read the system mailrc file.
-N, --nosum Do not display initial header summary.
-p, --print Print all mail to standard output.
-q, --quit Cause interrupts to terminate program.
-r, --read Same as -p
-s, --subject=SUBJ Send a message with a Subject of SUBJ.
-t, --to Precede message by a list of addresses.
-u, --user=USER Operate on USER’s mailbox.
--license Print license and exit.
--external-locker=PATH Set full path of the external locker program
--lock-expire-timeout=SECONDS Number of seconds after which the lock expires.
Examples
mesg y
mesg n
mesg
11. mail
Opens the mail program and displays the first message in the mailbox, if any. If mail is found,
the user is placed at a mail command prompt; type ? for a list of commands.
mail [email protected]
Viva Questions
Check if there is any inactive interfaces on the system. If yes display their configuration
information along with the active ones.
Adding/Deleting Users
Adding a user is easy. The command used is: useradd “name of the user”
Note – You must be logged-in as root to add, delete, and modify users. It is not
recommended to stay logged-in as root other than when necessary and only certain
members should have root access.
Example:
useradd roman
You can then use “su” plus the name of the user you just added to logon. “exit” will take you
out.
These commands are very basic, but there are other options we have as well. Options:
-d sets home directory for the user (if other than the default which is: /home/”user’s
name”)
-m creates the home directory
Using the –d option on its own will only set the home directory for the user, but does not
create it.
You can see I confirm this by “echo $HOME” which tells me my home directory and I use “ls”
to confirm.
If you just add the user, default directory is /home/”users name” and you can just use the –
m to create.
Lastly, using the “-r” option along with userdel will delete the user as well as the home
directory.
Changing Passwords
If you are logged in as root, the command is “username” password.
However, say I want to add roman to the group accounting and make his primary
group sales. We can add the “-G” option (other groups).
“-G” basically says add this user to a new group, but keep them in the old one (append).
Note: The groups must exit before we can add users to them.
Modifying Users
If a user is created and you just want to add that user to a group, or change the home
directory, etc:
Learning Outcome:
To add and delete the users by accessing the root user.
Viva Questions
Create a new user called user1 and this user to the sudo configuration file. Switch to this
new user and make sure you can execute root level commands.
Aim: Local Security Principles: Understanding Linux Security, Understand the Uses of root,
Using the sudo Command, Working with Passwords, permissions modification using
chmod. Chown, chgrp
User Accounts
The Linux kernel allows properly authenticated users to access files and applications. While
each user is identified by a unique integer (the user id or UID), a separate database
associates a username with each UID. Upon account creation, new user information
is added to the user database and the user's home directory must be created and populated
with some essential files. Command line programs such as useradd and userdel as well
as GUI tools are used for creating and removing accounts.
For each user, the following seven fields are maintained in the /etc/passwd file:
Password User password (or the character x if the Is never shown in Linux when it is
password is stored in being typed; this stops prying
the /etc/shadow file) in encrypted eyes
format
predefined accounts
Group ID The primary Group ID (GID); Group Will be covered in detail in the
(GID) Identification Number stored in chapter on Processes
the /etc/group file
User Info This field is optional and allows insertion For example: Rufus T. Firefly
of extra information about the user such
as their name
Types of Accounts:
By default, Linux distinguishes between several account types in order to isolate processes
and workloads. Linux has four types of accounts:
System
Normal
Network
For a safe working environment, it is advised to grant the minimum privileges possible and
necessary to accounts, and remove inactive accounts. The last utility, which shows the last
time each user logged into the system, can be used to help identify potentially inactive
accounts which are candidates for system removal.
Root is the most privileged account on a Linux/UNIX system. This account has the ability to
carry out all facets of system administration, including adding accounts, changing user
passwords, examining log files, installing software, etc. Utmost care must be taken when
using this account. It has no security restrictions imposed upon it.
When you are signed in as, or acting as root, the shell prompt displays '#’ (if you are
using bash and you haven’t customized the prompt as we discuss elsewhere in this course).
This convention is intended to serve as a warning to you of the absolute power of this
account.
Operations that
Require root
Privileges
Creating,
removing and
managing user
accounts.
Managing
software
Regular account users of Linux distributions may be allowed to install software packages,
update some settings, and apply various kinds of changes to the system.
However, root privilege is required for performing administration tasks such as restarting
services, manually installing packages and managing parts of the filesystem that are outside
the normal user’s directories.
1. At the command prompt, as root type useradd <username>and press the ENTER key.
2. To set the initial password, type passwd <username> and press the ENTER key.
The New password: prompt is displayed.
In Linux you can use either su or sudo to temporarily grant root access to a normal user;
these methods are actually quite different. Listed below are the differences between the
two commands.
su sudo
When elevating privilege, you need to enter When elevating privilege, you need to enter
the rootpassword. Giving the root the user’s password and not
password to a normal user
Once a user elevates to the root account Offers more features and is considered
using su, the user can do anything that more secure and more configurable. Exactly
the root user can do for as long as the user what the user is allowed to do can be
wants, without being asked again for a precisely controlled and limited. By default
password. the user will either always have to keep
giving their password to do further
operations with sudo, or can avoid doing so
for a configurable time interval.
The command has limited logging features. The command has detailed logging
features.
Permissions
The Unix operating system (and likewise, Linux) differs from other computing environments
in that it is not only a multitasking system but it is also a multi-user system as well.
What exactly does this mean? It means that more than one user can be operating the
computer at the same time. While your computer will only have one keyboard and monitor,
it can still be used by more than one user. For example, if your computer is attached to a
network, or the Internet, remote users can log in via telnet or ssh (secure shell) and operate
the computer. In fact, remote users can execute X applications and have the graphical
output displayed on a remote computer. The X Windows system supports this.
The multi-user capability of Unix is not a recent "innovation," but rather a feature that is
deeply ingrained into the design of the operating system. If you remember the environment
in which Unix was created, this makes perfect sense. Years ago before computers were
"personal," they were large, expensive, and centralized. A typical university computer
system consisted of a large mainframe computer located in some building on campus
and terminals were located throughout the campus, each connected to the large central
computer. The computer would support many users at the same time.
File permissions
Linux uses the same permissions scheme as Unix. Each file and directory on your system is
assigned access rights for the owner of the file, the members of a group of related users,
and everybody else. Rights can be assigned to read a file, to write a file, and to execute a file
(i.e., run the file as a program).
To see the permission settings for a file, we can use the ls command as follows:
Let's try another example. We will look at the bash program which is located in
the /bin directory:
In the diagram below, we see how the first portion of the listing is interpreted. It consists of
a character indicating the file type, followed by three sets of three characters that convey
the reading, writing and execution permission for the owner, group, and everybody else.
chmod
The chmod command is used to change the permissions of a file or directory. To use it, you
specify the desired permission settings and the file or files that you wish to modify. There
are two ways to specify the permissions, but I am only going to teach one way.
It is easy to think of the permission settings as a series of bits (which is how the computer
thinks about them). Here's how it works:
and so on...
Here is a table of numbers that covers all the common settings. The ones beginning with "7"
are used with programs (since they enable execution) and the rest are for other kinds of
files.
Value Meaning
(rwxr-xr-x) The file's owner may read, write, and execute the file. All others may
755 read and execute the file. This setting is common for programs that are used by all
users.
(rwx------) The file's owner may read, write, and execute the file. Nobody else has
700 any rights. This setting is useful for programs that only the owner may use and must
be kept private from others.
666 (rw-rw-rw-) All users may read and write the file.
(rw-r--r--) The owner may read and write a file, while all others may only read the
644 file. A common setting for data files that everybody may read, but only the owner
may change.
(rw-------) The owner may read and write a file. All others have no rights. A common
600
setting for data files that the owner wants to keep private.
Directory permissions
The chmod command can also be used to control the access permissions for directories. In
most ways, the permissions scheme for directories works the same way as they do with
files. However, the execution permission is used in a different way. It provides control for
access to file listing and other things. Here are some useful settings for directories:
Value Meaning
(rwxrwxrwx) No restrictions on permissions. Anybody may list files, create new files
777
in the directory and delete files in the directory. Generally not a good setting.
(rwx------) The directory owner has full access. Nobody else has any rights. This
700 setting is useful for directories that only the owner may use and must be kept
private from others.
Becoming the superuser for a short while
[me@linuxbox me]$ su
Password:
[root@linuxbox me]#
After executing the su command, you have a new shell session as the superuser. To exit the
superuser session, type exitand you will return to your previous session.
In some distributions, most notably Ubuntu, an alternate method is used. Rather than
using su, these systems employ thesudo command instead. With sudo, one or more users
are granted superuser privileges on an as needed basis. To execute a command as the
superuser, the desired command is simply preceeded with the sudo command. After the
command is entered, the user is prompted for the user's password rather than the
superuser's:
You can change the owner of a file by using the chown command. Here's an example:
Suppose I wanted to change the owner of some_file from "me" to "you". I could:
[me@linuxbox me]$ su
Password:
[root@linuxbox me]# chown you some_file
Notice that in order to change the owner of a file, you must be the superuser. To do this,
our example employed the sucommand, then we executed chown, and finally we
typed exit to return to our previous session.
The group ownership of a file or directory may be changed with chgrp. This command is
used like this:
In the example above, we changed the group ownership of some_file from its previous
group to "new_group". You must be the owner of the file or directory to perform a chgrp.
Learning Outcome:
Have a good grasp of best practices and tools for making Linux systems as secure as
possible.
Understand the powers and dangers of using the root (superuser) account.
Know how to use the sudo command to perform privileged operations while restricting
enhanced powers as much as feasible.
Know how to work with passwords, including how to set and change them.
Viva Questions
With a newly created user look at the password aging for the user, modify the
expiration date and check what has changed?
Program 21
Network Operations:
a) Introduction to Networking: An Ubuntu machine can be connected to internet in two
ways - wired and wireless. Both ways require a network interface card, IP address, subnet
mask, default gateway, and DNS server. The foremost step is to find and configure a
network interface by using following command:
$ifconfig
eth0 Link encap:Ethernet HWaddr 00:21:9b:ef:a3:db
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
Interrupt:16
There are two interfaces in list – eth0 and lo. eth0 can be configured to access internet since
lo is the loopback interface. Following steps are followed to manually configure eth0.
1. Open System Settings->Network Connections.
2. Click on options button.
5. Click on Add button and assign IP address, Netmask, and Gateway to the newly
created connection.
6. Add DNS servers and save the connection.
Once the configuration is over, ifconfig command can be used to verify it as shown below:
$ifconfig
collisions:0 txqueuelen:0
$ping
ping www.google.com
^C
The ping command just shown continuously pings the host www.google.com. After a few
pings, press Ctrl+C to end the pings, and the last few lines show you how many of the ping
requests succeeded.
$traceroute
traceroute www.facebook.com
7 ***
Using traceroute, you can see where the bottlenecks are along the way if your network
communication is stalling.
Browsers can be classified as graphical and non-graphical. Following are a few browsers
used in Linux:
2. Chrome is Google's web browser that is meant to be simple, extensible and fast. As
well, you can use extensions like in Firefox.
3. Konqueror is KDE's advanced file manager, web browser and document viewer.
Konqueror is an open source web browser that supports the current web standards.
5. Dillo is a lightweight and fast Internet browser. It does not have as many features as
some of the other browsers listed here but it is well-suited for older computers that
do not have enough speed or memory to run a full-featured browser.
7. Lynx is a character-based web browser that can be run inside a terminal or on the
console.
8. Links is a browser that may be be run in either text mode, or graphical mode.
10. Midori is a fast, lightweight graphical web browser based on WebKit. Often used
with the Xfce desktop environment.
On the Windows machine, go to Start –> All Programs –> Accessories –> run and type the
command:
\\computer_name\share_name
6. Type the Ubuntu computer name and the share name of the resource. You will get a
prompted to enter your credentials. Type your Ubuntu username and password and click
‘OK’
Learning Outcome:
Explain many basic networking concepts including types of networks and addressing
issues.
Know how to configure network interfaces and use basic networking utilities, such
as ifconfig, ip, ping, route& traceroute.
Transfer files to and from clients and servers using both graphical and text mode
applications, such as Filezilla, ftp, sftp, curl and wget.
Viva Questions
Practice the Lab exercises for Networking Operations, Chapter 12 of your edx
course.
Program 22
Aim: Process Oriented Commands:
Learning Outcome:
Use at, cron, and sleep to schedule processes in the future or pause them.
Viva Questions
Create a job that writes the date to an output file thrice, with a gap of 60 seconds
and 180 seconds. Check whether the job is running and bring it to foreground job.
Stop the foreground job and make it run in the background. Finally, kill the
background job and verify its status.
Program 23
Aim: Process Scheduling Commands
Linux and Unix provides sophisticated facilities to schedule a job to run at a specified time of
day.
The commands used for the purpose are:
At allows fairly complex time specifications, extending the POSIX.2 standard. It accepts
times of the form HH:MM to run a job at a specific time of day. (If that time is already past,
the next day is assumed.) You may also specify midnight, noon, or teatime (4pm) and you
can have a time-of-day suffixed with AM or PM for running in the morning or the evening.
You can also say what day the job will be run, by giving a date in the form month-
name day with an optional year, or giving a date of the
form MMDDYY or MM/DD/YY or DD.MM.YY. The specification of a date must follow the
specification of the time of day. You can also give times like now + count time-units, where
the time-units can be minutes, hours, days, or weeks and you can tell at to run the job
today by suffixing the time with today and to run the job tomorrow by suffixing the time
with tomorrow.
For example, to run a job at 4pm three days from now, you would do at 4pm + 3 days, to
run a job at 10:00am on July 31, you would do at 10am Jul 31 and to run a job at 1am
tomorrow, you would do at 1am tomorrow.
OPTIONS
-m: Send mail to the user when the job has completed even if there was no output.
-f file: Reads the job from file rather than standard input.
-v: Shows the time the job will be executed. Times displayed will be in the format "1997-02-
20 14:50" unless the environment variable POSIXLY_CORRECT is set; then, it will be "Thu
Feb 20 14:50:00 1996".
-c: cats the jobs listed on the command line to standard output.
DESCRIPTION
A crontab file contains instructions to the cron(8) daemon of the general form: ``run this
command at this time on this date''. Each user has their own crontab, and commands in any
given crontab will be executed as the user who owns the crontab. Uucp and News will
usually have their own crontabs, eliminating the need for explicitly running su(1) as part of a
cron command.
SHELL=/bin/sh
MAILTO=paul
23 0-23/2 * * * echo "run 23 minutes after midn, 2am, 4am ..., everyday"
Learning Outcome:
VIVA QUESTIONS
What server processes get initialized during system startup and then wait for a user
or system request indicating that their service is required?
Give an example of processes that are scheduled to run but are then disconnected
form the terminal.
Give all the possible states of processes.
What do you mean by niceness?
What is the unique identifier of a process?
What is the symbol for a low priority process?
What is the symbol for a high priority process?
Where is the crontab file located?
Create job using at to back up files in one directory to another 10 minutes from now.
Set up a cron job to backup the files in one directory to another every day at 10 am.
Put the commands in file called mycron.
Program 24
Aim: Regular Expressions, Redirections and Filters in Linux.
SYNOPSIS
DESCRIPTION
More is a filter for paging through text one screenful at a time. This version is especially
primitve. Users should realize that less(1) provides more(1) emulation and extensive
enhancements.
OPTIONS
Command line options are described below. Options are also taken from the environment
variableMORE (make sure to precede them with a dash (``-'')) but command line options will
override them.
-num: This option specifies an integer which is the screen size (in lines).
-d: more will prompt the user with the message "[Press space to continue, 'q' to quit.]" and
will display "[Press 'h' for instructions.]" instead of ringing the bell when an illegal key is
pressed.
-l: more usually treats ^L (form feed) as a special character, and will pause after any line that
contains a form feed. The -l option will prevent this behavior.
-f: Causes more to count logical, rather than screen lines (i.e., long lines are not folded).
-p: Do not scroll. Instead, clear the whole screen and then display the text.
-c: Do not scroll. Instead, paint each screen from the top, clearing the remainder of each line
as it is displayed.
2. wc, or "word count,": prints a count of newlines, words, and bytes for each input file.
Description:
wc prints newline, word, and byte counts for each FILE, and a total if more than oneFILE is
specified. With no FILE, or when FILE is a dash ("-"), wc operates on standard input. (A word
is a non-zero-length sequence of characters delimited by white space.)
The options below may be used to select which counts are printed. Counts are always in the
following order: newline, word, character, byte, maximum line length.
Options:
3. diff: analyzes two files and prints the lines that are different. Essentially, it outputs a set
of instructions for how to change one file in order to make it identical to the second file.
It does not actually change the files; however, it can optionally generate a script (with the -
e option) for the program ed (or ex which can be used to apply the changes.
SYNOPSIS
DESCRIPTION
Mandatory arguments to long options are mandatory for short options too.
-M, --month-sort- compare (unknown) < `JAN' < ... < `DEC'
SYNOPSIS
DESCRIPTION
Discard all but one of successive identical lines from INPUT (or standard input), writing to
OUTPUT (or standard output).Mandatory arguments to long options are mandatory for
short options too.
OPTIONS
-c, --count: prefix lines by the number of occurrences
-d, --repeated : only print duplicate lines
Grep searches the named input FILEs (or standard input if no files are named, or the file
name - is given) for lines containing a match to the given PATTERN. By default, grep prints
the matching lines.
In addition, two variant programs egrep and fgrep are available. Egrep is the same as grep -
E.Fgrep is the same as grep -F.
OPTIONS
-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines. Places a line containing --
between contiguous groups of matches.
-a, --text
-B NUM, --before-context=NUM
Print NUM lines of leading context before matching lines. Places a line containing --
between contiguous groups of matches.
-C NUM, --context=NUM
Print NUM lines of output context. Places a line containing -- between contiguous
groups of matches.
-b, --byte-offset
Print the byte offset within the input file before each line of output.
Redirection Operators:
Redirection is one of Unix's strongest points. Ramnick explains this concept in this article. He
talks about Input, Output Redirection. He cites many simple and useful ways in which we
can put redirection to good use.
Introduction
For those of you'll who have no idea what Redirection means, let me explain it in a few
words. Whenever you run a program you get some output at the shell prompt. In case
youdon't want that output to appear in the shell window, you can redirect it elsewhere. you
can make the output go into a file...or maybe go directly to the printer.. or you could make it
disappear :)
This is known as Redirection. Not only can the output of programs be redirected, you can
also redirect the input for programs. I shall be explaining all this in detail in this article. Lets
begin...
File Descriptors
One important thing you have to know to understand Redirection is file descriptors. In Unix
every file has a no. associated with it called the file descriptor. And in Unix everything is a
file. Right from your devices connected to your machine to the normal text files storing
some information - all of these are looked at, as files by the Operating System.
Similarly even your screen on which your programs display their output are files for Unix.
These have file descriptors associated with it. So when a program actually executes it sends
its output to this file descriptor and since this particular file descriptor happens to be
pointing to the screen, the output gets displayed on the screen. Had it been the file
descriptor of the printer, the output would have been printed by the printer. (There are
ofcourse other factors which come into play, but I guess you got the idea of how everything
is a file and you send whatver you want to particular files descriptors)
Whenever any program is executed (i.e. when the user types a command) the program has
3 important files to work with. They are standard input, standard output, and standard
error. These are 3 files that are always open when a program runs. You could kind of
consider them to be inherently present for all programs (For the techies.. basically when a
child process is forked from a parent process, these 3 files are made available to the child
process). For the rest, just remember that you always have these 3 files with you whenever
you type any command at the prompt. As explained before a file descriptor, is associated
with each of these files -
File
Descriptor Points to -
Descriptor
0 Standard Input (Generally Keyboard)
1 Standard output (Generally Display/Screen)
2 Standard Error Ouput (Generally Display/Screen)
You could redirect any of these files to other files. In short if you redirect 1 (standard
output) to the printer, your programs output would start getting printed instead of being
displayed on the screen.
What is the standard input? That would be your keyboard. Most of the times since you
enter commands with your keyboard; you could consider 0 to be your keyboard. Since you
get the output of your command on the screen, 1 would be the screen (display) and the
errors as well are shown on the screen to you, so 2 would also be the screen.
For those of you'll who like to think ahead of what is being discussed... you'll must have
already understood that you can now avoid all those irritating, irrelevant error messages
you often get while executing some programs. You could just redirect the standard error (2)
to some file and avoid seeing the error messages on the screen!!
Output Redirection
The most common use of Redirection is to redirect the output (that normally goes to the
terminal) from a command to a file instead. This is known as Output Redirection. This is
generally used when you get a lot of output when you execute your program. Often you see
that screens scroll past very rapidly. You could get all the output in a file and then even
transfer that file elsewhere or mail it to someone.
The way to redirect the output is by using the ' > ' operator in shell command you enter. This
is shown below. The ' > ' symbol is known as the output redirection operator. Any command
that outputs its results to the screen can have its output sent to a file.
$ ls > listing
The ' ls ' command would normally give you a directory listing. Since you have the ' > '
operator after the ' ls ' command, redirection would take place. What follows the ' > ' tells
Unix where to redirect the output. In our case it would create a file named ' listing ' and
write the directory listing in that file. You could view this file using any text editor or by
using the cat command.
Input Redirection
Input Redirection is not as popular as Output Redirection. Since most of the times you
would expect the input to be typed at the keyboard. But when it is used effectively, Input
Redirection can be of great use. The general use of Input Redirection is when you have some
kind of file, which you have ready and now you would like to use some command on that
file.
You can use Input Redirection by typing the ' < ' operator. An excellent example of Input
Redirection has been shown below.
The above command would start the mail program with contents of the file named '
my_typed_letter ' as the input since the Input Redirection operator was used.
Note: You can't have Input Redirection with any program/command. Only those commands
that accept input from keyboard could be redirected to use some kind of text files as their
input. Similarly Output Redirection is also useful only when the program sends its output to
the terminal. In case you are redirecting the output of a program that runs under X, it would
be of no use to you.
Error Redirection
This is a very popular feature that many Unix users are happy to learn. In case you have
worked with Unix for some time, you must have realised that for a lot of commands you
type you get a lot of error messages. And you are not really bothered about those error
messages. For example whenever I perform a search for a file, I always get a lot
ofpermission denied error messages. There may be ways to fix those things. But the simplest
way is to redirect the error messages elsewhere so that it doesn't bother me. In my case I
know that errors I get while searching for files would be of no use to me.
$ myprogram 2>errorsfile
This above command would execute a program named ' myprogram ' and whatever errors
are generated while executing that program would all be added to a file named ' errorsfile '
$ myprogram 2>>all_errors_till_now
The above command would be useful in case you have been saving all the error messages
for some later use. This time the error messages would append to the file rather than create
a new file.
You might realize that in the above case since I wasn't interested in the error messages
generated by the program I redirected the output to a file. But since those error messages
don't interest me I would have to go and delete that file created every time I run that
command. Else I would have several such files created all over whenever I redirect my
unwanted error output. An excellent way around is shown below
What's /dev/null ????? That something like a black hole. Whatever is sent to the ' /dev/null '
never returns. Neither does one know where it goes. It simple disappears. Isn't that fantastic
!! So remember.. whenever you want to remove something.. something that you don't want
...you could just send it to /dev/null
That's it!! Once you type the ' cat ' command, use the Redirection operator and add a name
for a file. Then start typing your line. And finally press Ctrl+D. You will have a file named '
filename ' in the same directory.
That would add the new line to the file named ' existing_file ' . Remember to use ' >> '
instead of ' > ' else you would overwrite the file.
This would add the contents of ' file1 ' and ' file2 ' and then write these contents into a new
file named ' file3 ' .
Redirection works with many commands besides normal ones such as ' cat ' or ' ls ' . One
example I could give you is in case you are programming using any language you could
redirect the output messages of the compilation of your code so that you can view them
later on. There are lots of commands where you can use Redirection. The more you use Unix
the more you will come to know.
Learning Outcome:
General Utilities for redirecting the output to files and applying filters to the output are
learned.
Viva Questions
What command will you use if you want to combine the contents of file1 and file2
in file3.
Give the symbol for redirection operator.
Give the symbol for redirection operator to append data to already created files.
How can you redirect your error messages to file named errorsfile?
What is the purpose of sort command?
What is the purpose of uniq command?
What is the purpose of grep command?
What is the purpose of diff command?
Give the command to count the number of lines in a file?
Give the command to count the number of words and characters in a file?
Create a file file_home having a list of all the files available in your home directory.
Create a file filez in your home directory, now append this file name to the file
created earlier, file_home.
Program 25
Aim: Bash Shell Scripting:
Most Linux users use the default bash shell, but those with long UNIX backgrounds with
other shells may want to override the default.
b) Syntax
Scripts require you to follow standard language syntax. Rules delineate how to define
variables and how to construct and format allowed statements, etc. The table lists some
special character usages within bash scripts:
Character Description
Used to add a comment, except when used as \#, or
#
as #! when starting a script
Used at the end of a line to indicate continuation on
\
to the next line
; Used to interpret what follows as a new command
$ Indicates what follows is a variable
Note that when # is inserted at the beginning of a line of commentary, the whole line is
ignored.
# This line will not get executed.
expr 8 + 8
echo $(expr 8 + 8)
Using the $((...)) syntax: This is the built-in shell format. The syntax is as follows:
echo $((x+1))
Using the built-in shell command let. The syntax is as follows:
One of the more under-appreciated commands in shell scripting is the eval builtin. The eval
builtin takes a series of arguments, concatenates them into a single command, then
executes it. For example, the following script assigns the value 3 to the variable X and then
prints the value:
#!/bin/sh
eval X=3
echo $X
For such simple examples, the eval builtin is superfluous. However, the behavior of the eval
builtin becomes much more interesting when you need to construct or choose variable
names programmatically. For example, the next script also assigns the value 3 to the
variable X:
#!/bin/sh
VARIABLE="X"
echo $X
When the eval builtin evaluates its arguments, it does so in two steps. In the first step,
variables are replaced by their values. In the preceding example, the letter X is inserted in
place of $VARIABLE. Thus, the result of the first step is the following string:
X=3
In the second step, the eval builtin executes the statement generated by the first step, thus
assigning the value 3 to the variable X. As further proof, the echo statement at the end of
the script prints the value 3.
The eval builtin can be particularly convenient as a substitute for arrays in shell script
programming. It can also be used to provide a level of indirection.
The script below uses eval by creating a series of variables to hold the values of a simulated
array.
#!/bin/sh
COUNTER=0
VALUE="-1"
read VALUE
eval ARRAY_$COUNTER=$VALUE
done
COUNTER=$(expr $COUNTER '-' 1) # Subtract one for the blank value at the end.
COUNTERB=0;
done
This same technique can be used for splitting an unknown number of input values in a single
line as shown in the next listing:
#!/bin/sh
COUNTER=0
VALUE="-1"
read LIST
IFS=" "
eval ARRAY_$COUNTER=$VALUE
done
done
Learning Outcome:
Know how to test for properties and existence of files and other objects.
Viva Questions
Write a script that does ls for a nonexistent file, followed by display of the exit status
code. Then create a file and display the new exit status code. In each task, send the ls
output to /dev/null.
Aim: Write Script to find out biggest number from given three nos. No’s are supplied as
command line argument. Print error if sufficient arguments are not supplied
Shell Variables are an integral part of shell programming. They provide ability to store and
manipulate information within a shell program.
Answer:#!/bin/bash
# Algo:
# 1) START: Take three nos as n1,n2,n3.
# 2) Is n1 is greater than n2 and n3, if yes
# print n1 is bigest no goto step 5, otherwise goto next step
# 3) Is n2 is greater than n1 and n3, if yes
# print n2 is bigest no goto step 5, otherwise goto next step
# 4) Is n3 is greater than n1 and n2, if yes
# print n3 is bigest no goto step 5, otherwise goto next step
# 5) END
if [ $# -ne 3 ]
then
echo "$0: number1 number2 number3 are not given" >&2
exit 1
fi
n1=$1
n2=$2
n3=$3
if [ $n1 -gt $n2 ] && [ $n1 -gt $n3 ]
then
echo "$n1 is Biggest number"
elif [ $n2 -gt $n1 ] && [ $n2 -gt $n3 ]
then
echo "$n2 is Biggest number"
elif [ $n3 -gt $n1 ] && [ $n3 -gt $n2 ]
then
echo "$n3 is Biggest number"
elif [ $1 -eq $2 ] && [ $1 -eq $3 ] && [ $2 -eq $3 ]
then
Output:
n1= 10
n2= 200
n3= 4
n2 is the biggest number
Viva Questions
How can you change the $ prompt to your name?
What are keywords?
What is the difference between variable names and keywords?
How can you make a variable value to remain unchanged?
Give the syntax for if-else loop.
What are conditional statements?
What does $1 specify?
Give the command to display the number of arguments passed.
Indicate whether the following variable names are valid or invalid. If invalid, state the reason
for the same.
I. Number of years
II. Si-int
III. AVERAGE
IV. 458
V. Expr
VI. @abc
String Manipulation:
A string variable contains a sequence of text characters. It can include letters, numbers,
symbols and punctuation marks. Some examples: abcde, 123, abcde 123, abcde-123,
&acbde=%123
String operators include those that do comparison, sorting, and finding the length. The
following table demonstrates the use of some basic string operators.
Operator Meaning
[[ string1 > string2 ]] Compares the sorting order of string1 and string2.
At times, you may not need to compare or use an entire string. To extract the first character
of a string we can specify:
${string:0:1} Here 0 is the offset in the string (i.e., which character to begin from) where the
extraction needs to start and 1 is the number of characters to be extracted.
To extract all characters in a string after a dot (.), use the following expression: ${string#*.}
Boolean Expressions:
&& AND The action will be performed only if both the conditions
evaluate to true.
Note that if you have multiple conditions strung together with the && operator processing
stops as soon as a condition evaluates to false. For example if you have A && B && C and A
is true but B is false, C will never be executed.
Likewise if you are using the || operator, processing stops as soon as anything is true. For
example if you have A || B || Cand A is false and B is true, you will also never execute C.
Boolean expressions return either TRUE or FALSE. We can use such expressions when
working with multiple data types including strings or numbers as well as with files. For
example, to check if a file exists, use the following conditional test:
[ -e <filename> ]
Similarly, to check if the value of number1 is greater than the value of number2, use the
following conditional test:
Case Structure:
The case statement is used in scenarios where the actual value of a variable can lead to
different execution paths. Case statements are often used to handle command-line options.
case expression in
pattern1) execute commands;;
pattern2) execute commands;;
pattern3) execute commands;;
pattern4) execute commands;;
*) execute some default commands or nothing ;;
esac
Debugging:
While working with scripts and commands, you may run into errors. These may be due to an
error in the script, such as incorrect syntax, or other ingredients such as a missing file or
insufficient permission to do an operation. These errors may be reported with a specific
error code, but often just yield incorrect or confusing output. So how do you go about
identifying and fixing an error?
Debugging helps you troubleshoot and resolve such errors, and is one of the most
important tasks a system administrator performs
In bash shell scripting, you can run a script in debug mode by doing bash –x ./script_file.
Debug mode helps identify the error because:
In UNIX/Linux, all programs that run are given three open file streams when they are
started as listed in the table:
Using redirection we can save the stdout and stderr output streams to one file or
two separate files for later analysis after a program or command is executed
On the left screen is a buggy shell script. On the right screen the buggy script is
executed and the errors are redirected to the file"error.txt". Using "cat" to display
the contents of "error.txt" shows the errors of executing the buggy shell script
(presumably for further debugging).
Learning Outcome:
Use Boolean expressions when working with multiple data types including strings or
numbers as well as files.
Viva Questions
Write a script that takes exactly one argument, a directory name. The script should print
that argument back to standard output. Make sure the script generates a usage message if
needed and that it handles errors with a message.
The case statement is used in scenarios where the actual value of a variable can lead to
different execution paths. Casestatements are often used to handle command-line options.
Answer:
#!/bin/bash
if test $# = 3
then
case $2 in
+) let z=$1+$3;;
-) let z=$1-$3;;
/) let z=$1/$3;;
x|X) let z=$1*$3;;
*) echo Warning - $2 invalid operator, only +,-,x,/ operator allowed
exit;;
esac
echo Answer is $z
else
echo "Usage - $0 value1 operator value2"
echo " Where, value1 and value2 are numeric values"
echo " operator can be +,-,/,x (For Multiplication)"
fi
To make use of if-then-else and case statement to control the execution of statements.
Viva Questions
What terms signify the beginning and end of if block in if-then-else?
What terms signify the beginning and end of else block in if-then-else?
What is CASE statement?
When is CASE preferred over if-then-else?
What is $# used for?
Give the structure for CASE statement.
Give the advantages for case statement
What do you mean by shell scripting?
An integer is input through keyboard. Write a shell script to find out whether it is an odd
number or even number.
Answer: #!/bin/bash
# Algo:
# 1) Input number n
# 2) Set sum=0, sd=0
# 3) Find single digit in sd as n % 10 it will give (left most digit)
# 4) Construct sum no as sum=sum+sd
# 5) Decrment n by 1
# 6) Is n is greater than zero, if yes goto step 3, otherwise next step
# 7) Print sum
#
if [ $# -ne 1 ]
then
echo "Usage: $0 number"
echo " I will find sum of all digit for given number"
echo " For eg. $0 123, I will print 6 as sum of all digit (1+2+3)"
exit 1
fi
n=$1
sum=0
sd=0
while [ $n -gt 0 ]
do
sd=`expr $n % 10`
sum=`expr $sum + $sd`
n=`expr $n / 10`
done
echo "Sum of digits for given number is $sum"
Learning Outcome:
Makes use of if else statement and looping construct (do while).
VIVA QUESTIONS
In what situations you will prefer the use of while loop over for loop?
What does the keyword fi signify?
What terms signify the beginning and end of if block in if-then-else?
What terms signify the beginning and end of else block in if-then-else?
What is CASE statement?
When is CASE preferred over if-then-else?
What is $# used for?
Give the structure for CASE statement.
Give the advantages for case statement
Answer: #!/bin/bash
nouser=`who | wc -l`
echo -e "User name: $USER (Login name: $LOGNAME)" >> /tmp/info.tmp.01.$$$
echo -e "Current Shell: $SHELL" >> /tmp/info.tmp.01.$$$
echo -e "Home Directory: $HOME" >> /tmp/info.tmp.01.$$$
echo -e "Your O/s Type: $OSTYPE" >> /tmp/info.tmp.01.$$$
echo -e "PATH: $PATH" >> /tmp/info.tmp.01.$$$
echo -e "Current directory: `pwd`" >> /tmp/info.tmp.01.$$$
echo -e "Currently Logged: $nouser user(s)" >> /tmp/info.tmp.01.$$$
if [ -f /etc/redhat-release ]
then
echo -e "OS: `cat /etc/redhat-release`" >> /tmp/info.tmp.01.$$$
fi
if [ -f /etc/shells ]
then
echo -e "Available Shells: " >> /tmp/info.tmp.01.$$$
echo -e "`cat /etc/shells`" >> /tmp/info.tmp.01.$$$
fi
if [ -f /etc/sysconfig/mouse ]
then
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "Computer Mouse Information: " >> /tmp/info.tmp.01.$$$
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "`cat /etc/sysconfig/mouse`" >> /tmp/info.tmp.01.$$$
fi
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "Computer CPU Information:" >> /tmp/info.tmp.01.$$$
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
cat /proc/cpuinfo >> /tmp/info.tmp.01.$$$
if [ -d /proc/ide/hda ]
then
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "Hard disk information:" >> /tmp/info.tmp.01.$$$
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "Model: `cat /proc/ide/hda/model` " >> /tmp/info.tmp.01.$$$
echo -e "Driver: `cat /proc/ide/hda/driver` " >> /tmp/info.tmp.01.$$$
echo -e "Cache size: `cat /proc/ide/hda/cache` " >> /tmp/info.tmp.01.$$$
fi
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "File System (Mount):" >> /tmp/info.tmp.01.$$$
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
cat /proc/mounts >> /tmp/info.tmp.01.$$$
rm -f /tmp/info.tmp.01.$$$
Learning Outcome:
To make use of the bash commands in shell programming and view the system
configurations.
Viva Questions:
Program 31
Answer: #!/bin/bash
# Algo:
# 1) START: set value of i to 5 (since we want to start from 5, if you
# want to start from other value put that value)
# 2) Start While Loop
# 3) Check, Is value of i is zero, If yes goto step 5 else
# continue with next step
# 4) print i, decement i by 1 (i.e. i=i-1 to goto zero) and
# goto step 3
# 5) END
#
i=5
while test $i != 0
do
echo "$i"
i=`expr $i - 1`
done
Output:
54321
Viva Questions:
# !/bin/bash
echo "Total no of factorial wants"
read fact
ans=1
counter=0
while [ $fact -ne $counter ]
do
counter=`expr $counter + 1`
ans=`expr $ans \* $counter`
done
echo "Total of factorial is $ans"
output
Total no of factorial wants 5
Total of factorial is 120
Viva Questions:
What are the different types of looping constructs available?
Give the different ways you can use to initialize the for loop?
In what situations you will prefer the use of while loop over for loop?
What does the keyword fi signify?
What terms signify the beginning and end of if block in if-then-else?
What terms signify the beginning and end of else block in if-then-else?
Perform the above program using while loop.
Give all the syntax for for loop
Aim: Shell Script to manipulate file Operations of creating, editing, saving and comparing
files.
Answer: #!/bin/bash
echo -e “ creating file1”>> cat > file1
if [ $# -ne 3 ]
then
echo "$0: number1 number2 number3 are not given" >&2
exit 1
fi
n1=$1
n2=$2
n3=$3
if [ $n1 -gt $n2 ] && [ $n1 -gt $n3 ]
then
echo "$n1 is Biggest number"
elif [ $n2 -gt $n1 ] && [ $n2 -gt $n3 ]
then
echo "$n2 is Biggest number"
elif [ $n3 -gt $n1 ] && [ $n3 -gt $n2 ]
then
echo "$n3 is Biggest number"
elif [ $1 -eq $2 ] && [ $1 -eq $3 ] && [ $2 -eq $3 ]
then
echo "All the three numbers are equal"
else
echo "I cannot figure out which number is bigger"
fi
[Ctrl-C] // To save the file
$ /usr/ sh file1.sh // to execute the file
Learning Outcome:
To use the bash commands in shell programming for creating, editing and manipulation of
files.
VIVA QUESTIONS
What are the different purposes of cat command?
What is the command to execute a file?
What combination of keys is used to save a file?
What is the key combination to interrupt a process
Write a script performing all the operations (creating, copying, viewing and concatenating)
performed by cat command.
Answer: #!/bin/bash
nouser=`who | wc -l`
echo -e "User name: $USER (Login name: $LOGNAME)" >> /tmp/info.tmp.01.$$$
echo -e "Current Shell: $SHELL" >> /tmp/info.tmp.01.$$$
echo -e "Home Directory: $HOME" >> /tmp/info.tmp.01.$$$
echo -e "Your O/s Type: $OSTYPE" >> /tmp/info.tmp.01.$$$
echo -e "PATH: $PATH" >> /tmp/info.tmp.01.$$$
echo -e "Current directory: `pwd`" >> /tmp/info.tmp.01.$$$
echo -e "Currently Logged: $nouser user(s)" >> /tmp/info.tmp.01.$$$
if [ -f /etc/redhat-release ]
then
echo -e "OS: `cat /etc/redhat-release`" >> /tmp/info.tmp.01.$$$
fi
if [ -f /etc/shells ]
then
echo -e "Available Shells: " >> /tmp/info.tmp.01.$$$
echo -e "`cat /etc/shells`" >> /tmp/info.tmp.01.$$$
fi
if [ -f /etc/sysconfig/mouse ]
then
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "Computer Mouse Information: " >> /tmp/info.tmp.01.$$$
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "`cat /etc/sysconfig/mouse`" >> /tmp/info.tmp.01.$$$
fi
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
if [ -d /proc/ide/hda ]
then
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "Hard disk information:" >> /tmp/info.tmp.01.$$$
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "Model: `cat /proc/ide/hda/model` " >> /tmp/info.tmp.01.$$$
echo -e "Driver: `cat /proc/ide/hda/driver` " >> /tmp/info.tmp.01.$$$
echo -e "Cache size: `cat /proc/ide/hda/cache` " >> /tmp/info.tmp.01.$$$
fi
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
echo -e "File System (Mount):" >> /tmp/info.tmp.01.$$$
echo -e "--------------------------------------------------------------------" >> /tmp/info.tmp.01.$$$
cat /proc/mounts >> /tmp/info.tmp.01.$$$
rm -f /tmp/info.tmp.01.$$$
Learning Outcome:
Viva Questions
What is a shell?
How is shell programming better than using gcc compiler?
What is shell scripting?
Give the command to display CPU information.
Give the command to mount the file system.
What environmental variable is used to display the home folder?
What environmental variable is used to display the path?
What environmental variable is used to display the shell being used?
What command is used to display the present working directory?
What is the command uname used for?
Aim: Write script called say Hello, put this script into your startup file called .bash_profile,
the script should run as soon as you logon to system, and it print any one of the following
message in info box using dialog utility, if installed in your system, If dialog utility is not
installed then use echo statement to print message : -
Good Morning
Good Afternoon
Good Evening , according to system time.
Answer: #!/bin/bash
if [ $temph -lt 12 ]
then
mess="Good Morning $LOGNAME, Have nice day!"
fi
Learning Outcome:
Process scheduling through command line.
Viva Questions
Schedule birthdays of your 2 friends. Display HAPPY BIRTHDAY and the name of the friend
on the particular date.
PRINTING
Learning Outcome:
Viva Questions:
What is the command for removing a job from the printer queue?
What will the command and syntax if you need to print 5 copies of the same
document?
Display all the active jobs on the printer?
What is the purpose of lpr command?
What is the purpose of lpr –P command?
What is the purpose of lprm command?
What is the purpose of lpq command?
Send the job to the printer
Remove a job from the printer.
Display the jobs in the printer queue.