+ All Categories

Manual

Date post: 03-Nov-2014
Category:
Upload: usama-javed
View: 17 times
Download: 1 times
Share this document with a friend
Description:
Lab Manual
Popular Tags:
75
OPERATIN G SYSTEM LAB MANUAL Submitted To:- Sir Umair Ashraf Submitted By:- Usama Javed Roll # 21 5 th Semester CS Dept. NFC-IEFR
Transcript
Page 1: Manual

OPERATING

SYSTEM

LAB MANUAL

Submitted To:-

Sir Umair Ashraf

Submitted By:-

Usama JavedRoll # 215th SemesterCS Dept.NFC-IEFR

Page 2: Manual

1

TABLE OF CONTENTS

Lab No. 01: Linux Basic Installation………………........................................................ 2

Lab No. 02: Linux shell and Basic shell commands......................................................... 14

Lab No. 03: Command Line File Manipulation……........................................................ 17

Lab No. 04: Command Line File processing …................................................................. 20

Lab No. 05: Command line Text Editors (Vim)................................................................ 25

Lab No. 06: Managing the file system.............................................................................. 30

Lab No. 07: Command line Process Management........................................................... 35

Lab No. 08: Basic Bash Scripting, writing and executing bash scripts........................... 39

Lab No. 09: Advance Bash Scripting 1............................................................................ 42

Lab No. 10: Advance Bash Scripting 2............................................................................ 44

Lab No. 11: Introduction to gcc........................................................................................ 46

Lab No. 12: Linux Networking 1...................................................................................... 51

Lab No. 13: Linux Networking 2........................................................................................ 53

Page 3: Manual

2

Lab No. 01: Linux Basic Installation

Page 4: Manual

3

Lab No. 01: Linux Basic Installation

Objective:

This lab provides a basic step-by-step installation of Linux Operation system. A simple approach

has been adopted out of many ways available for different configuration.

Scope:

On completing this exercise, the students will be able to:

Install Linux operating system

Create and manage Linux disk partitions

Configure different system resources during installation

Select packages during installation

Useful Concepts:

Partition

A space in hard disk set aside as a separate disk and has separate file system

Mount point

A logical location in a file system that provide a link to another file system

Package

An application that can be installed on a UNIX/ Linux system.

Boot loader

A small program that runs a the system boot and starts an operating system

Page 5: Manual

4

Exercise-1:- This exercise demonstrates step-by-step installation of Linux Operation sys-tem. The procedure is shown in figures below as follows:

in the boot screen, press Enter

in the installation welcome screen, click Next

in the language selection screen, click Next

in the keyboard configuration screen, click Next

in the installation type screen, choose Server and click Next

in the disk partitioning screen, you can select the following option

o remove all linux partition

o remove all partion on this disk 

o keep all partition and use free space

If you choose manual partition, select free space and create the following partition:

Mount Point:  Size (MB)  File system Type 

/boot  200  ext3

--------  (size for RAM)*2  swap 

/  all available free space  ext3

Clicking Next

in the partition warning screen, click Yes in the partition removal screen, click Next in the partitioning removal warning screen, click Yes in the disk setup screen, click Next in the boot loader screen, click Next in the network configuration screen, click Next in the firewall configuration screen, click Next in the time zone selection screen, choose Asia/Riyadh in the root password screen, enter the root password (min. 6 characters) and confirm it, click

Next In the package group selection screen, you can select different packages to install. Pack-

ages are grouped in different categories. Choose packages of your choice to install. Server group has server packages like apache, hdcp, squid etc. If you did not select the server installation option in step five, here is the chance that you can select servers of your choice. After selecting packages click next to go to the next screen

in the about to install screen, click Next in the installation status screen, wait while files are installed

Page 6: Manual

5

Page 7: Manual

6

Page 8: Manual

7

Page 9: Manual

8

Page 10: Manual

9

Page 11: Manual

10

Page 12: Manual

11

Page 13: Manual

12

Page 14: Manual

13

Why did you put /boot in the first location of the hard drive and forced it to be a primary Partition?

We did so because Operating System can only be installed in primary partition.

What is the advantage of using different partitions for different sections of the file system?

Advantage of using different partition for different sections of the file system is to save our data from getting destroyed if any on the drive gets corrupt so that only that particular partition will be damaged.

Specifically describe the critical difference between the partitions /dev/hda1 and /dev/hda5.

/dev/hda1 is the first primary partition on hard disk, whereas, /dev/hda5 is first logical partition on hard disk. OS can only be installed on primary partition and not on logical or extended partition.

Why don’t you want to use root as the regular login on your machine?

It defeats the security model that's been in place for years. Applications are meant to be run with non-administrative security (or as mere mortals) so you have to elevate their privileges to modify the underlying system. For example you wouldn't want that recent crash of Rhythmbox to wipe out your entire /usr directory due to a bug. Or to prevent the vulnerability that allow an attacker to gain a ROOT shell.

Page 15: Manual

14

Lab No. 02: Linux shell and Basic shell commands

Page 16: Manual

15

Exercise-1:- This exercise illustrates how to view content of a directory and move around the file system.

To get a listing of the directory contents, type:

ls

For a long view of the listing with time stamps, file permissions and file ownerships type:

ls -l

To move to directory-name directory type:

cd directory-name

To go to the

 /etc

Directory you simply type

cd /etc

To go one step back type:

cd ..

To go to user's home directory, type:

cd ~

To display the path to the directory you r currently working in, type:

pwd

At any point using the TAB key after typing a few characters in at the bash prompt will make bash fill in the rest of the file or directory name that matches what you have typed. If there is more than one match, tap the tab key twice and it will list all the matches.

Exercise-2:- This exercise illustrates how to clear screen contents and display history of command already used in the shell.

If you what to see the list of all commands you have used on the shell, type:

history

To clear the terminal screen, type:

clear

Page 17: Manual

16

Exercise-3:- This exercise illustrates how to Display or change system date and display cal-endar of different months and years.

To display calendar of the current month type:

cal

To display calendar of the prev/current/next month type

cal -3

