You are on page 1of 57

Submitted To:-

OPERATI NG SYSTEM
LAB MANUAL

Sir Umair Ashraf


Submitted By:-

Usama Javed Roll # 21 5th Semester CS Dept. NFC-IEFR

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

Lab No. 01: Linux Basic Installation

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

Exercise-1:- This exercise demonstrates step-by-step installation of Linux Operation system. 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: /boot -------/ 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. Packages 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 Size (MB) 200 (size for RAM)*2 all available free space File system Type ext3 swap ext3

10

11

12

13

14

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 dont 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.

15

Lab No. 02: Linux shell and Basic shell commands

16

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

17

Exercise-3:- This exercise illustrates how to Display or change system date and display calendar 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"

18

Lab No. 03: Command Line File Manipulation

19

Exercise -1:- This exercise illustrates how to View contents of a file. To view file contents on shell console, type: cat filename To merge contents of two or more files and display it on screen, type cat file1 file2 file3 ... To display a screenful text of file on the terminal, type: more filename To display file contents screenful at a time with page-up and page-down options, type: less filename To view first k lines of the file, type: head -n k filename e.g, to display first 5 lines of the file myfile on the terminal, type; head -n 5 myfile To 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

20

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 files 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

21

Lab No. 04: Command Line File Processing

22

Lab No. 04: Command Line File processing Exercise-1:- This exercise shows which types of files are used in linux and how to know about file types Linux 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 drwxr-xr-x 3 root crw------1 root lrwxrwxrwx 1 root /proc/kcore srw-rw-rw- 1 root brw-rw---1 root javidali@JLaptop:/dev$ audio 14, root dialout 5, root root disk 8, 4 60 1 11 0 1 2009-04-28 07:01 2009-04-28 12:01 2009-04-28 07:01 2009-04-28 07:01 2009-04-28 07:01 2009-04-28 12:01 audio bus console core -> log sda1

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 d b c l s File type Regular files Directories Block files Description text file, Postscript, graphics files, Hypertext (HTML), video file etc Files that act as containers to other files Files that are used for block (parallel)devices. Data from such devices are read or written to in blocks.

Character files Files that are used for character (serial) devices. Data from such de- vices are read or written to character by character Symbolic links Shortcut to other files or directories 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 Type Application Name Command for the application gv acroread xv gimp xdvi Netscape gtv Exercise-2:- This exercise demonstrates how to view and change access permissions 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 Postscript Portable Document Format (PDF) files Image Image files LaTeX ouput (DVI) Hypertext (HTML) MP3 and MPEG gv (based on GhostView) Adobe Acrobat Reader XV The Gimp xdvi Netscape gtv

23

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: Symbol u g Meaning User

Group o Other a All (equals to ugo) + Add a permission Remove (take away) a permission r Read permission w Write permission x 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.sh The result is: javidali@JLaptop:~$ ls l myscript.sh

24

---x--x--x 1 root root 207 2009-04-10 15:55 myscript.sh Often 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 Read Write execute Octal Number 4 2 1 Equivalent symbol r--w--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 To secure your home drive from everyone but the user, use the command: javidali@JLaptop:~$ chmod 700

15:55 myscript.sh

Exercise-3:- This exercise shows how to view 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.txt The res ult 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. Tjavidali@JLaptop:~$ sudo chown root:root newfile.txt

25

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 describes the ways to compress/uncompress, files and making 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.tar Output of this command is a file named backup.tar.gz To uncompress the file again, issue the command javidali@JLaptop:~$ gzip -d backup.tar.gz Or javidali@JLaptop:~$ gunzip backup.tar.gz Or you can use tar command to uncompress and extract contents of the file. Example is: javidali@JLaptop:~$ tar -xz backup.tar.gz Where -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.tar And to extract the contents of the archive, issue the following command. javidali@JLaptop:~$ tar -xvf backup.tar

26

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

27

Exercise-1:- This exercise illustrates how to start the editor, move cursor around and exit form the editor.
U

To start the editor from command line, type vi An empty file will be opened in the editor. If you want to open an existing file in the editor, type vi filename To 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, :wq Where "w" is for writing changes to the file and "q" is to quit or exit the editor Exercise-2:- This exercise illustrates how to Work in command 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: r to undo the last change to the file. Typing u again will re-do the change. u To delete character after the current cursor position x Exercise-3:- This exercise illustrates how to Copy, Cut and paste the text

28

To cut text from the file, type, d to cut multiple characters, type: NUMd wher NUM is the numper of characters to cut to cut the whole line type: dd to 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. Dw To cut three lines from current cursor position downwards. 3dd You 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: p to paste the buffer before the cursor position type: P To paste the text for the specified number of times, say 3, before the cursor position, type: 3P Exercise-4:- This exercise illustrates 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 and type: :% 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

29

To search a string backwards in the file, say "nfc", type: ? nfc To repeat the previous search in the same direction, type: n To repeat the previous search in the same direction, type: N To 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 single character a

* 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: /fj Or /tj To search for a character backwards within one line, say 'j', type: /Fj Or /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

30

Exercise -6:- This exercise illustrates 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 myfile and save the recovered file then Note: The -r option only works once per failed VI session.

31

Lab No. 06: Managing the File System

32

Lab No. 06: Managing the file system Exercise-1:- This exercise illustrates how Multiple Disks in the File system are represented. 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 can peek 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 3948063 22% /usr 0 /dev/hdc 609750 60975 0 100% / 0 The first line indicates that the disk with symbolic name5 /dev/hda8mnt/cdro at the root is mounted 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 illustrates how to recognize 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: h d a 1 h d a 3 h d a 5

33

h d a 7 h d b 2 f d 0 f d 1 s d a 1 d s a 8 s d b 2 e t c Here is a brief description of file system names. Disk file name Description fd0 disk drive fd1 disk drive hda master) hdb slave) hdc master) sda disk dirve sdb disk drive First SCSI Second SCSI First master hard disk drive (IDE-0 First slave hard disk drive (IDE-0 Second mater hard disk (IDE-1 First floppy Second floppy

34

Exercise-3:- This exercise illustrates Recognizing Partitions. Enter the command ls /dev |grep ?d* To display only disk related files and the output will be something like: h d a 1 h d a 3 h d a 5 h d a 7 h d b 2 f d 0 f d 1 s d a 1 d s a 8 s d b 2

35

Disk file name Description hda1 First master hard disk drive (IDE-0 master), first First master hard disk drive (IDE-0 primary partition hda3 master), third partition hda5 First master hard disk drive (IDE-0 master), 1st First master hard disk drive (IDE-0 logical partition Hda7 (IDE-0 slave), 1st partition sda1 First SCSI disk drive, first Second SCSI disk primary partition. sdb8 drive, 4th logical partition Exercise-4:- This exercise illustrates Mounting/un-mounting partition: 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 Un mounting partition, either type: umount partition Or e.g. Or umount mount_point umount /dev/hda5 umount /mnt To locate a program file in the user's path, type: Any of the to command will unmount the mounted partition /dev/hda5 on /mnt Mount_point

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

36

Lab No. 07: Command Line Process Management

37

Lab No. 07: Command line Process Management Exercise-1:- This exercise illustrates 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:~$ ps PID TTY TIME CMD 23985 pts/0 00:00:01 bash 24001 pts/0 00:00:00 ps javidali@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 COMMAND root 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 portmap root 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/X javid 7892 0.0 1.2 7580 1564 ? S 14:15 0:00 gnome-session javid 7957 0.0 1.3

38

4700 1700 ? S 14:15 1:39 sawmill javid 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 gmc javid 7972 0.0 0.7 3560 968 ? S 14:15 0:11 xscreensaver javid 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 computers 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 illustrates how to terminate a Process Sometimes you will come across a process that locks up and just wont 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 12504 If 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 illustrates 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 (&) character. For example, to run Netscape in the background, type:

39

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 bg this command restarts the currently suspended process in the background.

40

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

41

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

Exercise-1:- Hello world example. The script declares a string variable, stores Hello World in it and finally prints the value of variable on the screen. #!/bin/bash # declare STRING variable STRING="Hello World" #print variable on a screen echo $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 explains the use of Global vs. Local variables #!/bin/bash #Define bash global variable #This variable is global and can be used anywhere in this bash script VAR="global variable" function bash { #Define bash local variable #This variable is local to bash function only local VAR="local variable" echo $VAR } echo $VAR bash # 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 bash script #!/bin/bash # use predefined variables to access passed arguments #echo arguments to the shell echo $1 $2 $3 ' -> echo $1 $2 $3' # We can also store arguments from bash command line in special array args=("$@") #echo arguments to the shell echo ${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

42

# number of arguments passed to the bash script echo Number of arguments passed: $# ' -> echo Number of arguments passed: $#' Passing arguments to the scripts ./arguments.sh Bash Scripting Tutorial Here ./arguments.sh is the filename and the remaining are the arguments passed to the script. Exercise -4:- This exercise illustrates Executing shell commands with bash #!/bin/bash # use backticks " ` ` " to execute shell command echo `uname -o` # executing bash command without backticks echo uname -o Exercise -5:- This exercise illustrates Reading User Input #!/bin/bash echo -e "Hi, please type the word: \c " read word echo "The word you entered is: $word" echo -e "Can you please enter two words? " read word1 word2 echo "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 $REPLY read echo "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 colours echo "My favorite colours are also ${colours[0]}, ${colours[1]} and ${colours[2]}:-)"

43

Lab No. 09: Advance Bash Scripting 1

44

Lab No. 09: Advance Bash Scripting 1T Exercise-1:- Simple Bash if/else statement. In this example we declare a variable named di- rectory and assign it a value. Then we check in the if statement that the directory exists or not and the relevant message is printed on the screen accordingly. Please note the spacing inside the [ and ] brackets! Without the spaces, it won't work! #!/bin/bash directory="./BashScriptin g" # bash check if directory exists if [ -d $directory ]; then echo "Directory exists" else fi echo "Directory does not exists Exercise -2:- This exercise demonstrates Bash for loop #!/bin/bash # bash for loop for f in $( ls /var/ ); do echo $f done Exercise -3:- This exercise demonstrates Bash while loop #!/bin/bash COUNT=6 # bash while loop while [ $COUNT -gt 0 ]; do echo Value of count is: $COUNT let COUNT=COUNT-1 done Exercise -4:- This exercise demonstrates Bash until loop #!/bin/bash COUNT=0 # bash until loop until [ $COUNT -gt 5 ]; do echo Value of count is: $COUNT let COUNT=COUNT+1 done

45

Lab No. 10: Advance Bash Scripting 2

46

Lab No. 10: Advance Bash Scripting 2 Exercise -1:- This exercise demonstrates how to Declare simple bash array #!/bin/bash #Declare array with 4 elements ARRAY=( 'Debian Linux' 'Redhat Linux' Ubuntu Linux ) # get number of elements in the array ELEMENTS=${#ARRAY[@]} # echo each element in array # for loop for (( i=0;i<$ELEMENTS;i++)); do echo ${ARRAY[${i}]} done Exercise -2:- This exercise demonstrates how to Read file into bash array #!/bin/bash #Declare array declare -a ARRAY #Open file for reading to array exec 10<bash.txt let count=0 while read LINE <&10; do ARRAY[$count]=$LIN E ((count++)) done echo Number of elements: ${#ARRAY[@]} # echo array's content echo ${ARRAY[@]} # close file exec 10>&Exercise -3:- This exercise demonstrates Bash Functions !/bin/bash # BASH FUNCTIONS CAN BE DECLARED IN ANY ORDER function 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 C function_C "Function C." function_D

47

Lab No. 11: Introduction to gcc

48

Lab No. 11: Introduction to gcc Exercise-1:- This exercise demonstrates Writing a C Program in linux test editors. 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 :wq to save the program and exit the editor. Exercise-2:- This exercise demonstrates Compiling Programs You can learn more about g++ later by looking at the man pages. (Theres a lot there!) For now, well just look at the basics. To compile the C program of exercise 1, in the shell, simply type gcc -o intro_program introporgram.c in 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 youll 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.c The -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

49

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 explains 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.o g++ sort.o list.o -o sort sort.o: sort.cc sort.h g++ -g -c sort.cc list.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

50

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 variables 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.

51

Exercise-5:- This exercise demonstrates the Execution 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. ./introprogram Where ./ 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/introprogram To at the directory cs to users search path, first type Export PATH=$PATH:/home/cs And then to run the program now just type introprogram

52

Lab No. 12: Linux Networking 1

53

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 -a eth0 Link encap:Ethernet HWaddr 00:08:C7:10:74:A8 inet addr:192.168.1.100 Bcast:192.168.1.255 Mask:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:47379 errors:0 dropped:0 overruns:0 frame:0 TX packets:107900 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:100 RX 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 demonstrates 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 up The "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 demonstrates 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 to Create the virtual interface with the ifconfig command root@tmp]# ifconfig eth0:0 192.168.1.99 netmask 255.255.255.0 up Exercise-5:- This exercise demonstrates How to Activate/Shut Down 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

54

Lab No. 13: Linux Networking 2

55

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 of 0.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 -nr Kernel IP routing table Destination Gateway Genmask Flags MSS Window irtt Iface 255.255.255.255 0.0.0.0 255.255.255.255 U 40 0 0 wlan0 192.168.1.0 0.0.0.0 255.255.255.0 U 40 0 0 wlan0 127.0.0.0 0.0.0.0 255.0.0.0 U 40 0 0 lo 0.0.0.0 192.168.1.1 0.0.0.0 U 40 0 0 wlan0 G [root@tmp]# In this example, there are multiple gateways handling traffic destined for different networks on different interfaces. [root@tmp]# netstat -nr Kernel IP routing table Destination Gateway Genmask Flags MSS Window irtt Iface 172.16.68.64 172.16.69.19 255.255.255.224 40 0 0 eth1 172.16.11.96 172.16.69.19 255.255.255.224 40 0 0 eth1 172.16.68.32 3 172.16.69.19 UG 255.255.255.224 40 0 0 eth1 172.16.67.0 3 172.16.67.13 UG 255.255.255.224 40 0 0 eth0 UG 172.16.69.19 5 0.0.0.0 255.255.255.192 U 40 0 0 eth1 2 172.16.67.12 0.0.0.0 255.255.255.128 U 40 0 0 eth0 8 172.160.0 172.16.67.13 255.255.0.0 UG 40 0 0 eth0 5 172.16.0.0 172.16.67.13 255.240.0.0 UG 40 0 0 eth0 1 127.0.0.0 0.0.0. 255.0.0.0 U 40 0 0 lo [root@tmp]# 0 Exercise-2:- This exercise demonstrate How to Change Your Default Gateway 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 eth0 In 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=bigbo y GATEWAY=192.16 8.1.1

56

Exercise-3:- This exercise demonstrate How to Configure Two 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 range 10.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 wlan0 If 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 wlan0 A 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

57

# 10.0.0.0/8 via 192.168.1.254. Exercise-5:- This exercise demonstrate How to Delete a Route 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