To display weeks that starts on Monday, type:

cal -m

To display calendar of March 1988, type:

cal 03 1988

 To display current system date, type:

date

To change date to Thu Mar 3 23:05:25 2009, type:

date –s "Thu Mar 3 23:05:25 2009"

Page 18: Manual

17

Lab No. 03: Command Line File Manipulation

Page 19: Manual

18

 Exercise -1:- This exercise illustrates how to View contents of a file.To view file contents on shell console, type:cat filenameTo merge contents of two or more files and display it on screen, typecat file1 file2 file3 ...To display a screenful text of file on the terminal, type:more filenameTo display file contents screenful at a time with page-up and page-down options, type:less filenameTo view first k lines of the file, type:head -n k filenamee.g, to display first 5 lines of the file myfile on the terminal, type;head -n 5 myfileTo display last 5 lines of the file myfile on the terminal, type;tail -n 5 myfile

Exercise -2:- This exercise illustrates the procedure of File Copy, move, rename and delete command.

To copy a file to the same directory with different name, type:

cp source_fiel_name destination_file_name

To copy a file to a different directory, e.g. from /home/cs to /root type:

cp /home/cs/myfile /root/myfile

To move a file to different destination, type:

mv cource destination

To rename a file, type:

mv oldname newname

To delete the file from directory, type:

rm filename

To delete the file from different directory, the filename must precede full path name, like:

rm /home/cs/myfile

To delete an empty directory, type: *Represents 0 or more characters in a filename or by it-self, all files in a directory. More details in next section? Represents a single character in a filename. hello?.txt can represent hello1.txt, helloz.txt, but not hello22.txt[ ]Can be used to represent a range of values, e.g. [0-9], [A-Z], etc. hello[0-2].txt represents the names hello0.txt,hello1.txt, and

Page 20: Manual

19

hello2.txt;Command separator. Allows you to execute multiple commands on a single line.cd /var/log ; less messages

rmdir directory_name

To delete a non-empty directory, type:

rm –r directory_name

To delete a file forcefully, type:

rm –f file_name

Exercise -3:- This exercise illustrates how to search for files and file types.

To search a file in the entire disc, locate command is used. Type:

locate filename

To search a file in a particular directory and subdirectories, use find command. Type:

find –name filename directory_name

To access a specific file, say myfile.txt, in the directory and subdirectories, use find command, type:

find . -name myfile.txt -print

To search for all files that begin with the characters com, starting in the directory /home, type:

find /home -name com* -print

To search for a file based on the file’s content instead of its name. use grep command. to search all files inthe current directory for the string students type:

grep students ./*

To search all files in the current directory for strings starting with stu and ending with nts, type:

grep stu*nts ./*

To find whether a file is binary file, an executable file or a regular text file etc, type:

file filename

Page 21: Manual

20

Lab No. 04: Command Line File Processing

Page 22: Manual

21

Lab No. 04: Command Line File processingExercise-1:- This exercise shows which types of files are used in linux and how to know about file typesLinux considers each device as file. There are many types of file that are used in Linux. Use ls –l com-mand to find the type of file. For example:javidali@JLaptop:/dev$ ls –l

crw-rw----+ 1 root audio 14, 4 2009-04-28 07:01 audiodrwxr-xr-x 3 root root 60 2009-04-28 12:01 buscrw------- 1 root dialout 5, 1 2009-04-28 07:01 consolelrwxrwxrwx 1 root root 11 2009-04-28 07:01 core -> /proc/kcoresrw-rw-rw- 1 root root 0 2009-04-28 07:01 logbrw-rw---- 1 root disk 8, 1 2009-04-28 12:01 sda1javidali@JLaptop:/dev$

In this example, first character in each row, I.e. the first colom represent the file type. The following table shows file types, representation symbols with short description.

Symbol File type Description

- Regular files text file, Postscript, graphics files, Hypertext (HTML), video file etcd Directories Files that act as containers to other files

b Block files Files that are used for block (parallel)devices. Data from such devices are read or written to in blocks.

c Character files Files that are used for character (serial) devices. Data from such de- vices are read or written to character by character

l Symbolic links Shortcut to other files or directories

s socket files Files that are used in communication

Regular files other than text files can be explored by using an appropriate program, as indicated in the table below. Follow the command with the name of the file to view it or omit the file name and select the file from the menu once the program is running.

File Typ e Application Nam e Command f or the application

Postscript gv (based on GhostView) gvPortable Document Format (PDF)

Adobe Acrobat Reader acroreadImage files XV xvImage files The Gimp gimpLaTeX ouput (DVI) xdvi xdviHypertext (HTML) Netscape NetscapeMP3 and MPEG gtv gtv

Exercise-2:- This exercise demonstrates how t o view and change access permi ss i ons for a file.

We noticed in exercise-1 that ls -l command earlier presented a long of listing file with a line like the following for each file:

-rw-r--r-- 1 root javidali 0 2009-04-28 08:26 newfile.txt

Page 23: Manual

22

Here the first character in the first column (-) indicates that the file is a normal file. The next 9 characters indicate the access permissions for the file. The next set of 9 characters is divided into 3 groups of 3 characters. Purpose of these characters is as under:

• (-) represents no permission

• (r) represents 'read' permission

• (w) represents 'write' permission

• (x) represents 'execute' permission

The three group represents user (owner of the file), group(to which the owner belongs) and others (any other user of the system) respectively.

Three characters in each group are for 'read', 'write' and 'execute' permission respectively.

In our example, the owner has 'read' and 'write' permission for the file and everyone else has only read permission.

For a normal file, read, write and execute permissions are obvious.

For a directory, read and write permissions mean that to read the contents of the directory and create new entries in the directory. Execute permission means that one can search in the directory but not read from or write to the directory.

You can use the chmod command to change the access permissions of a file or a directory. To specify permissions for a file with chmod, any of the following two methods can be used.

• use a symbolic mode

• use an octal mode

Symbolic mode use combination of the following symbols:

S y m bo l Meanin g u Userg

Group o Othera All (equals to ugo)+ Add a permission- Remove (take away) a permission r Read permissionw Write permissionx Execute permission

Then gives write permission to the group and read permission to others for all files in the current directory, type the command

Now look at The permissions again:Then take away the read and write permission from the owner of the file myscript.sh, group of the owner and all other users for the files newfile.txt, type the command

javidali@JLaptop:~$ chmod a-rw myscript.shThe result is:

javidali@JLaptop:~$ ls –l myscript.sh

Page 24: Manual

23

---x--x--x 1 root root 207 2009-04-10 15:55 myscript.shOften your home directory has important documents and needs to restrict access to it. If you want to takes all the three access permissions away from everyone but the user, use the command:

javidali@JLaptop:~$ chmod go-rwx ̃

Octal mode use the same symbols for user,group and other but for access permissions its uses octal num- bers.

Permission Octal Number Equivalent symbolRead 4 r--

Write 2 -w-

execute 1 --x

If two or more permissions are to be set, the octal numbers are added together. For example, r-x is equiva- lent to 4+1=5 and rw-r--r-- is equivalent to 644. now for example to give read,write and execute permis- sion to user, write permission to the group and read permission to others for the file mysscript.sh , type the command

javidali@JLaptop:~$ chmod 724 myscript.sh

Here is the result:

-rwx-w-r-- 1 root root 207 2009-04-10 15:55 myscript.shTo secure your home drive from everyone but the user, use the command:

javidali@JLaptop:~$ chmod 700 ̃

Exercise-3:- This exercise sho w s how to v i ew and change the own ership of the file

ls -l command is can be used to view the owner of a file. For example to know that who is the owner of the file newfile.txt, issue the following command.

student@JLaptop:~$ ls –l newfile.txt---x--x--x 1 student cs 207 2009-04-10 15:55 newfile.txt

Here column next to the number '1' represents that 'student' is the owner of this file , and next column in- dicates that group of this owner is 'cs'.

Use chown command to change the owner of a file. For example to change the owner of the file 'new- file.txt' from student to root, issue the following command.

javidali@JLaptop:~$ chown root newfile.txtThe result is:

javidali@JLaptop:~$ ls –l newfile.txt---x--x--x 1 root cs 207 2009-04-10 15:55 newfile.txt

Note that you have to change the group of the owner as well, for example, to change the owner and group of the file 'newfile.txt' both to root, try the following command.

T javidali@JLaptop:~$ sudo chown root:root newfile.txt

Page 25: Manual

24

The effect will be like:

javidali@JLaptop:~$ ls –l newfile.txt---x--x--x 1 root root 207 2009-04-10 15:55 newfile.txt

Exercise-4:- This exercise des c ribes the w ays to compre s s/un c ompress, files a n d maki n g archives of files for backup purposes.

Among many available utilities for archiving and compression purposes are the tar and gzip utilities. tar is an archiving utility while gzip is used for compressing the file size. Compressed files can be restored to their original form using gzip -d or gunzip or zcat. Now for example to backup the 'mydata' directory inside home directory of user 'student', we will first archive the directory and then compress the archive file. Steps are:

javidali@JLaptop:~$ sudo tar -cvf backup.tar /home/student/mydata//home/student/mydata/.synaptic//home/student/mydata/.synaptic/options../home/student/mydata/DriverInstall/sk98lin.tar.bz2/home/student/mydata/Music/javidali@JLaptop:~$

We can find that mydata directory and backup.tar file both have the same size. To reduce this size we have to compress the archive. Here is the command;

javidali@JLaptop:~$ gzip backup.tarOutput of this command is a file named backup.tar.gz

To uncompress the file again, issue the command

javidali@JLaptop:~$ gzip -d backup.tar.gzOr

javidali@JLaptop:~$ gunzip backup.tar.gzOr you can use tar command to uncompress and extract contents of the file. Example is:

javidali@JLaptop:~$ tar -xz backup.tar.gzWhere -z switch issues gzip command from within the tar command and -x switch

extract the contents. To list contents of an archive use -t switch with tar command:

javidali@JLaptop:~$ tar -t backup.tarAnd to extract the contents of the archive, issue the following command.

javidali@JLaptop:~$ tar -xvf backup.tar

Page 26: Manual

25

Lab No. 05: Command Line Text Editors (Vim)

Page 27: Manual

26

UExercise-1:- This exercise illustrates how to s t art the editor, move cursor around and exit form the editor.

To start the editor from command line, type

viAn empty file will be opened in the editor. If you want to open an existing file in the editor, type

vi filenameTo switch to 'Insert' mode, press:

i key

-- INSERT -- key word at the bottom will indicate that you are in an inserting mode and your cursor will start blinking, to go to the start of the line. Press

a

at command mode will take you to the current cursor position and you

can enter any text. To move cursor around while you are in command

mode, press

h key move left,

l key move right,

k key move up,

j key = move down

you can also use arrow keys while in insert mode to do

the same tasks. To switch back to command mode, press

Escape key

While in command mode, each command is preceded by colon ":"

To exit the editor without saving changes made to the file, switch to command mode and type,

:q!To save changes and exit the editor, switch to command mode and type the command,

:wqWhere "w" is for writing changes to the file and "q" is to quit or exit the editor

Exercise-2:- This exercise i l lustr a tes how to Work in c o mmand mode in vi edtor.

Press Escape key to switch to command mode and practice the following commands and observe the re- sults.

To replace one character under the cursor, type:

rto undo the last change to the file. Typing u again will re-do the change.

uTo delete character after the current cursor position

x

Exercise-3:- This exercise illustr a tes how to Copy, Cut and paste the text

Page 28: Manual

27

To cut text from the file, type,

dto cut multiple characters, type:

NUMdwher NUM is the numper of

characters to cut to cut the

whole line type:

ddto cut from current cursor position to the beginning of the line,type.

d^to cut from current cursor position to the end of the line.

d$to cut from current cursor position to the end of the word.

DwTo cut three lines from current cursor position downwards.

3ddYou can use the y command which similarly to the d command which is used just

to copy the text. To paste the buffer after the cursor position, type:

pto paste the buffer before the cursor position type:

PTo paste the text for the specified number of times, say 3, before the cursor position, type:

3P

Exercise- 4 :- This exercise illu s tr a tes how to format a program and check source code for for correctness.

You can use variable to set up the indentation for each level of

nesting in code. To set the shift width to 4 characters, type:

:set sw=4

To Shift the current line one shift width to the left, type:

:<<To Shift the current line three shift width to the right, type:

:3>>To check for matching parenthesis or brace in your code, place the cursor onto a parenthesis or brace andtype:

:%

Exercise -5:- This exercise illustrates how to Search Character/string in a file using vi.

To search a string forwards in the file, say "nfc", type:

/nfc

Page 29: Manual

28

To search a string backwards in the file, say "nfc", type:

? nfcTo repeat the previous search in the same direction, type:

nTo repeat the previous search in the same direction, type:

NTo search special characters in the file, type a backslash (\)

before the character. Some special characters that are used in

search expression and their meaning:

^ Beginning of the line. (At the beginning of a search expression)

. Matches a single character

* Matches zero or more of the previous character.$ End of the line, (At the end of the search expression)

[ ] Starts a set of matching, or non-matching expressions... For example: /f[iae]t matches either of these: fit fat fet In this form, it matches anything except these: /a[^bcd] will not match any of these, but anything with an a and another letter: ab ac ad

< > Put in an expression escaped with the backslash to find the ending or beginning

of a word. For example: /\<the\> should find only word the, but not words like these:

there and other.

There are two sets of commands used for character search. [f & F] and [t & T]

To search for a character forwards within one line, say 'j', type:

/fjOr

/tjTo search for a character backwards within one line, say 'j', type:

/FjOr

/Tj; or , command can be used to repeat these two sets of commands.

; repeats the last character search command in the same direction,

, repeats the command in the reverse direction

Page 30: Manual

29

Exercise -6:- This exercise ill u strates how to recover Your Work:

The VI editor keeps a temporary copy of your edited file, and when you save your work, it puts the con- tents of the temporary copy into the original file. If file is closed accidentally during editing, the

To recover the file named myfile, start the editor with –r option for recovery

vi -r myfileand save the recovered file then

Note: The -r option only works once per failed VI session.

Page 31: Manual

30

Lab No. 06: Managing the File System

Page 32: Manual

31

Lab No. 06: Managing the file system

Exercise-1:- This exercise illustr a tes how Multiple Disks in t h e File sy s t em are

re p resented. Each partition of the disk is mounted at a separate directory in the

filesystem. So, for example, a separate disk may be mounted at the directory /mnt. In

this case, every time you access something in directory/mnt, you are actually accessing a file on this separate disk. This is transparent to the user, but you canpeek at which disks are mounted where on a computer by using the df command in the shell. You will see something like this:

Filesystem 1k-blocks Used Available Use% Mounted /dev/hda8 497667 78511 393454 17% //dev/hda1 14607 2758 1 1095 20% /boot/dev/hda7 5308207 108534

03948063 22% /usr

/dev/hdc 609750 609750

0 100% /mnt/The first line indicates that the disk with symbolic name5 /dev/hda8 is mounted at the root

directory.

The second line indicates that another disk with symbolic name /dev/hda1 is mounted at subdirectory/boot. The third line is similar.

The disk in the fourth line represents the CD-ROM drive, which is mounted at /mnt/cdrom.

Exercise-2:- This exercise ill u str a tes how to recogn i z e disks.

To see all the disks and partitions on your system, you can list the files in

/dev directory. Use ls /dev command will will display all the device related

files.

To display only disk related files type:

ls /dev |grep ?d*output will be something like:

hda1 hda3 hda5

Page 33: Manual

32

hda7 hdb2 fd0 fd1 sda1 dsa8 sdb2 etc

Here is a brief description of file system names.

Disk file name Des c ription

fd0 First floppy

disk drive fd1 Second floppy

disk drive

hda First master hard disk drive (IDE-0

master) hdb First slave hard disk drive (IDE-0

slave) hdc Second mater hard disk (IDE-1

master)

sda First SCSI

disk dirve sdb Second SCSI

disk drive

Page 34: Manual

33

Exercise-3:- This exercise illustr a tes Recogni z i ng Partiti o ns. Enter the command

ls /dev |grep ?d*

To display only disk related files and the output will be something like:

hda1 hda3 hda5 hda7

hdb2 fd0 fd1 sda1 dsa8 sdb

Page 35: Manual

34

2Disk file name Des c ription

hda1 First master hard disk drive (IDE-0 master), first

primary partition hda3 First master hard disk drive (IDE-0

master), third partition

hda5 First master hard disk drive (IDE-0 master), 1st

logical partition Hda7 First master hard disk drive (IDE-0

master), 3rd logical partition hdb1 First slave hard disk drive

(IDE-0 slave), 1st partition

sda1 First SCSI disk drive, first

primary partition. sdb8 Second SCSI disk

drive, 4th logical partition

Exer c is e - 4 :- This exe r cise illu s tr a tes Mounting/un-mounting parti t ion:

To see the contents stored on a partition you must have a mount point in the root directory from where you can access those contents. To mount a partition, for example hda5 to /mnt directory, type:

mount /dev/hda5 /mnt

Doing this, you will be able to see the content of hda5 partition in

/mnt directory. To mount a Windows NTFS partition, type:

mount -ntfs-3g partition_path Mount_pointUn mounting partition, either type:

umount partitionOr e.g.

Or

umount mount_point

umount /dev/hda5

umount /mntTo locate a program file in the user's path, type:

Any of the to command will unmount the mounted partition /dev/hda5 on /mnt

Page 36: Manual

35

Lab No. 07: Command Line Process Management

Page 37: Manual

36

Lab No. 07: Command line Process Management

Exercise-1:- This exercise i l lustr a tes Listing Processes

You can view the processes that are currently running on the system with the ps command. Type ps now and you will see something like the following:

javidali@JLaptop:~$ psPID TTY

TIME CMD23985 pts/0 00:00:01 bash24001 pts/0 00:00:00 psjavidali@JLaptop:~$

This tells you that you are running 2 processes and the commands (CMD) used to start them were bash (your shell) and ps (the process you just started when you entered ps). The first column in the list, headed by PID, gives the process ID for each process, an integer used to uniquely identify each process. The next column, TTY, gives the terminal name to which the process is attached. The third column, TIME, gives the amount of time the process has been running for (or the amount of time it has been running since it was last sleeping or stopped).

Using ps by itself only gives information about processes that you own, which, unless you are a system administrator, is usually all the information you need. If you want information about all the processes running on the system, you can issue the ps aux command. This command combines 3 options (the nor- mal dash before options is not necessary) which, together, give information about all processes that have users have attached to them. Here is a (significantly trimmed) example of what this output might look like:

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMANDroot 1 0.0 0.0 1324 76 ? S Jul23 0:12 init [5] root 2 0.0 0.0 0 0 ? SW Jul23 0:21 [kflushd] root 3 0.0 0.0 0 0 ? SW Jul23 0:03 [kupdate] root 4 0.0 0.0 0 0 ? SW Jul23 0:00 [kpiod] root 5 0.0 0.0 0 0 ? SW Jul23 0:14 [kswapd]root 6 0.0 0.0 0 0 ? SW< Jul23 0:00 [mdrecoveryd]root 415 0.0 0.1 1548 160 ? S Jul23 0:02 syslogd -m 0 rpc 440 0.0 0.1 1472 252 ? S Jul23 0:00 portmaproot 456 0.0 0.0 0 0 ? SW Jul23 0:00 [lockd]root 500 0.0 0.2 5744 272 ? S Jul23 0:00 [ypbind]nobody 566 0.0 0.0 7616 24 ? S Jul23 0:00 [identd]...root 1006 14.7 24.7 62796 31612 ? R Jul23 53:50 /etc/X11/Xjavid 7892 0.0 1.2 7580 1564 ? S 14:15 0:00 gnome-session javid 7957 0.0 1.3

Page 38: Manual

37

4700 1700 ? S 14:15 1:39 sawmilljavid 7966 0.0 2.1 9336 2784 ? S 14:15 3:51 panel javid 7969 0.0 0.8 8404 1092 ? S 14:15 0:00 gmcjavid 7972 0.0 0.7 3560 968 ? S 14:15 0:11 xscreensaverjavid 7992 0.0 1.3 7676 1676 ? S 14:26 0:21 gnome-terminal javid 7994 0.0 0.6 2440 796 pts/0 S 14:26 0:01 bash

This listing gives a lot of information about the 100 or so processes that are probably currently executing on the system. For example, you can gather that the computer was rebooted last on July 23. You can see that X windows (/etc/X11/X) is using almost 25% of the computer’s memory at the moment and 15% of the CPU time. You can also view the current status (STAT) of each of the processes in the system. An R in this column means that the processing is currently “runnable” which, as you will learn when you take Operating Systems, means that the process is either currently running or in the ready queue, waiting to gain access to the processor. An S indicates that the process is “sleeping” (currently not waiting to use the processor). A W means that, in addition to sleeping, the process has been “swapped out” (not currently resident in memory but on the disk instead). Lastly, the < marks a process that is given higher priority than normal while waiting for the CPU.

Exercise-2:- This exercise illustr a tes how to terminate a Process

Sometimes you will come across a process that locks up and just won’t quit, no matter what you do. In this case, the only alternative is to force the process to quit. If the process is one that you started from the shell in the foreground, you can end it by typing Ctrl - C. If the process is running in the background, you will need to issue the kill command followed by a process ID. For example, to kill the Netscape process above, you would type:

kill 12504If this does not work, use the -9 (or -s SIGKILL) option to forcibly kill the process.

The kill command (or Ctrl - C) also comes in handy when you must kill a program that you wrote with an infinite loop!

Exercise-3:- This exercise illustr a tes how to Run a Process in the Background

When you run a program in Linux, it can either be run in the foreground or in the background. When you run a program in the foreground (which is the default), the resulting process must finish before you get another prompt in the shell. This is fine when you run short processes like ls, for example. However, if you want to run Netscape (for example) from the shell, you probably do not want to have to quit Netscape in order to get a new prompt to, say, copy a file. The alternative is to run Netscape in the background, which means that the new process will run concurrently with the shell prompt, and a prompt will be re- turned to you immediately. To run a program in the background, simply follow the command with an am- persand (&)

Page 39: Manual

38

character. For example, to run Netscape in the background, type:

netscape &Generally speaking, any time you run a program that generates its own window on the desktop, it is best to run it in the background.

If you start a program in the foreground by mistake and want to turn it into a background process, hit Ctrl- Z , which suspends the process. Then type

bgthis command restarts the currently suspended process in the background.

Page 40: Manual

39

Lab No. 08: Basic Bash Scripting, writing and executing bash scripts

Page 41: Manual

40

Lab No. 08: Basic Bash Scripting, writing and executing bash scriptsU

Exercise-1:- Hello w orld example. The script declares a string v a riable, s tores “HelloWorld” in it and finally prints the value of v a riable on t h e screen.

#!/bin/bash# declare STRING variableSTRING="Hello World"#print variable on a screenecho $STRING

Saving and executing the scripts

Save the above script in the file named

“hello_world.sh” Navigate to the directory

where the script is saved Execute the script

using the command “./hello_world.sh”

Exercise -2:- This exercise expl a i ns the use of Global vs. Local varia b l es

#!/bin/bash#Define bash global variable#This variable is global and can be used anywhere in this bash scriptVAR="global variable" function bash {#Define bash local variable#This variable is local to bash function only local VAR="local variable"echo $VAR}echo $VARbash# Note the bash global variable did not change# "local" is bash reserved word echo $VAR

Exercise -3:- This exercise illustrates Passing command line arguments to the ba s h script

#!/bin/bash# use predefined variables to access passed arguments#echo arguments to the shellecho $1 $2 $3 ' -> echo $1 $2 $3'# We can also store arguments from bash command line in special array args=("$@")#echo arguments to the shellecho ${args[0]} ${args[1]} ${args[2]} ' -> args=("$@"); echo ${args[0]}${args[1]} ${args[2]}'

#use $@ to print out all arguments at once echo $@ ' -> echo $@'# use $# variable to print out

Page 42: Manual

41

# number of arguments passed to the bash scriptecho Number of arguments passed: $# ' -> echo Number of arguments passed: $#'

Passing arguments to the scripts

./arguments.sh Bash Scripting TutorialHere ./arguments.sh is the filename and the remaining are the arguments passed to the script.

Exercise -4:- This exercise illustrat e s Executi n g shell c o mmands w i th bash

#!/bin/bash# use backticks " ` ` " to execute shell commandecho `uname -o`# executing bash command without backticks echo uname -o

Exercise -5:- This exercise illustrates Reading User Input

#!/bin/bashecho -e "Hi, please type the word: \c "read wordecho "The word you entered is: $word"echo -e "Can you please enter two words? " read word1 word2echo "Here is your input: \"$word1\" \"$word2\""echo -e "How do you feel about bash scripting? "# read command now stores a reply into the default build-in variable$REPLYreadecho "You said $REPLY, I'm glad to hear that! "echo -e "What are your favorite colours ? "# -a makes read command to read into an array read -a coloursecho "My favorite colours are also ${colours[0]}, ${colours[1]} and${colours[2]}:-)"

Page 43: Manual

42

Lab No. 09: Advance Bash Scripting 1

Page 44: Manual

43

Lab No. 09: Advance Bash Scripting 1TExercise-1:- Simple Bash if/else st at ement. In this example w e declare a variable named di- rectory and assign it a value. Then w e check in the if statement that the directo r y exi s ts o r not and the relevant message is p r inted on the screen acc o rdingly.

Please note the spacing inside the [ and ] brackets! Without the spaces, it won't work!

#!/bin/bash directory="./BashScripting"# bash check if directory exists if [ -d $directory ]; then

echo "Directory exists"else

fiecho "Directory does not exists

Exercise -2:- This exercise demon s trates Bash “for” loop

#!/bin/bash# bash for loopfor f in $( ls /var/ ); do

echo $fdone

Exercise -3:- This exercise demon s trates Bash while loop

#!/bin/bashCOUNT=6# bash while loopwhile [ $COUNT -gt 0 ]; do

echo Value of count is: $COUNTlet COUNT=COUNT-1

done

Exercise -4:- This exercise demon s trates Bash until loop

#!/bin/bashCOUNT=0# bash until loopuntil [ $COUNT -gt 5 ]; do

echo Value of count is: $COUNTlet COUNT=COUNT+1

done

Page 45: Manual

44

Lab No. 10: Advance Bash Scripting 2

Page 46: Manual

45

Lab No. 10: Advance Bash Scripting 2

Exercise -1:- This exercise demon s trates how to Declare si mple bash a rray

#!/bin/bash#Declare array with 4 elementsARRAY=( 'Debian Linux' 'Redhat Linux' Ubuntu Linux )# get number of elements in the arrayELEMENTS=${#ARRAY[@]}

# echo each element in array# for loopfor (( i=0;i<$ELEMENTS;i++)); do

echo ${ARRAY[${i}]}done

Exercise -2:- This exercise demon s trates how to Read file into bash array

#!/bin/bash#Declare array declare -a ARRAY#Open file for reading to arrayexec 10<bash.txt let count=0while read LINE <&10; do

ARRAY[$count]=$LINE ((count++))

doneecho Number of elements: ${#ARRAY[@]}# echo array's content echo ${ARRAY[@]}# close fileexec 10>&-

Exercise -3:- This exercise demon s trates Bash Functions

!/bin/bash# BASH FUNCTIONS CAN BE DECLARED IN ANY ORDERfunction function_B {

echo Function B.}function function_A {

echo $1}function function_D {

echo Function D.}function function_C {

echo $1}# FUNCTION CALLS# Pass parameter to function A function_A "Function A." function_B# Pass parameter to function Cfunction_C "Function C." function_D

Page 47: Manual

46

Lab No. 11: Introduction to gcc

Page 48: Manual

47

Lab No. 11: Introduction to gcc

Exercise-1:- This exercise demonstrates W r iting a C Program in linux test e d itors.

To write a C program, you can use any editor. Linux has a rich set of Code-oriented GUI Editors (with syntax highlighting, indentation, etc.) i.e. glimmer, nedit, gvim, kwrite, and xemacs etc. But if you are using the command line, you can try vim or emacs editor, we will use vim in our example.

Type the following on command

prompt. Vim introprogram.c

And you will have an empty file opened in the vim editor if the file intoprogram.c does not

exist before. Press I key to switch to insert mode and type the following program:

#include<stdoi.h>#include<stdio.h> Int main (){

Printf("\n welcome to gcc tutorial"); Return 0;}Hit ESC key to switch back to command mode and type

:wqto save the program and exit the editor.

Exercis e -2:- This exercise demonstrates Com p iling Prog r ams

You can learn more about g++ later by looking at the man pages. (There’s a lot there!) For now, we’ll just look at the basics.

To compile the C program of exercise 1, in the shell, simply type

gcc -o intro_program introporgram.cin the terminal window. The -o option gives the name of the executable to create; if omitted, the executa- ble will be called a.out.

In general you’ll probably want to compile programs with more options specified. Here is a better way to compile a program:

gcc -g -Wall -o intro_program introporgram.cThe -g option produces debugging information in the

executable. The -Wall option instructs the compile to

display “all warnings

To compile multiple source files into one executable, just include them all on the command line. For ex- ample, to compile

Prog1.c and prog2.c into a single executable called prog, type:

gcc -g Wall -o prog prog1.c prog2.c

Page 49: Manual

48

Once you have a working executable program, go to a terminal window to execute it. Make sure you are in the correct directory and then type the name of the executable program.Exercise-3:- This exercise expl a ins the used of Make utility

When you are creating large software projects, it is usually a good idea to break the code into multiple source files. This way, errors are usually easier to find and edit, and when you recompile the program you only need to recompile the file you changed and those upon which it depends. Of course, this can become confusing and complicated when the system becomes large. Linux has a powerful tool called make that allows you to efficiently manage a complex project and compile it efficiently. The make utility reads a file called a makefile that describes the files involved in the project and the dependencies between them.

Each line in a makefile is of the form:

targets: dependencies<Tab> commands

Here, targets is a list of target files separated by spaces and dependencies is a list of files on which the targets depend. In other words, if any of the files in a dependency list is modified, make should recompile and/or relink the target. The commands are the commands used to recreate the targets. (Note that the<Tab> preceding commands really must be a tab character and not several

spaces.) For example, consider the following simple makefile:

# A simple makefile

sort: sort.o list.og++ sort.o list.o -o sort sort.o: sort.cc sort.h g++ -g -c sort.cclist.o: list.cc list.h g++ -g -c list.cc

This file states that the executable sort is dependent on the object files sort.o and list.o. If either of these object files change, the command g++ sort.o list.o -o sort should be used to recreate (link) sort from the object files. The next two groups show how to create the object files. The first states that sort.o should be recreated (compiled using g++) if sort.cc or sort.h changes. (The -c option to g++ tells the compiler to only compile, creating object files, and not to link them together.) The third group does a similar thing for list.o. So, you can see that if, for example, list.h is modified,

list.o and then sort will need to be recreated but sort.o will not.

To use this makefile, it should be placed in the same directory as the source files and named Makefile. Then, execute make sort to compile and link everything.

Exercise-4:- This exercise demonstrates the Debugging process.

You can start up DDD by typing ddd in the shell, followed by the name of your executable program. In order for the source program to be visible to the debugger, you had to have compiled

Page 50: Manual

49

the program with the-g option, which includes debugging information in the executable. To simply run your program in DDD, press the Run button in the small floating window that appears. The output of your program will be dis- played in the window below your source code. The Interrupt button will stop a running program, the same way a Ctrl - C does in the shell. If you want to continue to run your program from where you left off, press the Cont button. Usually, when you are debugging a program, you want the program to stop execu- tion at some point so that you can examine the value of a variable or check some other part of your pro- gram. To stop your program, you set a breakpoint. To set a breakpoint, find the line of your source code where you wish to stop and click to the left of it with the left mouse button. Then press the Break button (with the stop sign) below the menu bar. A stop sign icon should appear to the left of the line. Now, when you run your program, execution will stop every time this line is reached. You can set as many break- points as needed. To clear a breakpoint, do the same thing, except this time the stop sign will be dimmed and the button will say Clear instead.

If you wish to have your program stop every time the value of some variable changes, you can set a watchpoint. To set a watchpoint, left-click on a variable name in your source code and press the Watch button below the menu bar.

Once your program has stopped, there are two options (buttons) for stepping through your program a line at a time — Step and Next. To step means to proceed to the next line of source code in your program, even if it is inside a function. The Next option advances to the next source line, but treats function-calls as if they were single instructions. The Stepi and Nexti buttons behave similarly, but recognize individual machine language instructions, not lines of source code.

To view the value of a variable as your program runs, select that variable name by left-clicking on it and then press the Display button below the menu bar. A box with that variable’s value will appear in a new window above your source code.

These are the basics of DDD. But there is quite a bit more to learn if you desire. The display function of DDD, in particular, is quite sophisticated and flexible. Under the Help menu, you can find context sensi- tive help and a detailed manual (also available at

w.gnu.org/manual/ddd/). You will also notice that if you linger over a button with the cursor, a description of that button will appear.

Page 51: Manual

50

Exercise-5:- This exercise demonstrates the E x ecution of a program

To execute the program form the terminal window or a shell, type the name of the executable file (the output file of compiling process). For example, to run the program of exercise 1, type.

./introprogramWhere ./ is te relative path of the executable file named introprogram.

You can also use the ablolute path to execute a program or add the directory to the users search path inor- der to execute the program without referring path.

To use absolute path, for example your executable file is located at /home/cs, type:

/home/cs/introprogramTo at the directory cs to users search path, first type

Export PATH=$PATH:/home/csAnd then to run the program now just type

introprogram

Page 52: Manual

51

Lab No. 12: Linux Networking 1

Page 53: Manual

52

Lab No. 12: Linux Networking 1

Exercise -1:- This exercise illustrate how to Determining Your IP Address

Most modern PCs come with an Ethernet port. When Linux is installed, this device is called eth0. You can determine the IP address of this device with the ifconfig command.

[root@tmp]# ifconfig -aeth0 Link encap:Ethernet HWaddr 00:08:C7:10:74:A8inet addr:192.168.1.100 Bcast:192.168.1.255 Mask:255.255.255.0UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1RX packets:47379 errors:0 dropped:0 overruns:0 frame:0TX packets:107900 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:100RX bytes:4676853 (4.4 Mb) TX bytes:43209032 (41.2 Mb)Interrupt:11 Memory:c887a000-c887b000 [root@tmp]#

In this example, eth0 has an IP address of 192.168.1.100 and a subnet mask of 255.255.255.0. This com- mand gives good information on the interrupts, or PCI bus ID, used by card.

Exercise -2:- This exercise demon s trates how to Changing Your IP Address

You can give eth0 interface an IP address using the ifconfig command:

[root@tmp]# ifconfig eth0 10.0.0.1 netmask 255.255.255.0 upThe "up" at the end of the command activates the interface. To make this permanent each time you boot up you'll have to add this command in your /etc/rc.local file which is run at the end of every reboot.

Exercise-3:- This exercise demon s trates how to assign Multiple IP Addresses on a Single NIC

A virtual subinterface is also known as an IP alias. IP aliasing is one of the most common ways of creat- ing multiple IP addresses associated with a single NIC. Aliases have the name format parent-interface- name:X, where X is the sub-interface number of your choice.

The process for creating an IP alias is very similar to the steps outlined for the real interface in the previ- ous section, "Changing Your IP Address":

First ensure the parent real interface exists

Verify that no other IP aliases with the same name exists with the name you plan to use. In this we want to create interface eth0:0.

Exercise-4:- This exercise demonstrates how t o Create the virtual interf a ce w i th the ifcon- fig comma n d

root@tmp]# ifconfig eth0:0 192.168.1.99 netmask 255.255.255.0 up

Exercise-5:- This exercise demonstrates How to Activate/Shut Do w n Your NIC

The ifup and ifdown commands can be used respectively to activate and deactivate a NIC interface. You must have an ifcfg file in the /etc/sysconfig/network-scripts directory for these commands to work. Here is an example for interface eth0:

[root@bigboy tmp]# ifdown eth0

Page 54: Manual

53

Lab No. 13: Linux Networking 2

Page 55: Manual

54

Lab No. 13: Linux Networking 2

Exercise-1:- This exercise demonstrate How to View Your Current Routing Table

The netstat -nr command will provide the contents of the touting table. Networks with a gateway of0.0.0.0 are usually directly connected to the interface. No gateway is needed to reach your own directly connected interface, so a gateway address of 0.0.0.0 seems appropriate. The route with a destination ad- dress of 0.0.0.0 is your default gateway.

In the following example there are two gateways, the default and the one to 255.255.255.255 which is usually added on DHCP servers. It is a DHCP server in this case.

[root@tmp]# netstat -nrKernel IP routing tableDestination Gateway Genmask Flags MSS Window irtt Iface255.255.255.255 0.0.0.0 255.255.255.255 U 40 0 0 wlan0192.168.1.0 0.0.0.0 255.255.255.0 U 40 0 0 wlan0127.0.0.0 0.0.0.0 255.0.0.0 U 40 0 0 lo0.0.0.0 192.168.1.1 0.0.0.0 U

G40 0 0 wlan0

[root@tmp]#In this example, there are multiple gateways handling traffic destined for different networks on differentinterfaces.

[root@tmp]# netstat -nrKernel IP routing tableDestination Gateway Genmask Flags MSS Window irtt Iface172.16.68.64 172.16.69.19 255.255.255.224 40 0 0 eth1172.16.11.96 172.16.69.19

3255.255.255.224 UG

40 0 0 eth1172.16.68.32 172.16.69.19

3255.255.255.224 UG

40 0 0 eth1172.16.67.0 172.16.67.13

5255.255.255.224 UG

40 0 0 eth0172.16.69.192

0.0.0.0 255.255.255.192 U 40 0 0 eth1172.16.67.128

0.0.0.0 255.255.255.128 U 40 0 0 eth0172.160.0 172.16.67.13

5255.255.0.0 UG 40 0 0 eth0

172.16.0.0 172.16.67.131

255.240.0.0 UG 40 0 0 eth0127.0.0.0 0.0.0.

0255.0.0.0 U 40 0 0 lo

[root@tmp]#

Exercise-2:- This exercise demonstrate How to Change Your Default Gate w ay

Your server needs to have a single default gateway. DHCP servers will automatically assign a default gateway to DHCP configured NICs, but NICs with configured static IP addresses will need to have a manually configured default gateway. This can be done with a simple command:

[root@tmp]# route add default gw 192.168.1.1 eth0In this case, make sure that the router/firewall with IP address 192.168.1.1 is connected to the same net- work as interface eth0!

Once done, you'll need to update your /etc/sysconfig/network file to reflect the change. This file is used to configure your default gateway each time Linux boots.

NETWORKING=yes HOSTNAME=bigboy GATEWAY=192.168.1.1

Page 56: Manual

55

Exercise-3:- This exercise demonst r ate How to Configure T w o Gateways

Some networks may have multiple router/firewalls providing connectivity. Here's a typical scenario:

You have one router providing access to the Internet that you'd like to have as your default gateway (see the default gateway example earlier)

You also have another router providing access to your corporate network using addresses in the range10.0.0.0 to 10.255.255.255. Let's assume that this router has an IP address of 192.168.1.254

The Linux box used in this example uses interface wlan0 for its Internet

connectivity. There are a number of ways to add this new route.

Exercise-4:- This exercise demonstrate how to add Temporary and Permanent Static Routes

The route add command can be used to add new routes to your server that will last till the next reboot. In our example the reference to the 10.0.0.0 network has to be preceded with a -net switch and the subnet mask and gateway values also have to be preceded by the netmask and gw switches respectively.

[root@tmp]#route add -net 10.0.0.0 netmask 255.0.0.0 gw 192.16.1.254 wlan0If you wanted to add a route to an individual server, then the "-host" switch would be used with no net- mask value. (The route command automatically knows the mask should be 255.255.255.255). Here is an example for a route to host 10.0.0.1.

[root@tmp]# route add -host 10.0.0.1 gw 192.168.1.254 wlan0A universal way of making this change persistent after a reboot would be to place this route add command in the file /etc/rc.d/rc.local, which is always run at the end of the booting process.

In Fedora Linux, permanent static routes are added on a per interface basis in files located in the/etc/sysconfig/network-scripts directory. The filename format is routeinterface-name so the filename for interface wlan0 would be route-wlan0. The format of the file is quite intuitive with the target network coming in the first column followed by the word via and then the gateway's IP address. In our routing ex- ample, to set up a route to network 10.0.0.0 with a subnet mask of 255.0.0.0 (a mask with the first 8 bits set to 1) via the 192.168.1.254 gateway, we would have to configure file /etc/sysconfig/network- scripts/route-wlan0 to look like this:

## File /etc/sysconfig/network-scripts/route-wlan0

Page 57: Manual

56

#10.0.0.0/8 via 192.168.1.254.

Exercise-5:- This exercise demonstrate How to Delete a R oute

Here's how to delete the routes added in the previous section.

[root@tmp]#route del -net 10.0.0.0 netmask 255.0.0.0 gw 192.16.1.254 wlan0

The file /etc/sysconfig/network-scripts/route-wlan0 will also have to be updated so that when you reboot the server will not reinsert the route. Delete the line that reads:

10.0.0.0/8 via 192.16.1.254


Recommended