55
CS2406-OPEN SOURCE LAB http://csetube.weebly.com/

Fosslab Manual

Embed Size (px)

Citation preview

Page 1: Fosslab Manual

http://csetube.tk/

CS2406-OPEN SOURCE LAB

http://csetube.weebly.com/

Page 2: Fosslab Manual

http://csetube.tk/

CS2406

OBJECTIVE:

OPEN SOURCE LAB L T P C

0 0 3 2

To expose students to FOSS environment and introduce them to use open source

packages

1. Kernel configuration, compilation and installation : Download / access the

latest kernel source code from kernel.org,compile the kernel and install it in the

local system.Try to view the source code of the kernel

2. Virtualisation environment (e.g., xen, kqemu or lguest) to test an applications,

new kernels and isolate applications. It could also be used to expose students to

other alternate OSs like *BSD

3. Compiling from source : learn about the various build systems used like the

auto* family, cmake, ant etc. instead of just running the commands. This could

involve the full process like fetching from a cvs and also include autoconf,

automake etc.,

4. Introduction to packet management system : Given a set of RPM or DEB, how

to build and maintain, serve packages over http or ftp. and also how do you

configure client systems to access the package repository.

5. Installing various software packages

Either the package is yet to be installed or an older version is existing. The

student can practice installing the latest version. Of course, this might

need internet access.

Install samba and share files to windows

Install Common Unix Printing System(CUPS)

7. Write userspace drivers using fuse -- easier to debug and less dangerous to the

system (Writing full-fledged drivers is difficult at student level)

8. GUI programming : a sample programme – using Gambas since the students

have VB knowledge. However, one should try using GTK or QT

9. Version Control System setup and usage using RCS, CVS, SVN

10. Text processing with Perl: simple programs, connecting with database e.g.,

MYSQL

11. Running PHP : simple applications like login forms after setting up a LAMP

stack

12. Running Python : some simple exercise – e.g. Connecting with MySql database

13. Set up the complete network interface usinf ifconfig command like setting

gateway, DNS, IP tables, etc.,

http://csetube.weebly.com/

Page 3: Fosslab Manual

http://csetube.tk/

LIST OF EXPERIMENTS

Ex No. 1 Kernel Configuration, Compilation and Installation

Ex No. 2 Virtualisation Environment

Ex No. 3 Compiling from Source

Ex No. 4 Packet Management System

Ex No. 5 Installing Various Software Packages

Ex No. 6 FUSE - File System in User Space Ex

No. 7 GUI Programming Using GAMBAS2

Ex No. 8 Version Control System Setup and Usage using

RCS, CVS, SVN

Ex No. 9 PERL programming

Ex No. 10 PHP with MYSQL

Ex No. 11 Python programming with MYSQL

Ex No. 12 Setting Up The Complete Network Interface

http://csetube.weebly.com/

Page 4: Fosslab Manual

http://csetube.tk/

Ex No. 1 Kernel Configuration, Compilation and Installation

Aim:

To do Download / access the latest kernel source code from kernel.org, compile the

kernel and install it in the local system. Also try to view the source code of the

kernel.

Algorithm :

1. Check for the current version of the working kernel

$uname -r

2. Download the kernel source code from

wget http://fosslabserver.linuxpert.in/kernel/v2.6/linux-2.6.35.7.tar.gz

3. Extract the kernel source code (through GUI) or terminal

tar zxvf linux-2.6.35.7.tar.gz

4. Inside the kernel source directory, open the Makefile

vi Makefile

5. Look for the line EXTRAVERSION and append a name

ex. 2.6.35.7-mykernel

6. make menuconfig

7. make bzImage

8. su

9. cp arch/x86/boot/bzImage /boot/vmlinuz-2.6.35.7

(choose the desired kernel options)

(builds the kernel)

http://csetube.weebly.com/

Page 5: Fosslab Manual

http://csetube.tk/

10. chmod 755 /boot/vmlinuz-2.6.35.7

11. make modules (builds the kernel modules)

12. make modules_install (installs the kernel modules in the /lib/modules

directory)

13. mkinitrd /boot/initramfs-2.6.35.7.img 2.6.35.7-<extra-ver>

Note: check for the newly created directory in the

/lib/modules directory and give the name above

http://csetube.weebly.com/

Page 6: Fosslab Manual

http://csetube.tk/

Ex No. 2 Virtualisation Environment

Aim:

To develop Virtualisation environment (e.g., xen, kqemu or lguest) to test an

applications, new kernels and isolate applications.

Algorithm:

Steps for Virtualization using QEMU and FreeDOS

1. Download the fdbasecd.iso from www.freedos.org (or) from fosslab server

The following steps should be followed from the directory where fdbasecd.iso is

stored

2. qemu-img create virtualdisk.img 100M

3. qemu -hda virtualdisk.img -cdrom fdbasecd.iso -boot d

4. After booting through QEMU, select 1 to boot from CDROM

5. Select Language - English US

6. Select option to boot FreeDOS from CDROM

7. from X:>fdisk

8. Enable Large disk support (Y)

9. Create DOS partition -> Primary DOS partition

10. Make the whole DOS Primary partition as Active (Y)

http://csetube.weebly.com/

Page 7: Fosslab Manual

http://csetube.tk/

Ex No. 3 Compiling from Source

Aim:

To learn about the various build systems used like the auto* family, cmake, ant etc.

instead of just running the commands. This could involve the full process like

fetching from a cvs and also include autoconf, automake etc.,

Algorithm:

1. Open terminal

2. Check for webattery availability

#rpm –q webattery

#which webattery

#rpm –e webattery

#exit

3. Move to Home/Downloads directory and download webattery package

$cd Downloads

$rpm –ivh weabattery-1.2.6.f14.src.rpm

4. Move to rpmbuild folder in Home directory and rpmbuild SOURCES

folder

$cd ..

$cd rpmbuild

$cd SOURCES

5. Extract webattery package

$tar zxvf webattery-1.2.tar.gz

6. Move to webattery-1.2 directory src

$cd webattery-1.2

$cd src

$cd ..

7. Perform configuration

$./configure

8. Do make

$make

9. Login as superuser

$su –

http://csetube.weebly.com/

Page 8: Fosslab Manual

http://csetube.tk/

10.Install webattery package

#make install

11.Check for webattery package

#which webattery

http://csetube.weebly.com/

Page 9: Fosslab Manual

http://csetube.tk/

Ex No. 4 Packet Management System

Aim:

To build and maintain RPM or DEB packages, serve packages over http or ftp and

also to configure client systems to access the package repository.

Algorithm:

1. Go to browser and type

http://fosslabserver/pub/tools/internet/qmail

2. Download the qmail-packages.zip to Downloads folder

3. Go to Downloads folder and extract qmail-packages.zip

4. In the terminal move to Downloads folder which is under home/fosslab

5. List all the files in the Downloads folder

using $ls –l

6. Move the contents of qmail-packages directory to directory qmail

$mv qmail-packages qmail

$ls –l

7. Move to qmail directory

$cd qmail

$ls

8. To see no of rpm packages give the command as

follows $ls *.rpm | wc

9. Move again to Downloads folder

10. Now create a repository for qmail

$createrepo qmail/

11. Next go to qmail directory and check if repodata folder is

created $cd qmail

$ls –l

12. Move to repodata folder

$cd repodata

$ls –l

13. Move back to fosslab directory

14. Check for the Apache Web Server Status

$service httpd status

$service httpd start (if Apache Web Server Status is stopped)

$service httpd status

http://csetube.weebly.com/

Page 10: Fosslab Manual

http://csetube.tk/

15. Go to browser and type

http://localhost

if the Fedora test page is displayed then Apache Web Server is running

16. Move the qmail packages from home/fosslab/Downloads directory to

/var/www/html/ which can be served by Apache Web Server requesting

clients

$mv /home/fosslab/Downloads/qmail /var/www/html

17.Go to /var/www/html and see if the qmail packages are available

$cd /var/www/html

$ls –l

18. Next go to browser and

type http://localhost/qmail

19. Now we have to create the repository configuration file so that the clients

can use the configuration file for installing qmail packages from the server

$su

#cd /etc/yum.repos.d/

#ls –l

#vi qmail.repo

Type the following lines into the

file [qmail]

name=Q-Mail packages

baseurl=http://localhost/qmail

enabled=1

gpgcheck=0

save the file :wq

20. View the qmail.repo file

#cat qmail.repo

21. Now we have to rebuild the YUM Cache, so that YUM package manager

includes the qmail package information

#yum clean all

#yum makecache

22.Now check if qmail packages are included

#yum search qmail

23.Now install qmail toaster

#yum install qmailtoaster-plus

#yum install libsrs2-toaster

http://csetube.weebly.com/

Page 11: Fosslab Manual

http://csetube.tk/

YUM

fedora.repo, fedora-updates.repo

1. Loginassuperuser

/etc/yum.repos.d/ $su

#cd /etc/yum.repos.d

#ls –l

and move to

2. Editfedora.repo

file #vi fedora.repo

Make the following changes

Add # before „mirrorlist‟ in line

5 Add the following line at line 7

baseurl=http://fosslabserver/f14repo/

save the file

3. Edit fedora-updates.repo

#vi fedora-updates.repo

Change enabled=0 and save the file

4. Now we have to rebuild YUM

cache #yum clean all

#yum makecache

5. List repo groups

#yum grouplist

6. Now install “XFCE” #yum

groupinstall “XFCE”

7. Now install kernel

#yum install kernel rpmfusion-

free.repo, rpmfusion-nonfree

1. In the browser type

http://fosslabserver/f14repo/rpmfusion/i386/free

find the file rpmfusion-free-release-14.0.4.noarch.rpm and copy the path

2. In the terminal

superuser $su

login as

3. Now you have to install the rpmfusion-free-release-14.0.4.noarch.rpm by

pasting the path after rpm

#rpm–ivhhttp://fosslab/f14repo/rpmfusion/i386/free/rpmfusion-free-

release-14.0.4.noarch.rpm

http://csetube.weebly.com/

Page 12: Fosslab Manual

http://csetube.tk/

4. Next you have to install the rpmfusion-nonfree-release-14.0.4.noarch.rpm by

pasting the path after rpm

#rpm –ivh http://fosslab/f14repo/rpmfusion/i386/free/rpmfusion-nonfree-

release-14.0.4.noarch.rpm

5. Move to /etc/yum.repos.d/

$cd /etc/yum.repos.d/

6. Edit rpmfusion-free.repo

#vi rpmfusion-free.repo

Add # before „mirrorlist‟ in line 4

Add the following line at line 6

baseurl=http://fosslabserver/f14repo/rpmfusion/i386/free

save the file

7. Edit rpmfusion-free-updates.repo

Change enabled=0 and save the file

8. Edit rpmfusion-nonfree.repo

Add # before „mirrorlist‟ in line 4

Add the following line at line 6

baseurl=http://fosslabserver/f14repo/rpmfusion/i386/nonfree/

save the file

9. Edit rpmfusion-nonfree-updates.repo

Change enabled=0 and save the file

10.Now we have to rebuild YUM cache

#yum clean all

#yum makecache

11. Now check if packages are included

#yum search vlc

12.Next install vlc

#yum install vlc*

http://csetube.weebly.com/

Page 13: Fosslab Manual

http://csetube.tk/

Ex No. 5 Installing Various Software Packages

Aim:

To install samba and share files to windows and also install Common Unix

Printing System (CUPS)

Algorithm:

CUPS

1. Check for existence of CUPS

$rpm –qa | grep cups

$rpm –qi cups 2. Check if CUPS is running

#service cups status

3. Open firefox and type the following

#open firefox

http://localhost:631/

under CUPS for administrators select Adding Printers and Classes

4. Under Printers select Add Printer and give username and

password Username : root

Passwd: admin123

5. Under Add Printer select HP Printer (HPLIP) and click on continue 6. Then give the connection as

http://localhost:631/ipp/ and click on continue

7. Give a name for the printer(HP1010), description(HP1010 LaserJet Printer)

and location (Lab 1) and click on continue.

8. Select the make as HP and click on continue.

9. Select the model (HP LaserJet 1010 Foomatic/hpijs (en) and click on Add

Printer

10.After printer is added change the page size as A4 and click on set default

properties

11.In the next page click on HP1010

12.Select print test page from

Maintenance 13.Click on show all jobs

SAMBA

I Stage 1 (Linux)

1. Check if SAMBA is installed and working

$rpm –qa | grep cups

$su

#service smb status

http://csetube.weebly.com/

Page 14: Fosslab Manual

http://csetube.tk/

#service smb start (if samba was in stopped state)

#service smb status

2. Check if network message block is

running #service nmb status

#service nmb start (if samba was in stopped

state) #service nmb status

3. View the ip table

#iptables –L

4. Stop the iptables service

#service iptables stop

5. View the ipv6

table #ip6tables –L

6. Stop the iptables service

#service ip6tables stop

7. Check enforce status

#getenforce

#setenforce (to enable enforce)

#setenforce 0

8. Add winuser and set samba password for the winuser

#useradd winuser

#smbpasswd –a winuser

#service smb status

# service nmb status

II Stage 2 (Windows)

1. Go to run and type the ip of your linux

box \\192.168.1.43 (for example)

2. Give the password which you assigned to winuser in linux

3. Create some folders in the linux login

III Stage 3 (Linux)

1. Login as winuser

2. Go to places home folder and check if the folders created in windows is

available

http://csetube.weebly.com/

Page 15: Fosslab Manual

http://csetube.tk/

IV Stage 4 (Linux)

1. Login open source lab\

2. Go to places home folder

3. Press CTRL+L and type

smb://192.168.1.252 (ip address of the windows machine)

4. Login as administrator

5. Create some folders and try viewing in linux box

http://csetube.weebly.com/

Page 16: Fosslab Manual

http://csetube.tk/

Ex No. 6 FUSE - File System in User Space

Aim:

To write userspace drivers using fuse -- easier to debug and less dangerous to the

system

Algorithm:

1. Check whether FUSE is installed

$rpm –qa | grep fuse

$rpm –qi fuse

2. Open browser and type the following

http://fosslabserver.linuxpertsystem.in/osslab/samples/fuse.gz

download fuse.gz

3. Go to Places Downloads and extract fuse.gz

(or)

Do the following

$wget http://fosslabserver.linuxpertsystem.in/osslab/samples/fuze.gz

$tar zxvf fuse.gz

4. Go to terminal then move to home/fosslab/Downloads

5. Extract fusetutorial.gz and move to that directory

6. Next move to src directory

7. Look for bbfs.c file and view it

8. Then look for log.c and view it

9. Now try to fuse cflags

$pkg-config fuse --cflags

10.Then fuse libs $pkg-

config fuse --libs

11. Perform makefile

$make

12. Look for bbfs file (coloured green)

13. Move to examples folder

$cd ../examples

14. View the mountdir and rootdir directories

$ls –al mountdir

http://csetube.weebly.com/

Page 17: Fosslab Manual

http://csetube.tk/

$ls –al rootdir

15. Move to rootdir folder and create some empty files

$cd rootdir/

$touch

myfile $ls –l

16. Move back to examples folder and check the no of files in mountdir

$cd ..

$ls –l mountdir 17.Check

the files in rootdir/

$ls –l rootdir/ 18.Now

call the fuse bbfs

$ ..src/bbfs rootdir/ mountdir/

19.Now check the no of files under mountdir/

$ls –l mountdir/

20. Now mount the filesystem to see the fuse

working $mount

21. Next unmount the fuse and check for the no of files in

mountdir/ $fusermount –u mountdir/

$ls –l

$mount

$tail –f bbfs.log

http://csetube.weebly.com/

Page 18: Fosslab Manual

http://csetube.tk/

Ex No. 7 GUI Programming Using GAMBAS2

Aim:

To create a login form for booking train ticket using GAMBAS2

Algorithm:

1. Go to Applications Programming

2. Under Programming Gambas2

3. In the Gambas2 environment select New Project

4. Next select the location of the project to be created

5. In the next step give a name for your project

6. Now after your project is created you have to create forms for your project

7. The different tools are available under the toolbox

8. Add the appropriate tools to your form

9. Next add the appropriate code for the different controls placed on the

form 10.Save the project

11.Run the project

http://csetube.weebly.com/

Page 19: Fosslab Manual

http://csetube.tk/

Ex No. 8 Version Control System Setup and Usage using RCS, CVS, SVN

Aim:

To do Version Control System setup and usage using RCS, CVS, SVN

Algorithm:

1. Check for SVN status $rpm

–qa | grep subversion

2. Check for java / jre installed

status $rpm –qa | grep java

3. Go to browser and type

http://fosslabserver/tools/development/svnedge

4. DownloadCollabNetSubversionEdge-1.3.2_linux-x86_64.tar.gz

downloads folder

to

5. Go to Places Downloads and extract CollabNetSubversionEdge-

1.3.2_linux-x86_64.tar.gz

6. Login as superuser and edit sudo

$su –

#visudo

7. In the visudo file add the following line after line no 77 (to insert line no

type :se nu)

fosslab ALL=(ALL) ALL

8. Check for java

version $java –version

$which java

9. Set the environmental variables

$export JAVA_HOME=/usr

$JAVA_HOME/bin/java –version

10. Move to fosslab/Downloads directory

$cd fosslab $cd

Downloads

11.Move to csvn directory

$cd csvn

12.Install CSV

$sudo –E bin/csvn install

13. Start bin/csvn service

$bin/csvn start

14.Check for bin/csvn console status

http://csetube.weebly.com/

Page 20: Fosslab Manual

http://csetube.tk/

$bin/csvn console

15.Type the following address in browser and check

http://localhost:3343/csvn

16. Give the user and password

17. Click on Administration link and change port to 8888 and Administrator as

admin and also give admin email id

18. Click on Save

19. Click on status link and start the subversion edge

20. Install the webattery package as given in exercise 3

21. Go to http://localhost:3343/csvn and give username and password

22. Under repositories link click on new repository

23. Give the name of repository as webattery and click on create

24. Click on repository list link to view the repository added

25. Copy the text next to webattery

26. Go to terminal and make directory subversion-test

$mkdir subversion-test

27. Move the subversion-test folder

28. Paste the text which you copied which was next to webattery

29. Give username and password

http://csetube.weebly.com/

Page 21: Fosslab Manual

http://csetube.tk/

Ex No. 9 PERL programming

Aim:

To demonstrate the PERL program connectivity with MySQL database

Algorithm:

1. Sample PERL

#!usr/bin/perl # the above line is shebang

directive $name=<STDIN>;

chomp($name);

print "$name\n";

output:

[linuxpert@localhost ~]$ perl

first.pl Hello World

Hello World

2. Scalar variables in

PERL #!/usr/bin/perl

my $animal="Camel"; # this variable is lexically scoped ie

local my $ans=42_243; #this is similar to 42243

print "$animal\n";

print "$ans\n";

print "The square of &ans",$ans*$ans,"\n";

output:

[linuxpert@localhost

scalar.pl Camel

42243

3. Array in PERL

#!usr/bin/perl

my @animal=("cow","Buffalo","Camel");

print "@animal\n"; # list all elements in array

print "$#animal\n"; # list last element position

print "$animal[0]\n"; #list 0th position

element $count=@animal;

print "$count"; # count no of elements in

array output:

[linuxpert@localhost ~]$ perl array.pl

~]$ perl

http://csetube.weebly.com/

Page 22: Fosslab Manual

http://csetube.tk/

cow Buffalo Camel

2

cow

3

4. Hash in PERL

#!usr/bin/perl

%color=('apple'=>"red",'banana'=>"yellow",'orange'=>"orange");

print "$color{'apple'}\n";

output:

[linuxpert@localhost

hash.pl red

~]$ perl

5. To display all values in hash

#!usr/bin/perl

%color=('apple'=>"red",'banana'=>"yellow",'orange'=>"orange");

print "$color{'apple'}\n";

# to display all the values in

hash @keys=keys %color;

foreach $key (@keys)

{

print "$color{$key}\n";

}

output:

[linuxpert@localhost ~]$ perl hashvalues.pl

red

yellow

red

orange

6.for delection of Hash

values #!usr/bin/perl

%color=('apple'=>"red",'banana'=>"yellow",'orange'=>"orange");

print "$color{'apple'}\n";

# to display all the values in hash

@keys=keys %color;

@values=values %color; # it ill store the array values

foreach $key (@keys)

{

http://csetube.weebly.com/

Page 23: Fosslab Manual

http://csetube.tk/

print "$color{$key}\n";

}

delete $color{'apple'}; # to remove specific

key 7.If loop in perl

#!usr/bin/perl

my $a=10;

$condition=1;

if($condition)

{

my $y=100;

print "$a\n";

print "$y\n";

}

print "$a\n";

print "$y\n";

output:

[linuxpert@localhost ~]$ perl ifloop.pl

10 100 10

8. If not loop (unless)in

perl #!usr/bin/perl

$a=5;

unless($a>10) #is equal to if not

{

print "a less than 10";

}

output:

[linuxpert@localhost ~]$ perl unless.pl

a less than 10

9. While loop (until) in perl

#!usr/bin/perl

$a=0;

until($a>10) #is equal to while

{

print "$a\n";

http://csetube.weebly.com/

Page 24: Fosslab Manual

http://csetube.tk/

$a++;

}

out put:

[linuxpert@localhost ~]$ perl unless.pl

a less than 10[linuxpert@localhost ~]$ perl

until.pl 0 1 2 3 4 5 6 7 8 9 10

10. for each loop (upper limit is not fixed )in

perl #!usr/bin/perl

my @animals=("cow","buffalo","camel",123,100,243,300);

foreach $key(@animals)

{

print "$key\n";

}

output:

[linuxpert@localhost

foreach.pl cow

buffalo

camel

~]$ perl

123

100

243

300

11. String operation:

#!usr/bin/perl

$a="hello";

$b="world";

http://csetube.weebly.com/

Page 25: Fosslab Manual

http://csetube.tk/

print $a.$b,"\n";

$str="-";

print $str x 80,"/n";

@a=(10..25);

print "@a\n";

output

[linuxpert@localhost ~]$ perl

string.pl helloworld

----------------------------------------------------------------------

----------/n10

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 12. Hard reference variable:

12.1 Reference

variable(scalar) #!usr/bin/perl

$a=100;

$b=\$a;

print "$b\n";

output:

[linuxpert@localhost ~]$ perl reference.pl

SCALAR(0x9506a68)

12.2 De reference the variable(scalar variable)

#!usr/bin/perl

$a=100;

$b=\$a;

print "$$b\n";

output:

[linuxpert@localhost ~]$ perl reference1.pl

100

12.3 Array reference variable

#!usr/bin/perl

@arr=('hello','122','200','Hello');

$c=\@arr;

print "$c\n"; # print the address

print "@$c\n"; # print the values of array

print "$c->[1]\n"; #point the specified location in array, to access the

single element

output:

http://csetube.weebly.com/

Page 26: Fosslab Manual

http://csetube.tk/

[linuxpert@localhost ~]$ perl arrayvariable.pl

ARRAY(0x8358a70)

hello 122 200 hello

122

12.4 Hash variable

perl #!usr/bin/perl

in

%color=('apple'=>"red",'banana'=>"yellow",'orange'=>"orange");

$h=\%color;

print "$h\n";#print the

address @keys=keys %$h;

reference

print "@keys\n"; #it contains the key value

print "$h->{'apple'}\n"; # it print the the apple

alone output:

[linuxpert@localhost ~]$ perl

hashvariable.pl HASH(0x830da70)

banana

orange red

12.5 Magic variable in perl

#!usr/bin/perl

%color=('apple'=>"red",'banana'=>"yellow",'orange'=>"orange");

$h=\%color;

apple

print "$h\n";#print the reference

address @keys=keys %$h;

print "$h->{'apple'}\n"; # it print the the apple

alone foreach (@keys)

{

print "$h->($_}\n"; # to display all key values we use $_ instead of keys

}

output:

[linuxpert@localhost ~]$ perl

hashvariable1.pl HASH(0x8df4a70)

red HASH(0x8df4a70)-

>(banana}

HASH(0x8df4a70)->(apple}

HASH(0x8df4a70)->(orange}

13 .Function

http://csetube.weebly.com/

Page 27: Fosslab Manual

http://csetube.tk/

#!usr/bin/perl

sub sayHello()

{

print "Hello\n";

}

&sayHello();

output:

[linuxpert@localhost ~]$ perl function.pl

Hello

13.1 functionwith

parameter #!usr/bin/perl

sub add()

{

my ($a,$b)=@_; #the values will be stored in @_ array variable

for dynamically

print $a+$b;

}

&add(10,15);

output:

[linuxpert@localhost

functionparam.pl 25

~]$ perl

13.2 Find Maximum value using function

#!usr/bin/perl

sub max()

{

$max=shift @_; # shift function remove the first element in array and

the remaining element will be stored in $max

foreach $v (@_) # $v is the second values in the @_

{

$max=$v if $max<$v;

}

return $max;

}

$d=&max(10,278,1050,76,800,246,76,345);

print "The maximum value is $d\n";

output:

http://csetube.weebly.com/

Page 28: Fosslab Manual

http://csetube.tk/

[linuxpert@localhost ~]$ perl

functionparam.pl The maximum value is 1050

14. Symbolic reference

That is no values and name for function (anonymous function)

Anonymous function is used only when need to use the code only

once #!usr/bin/perl

$b=sub #anonymous

{

my ($c,$d)=@_;

$e=$c*$d; return

$e;

};

$a=&$b(20,30);#De reference the

function print "the product is $a\n";

output:

[linuxpert@localhost ~]$ perl

symbolicref.pl the product is 600

14.program to check greater among 3

number #Greatest among 3 number

print "Enter A value : ";

$a=<>;

print "Enter b value : ";

$b=<>;

print "Enter c value : ";

$c=<>;

if(($a > $b)&&($a > $c))

{

print "A is greater";

}

elsif(($b > $c)&&($b > $a))

{

print "B is greater";

}

else

{

print "C is greater";

http://csetube.weebly.com/

Page 29: Fosslab Manual

http://csetube.tk/

}

15.Program to get details in run time

#! usr/bin/perl

print "Enter the Student Information";

print "\n enter name";

chomp($name = <>);

print "\nenter dob";

chomp($dob=<>);

print "\n enter registerno.";

chomp($registern0.=<>);

print "\n enter education";

chomp($Education=<>);

print "\n Student Information";

print "\n Name: $name";

print "\n Date Of Birth :$dob"; print

"\n Register no.:$registern0."; print

"\nQualification :$Education";

16. Program to perform array releted

function #!/usr/bin/perl

# Define an array

@coins = ("aaa","bbb","ccc");

#Array can be represent using qw

format #Display all Elements in Array

print "Array Elements";

print "\n First Statement :

@coins"; print "\n";

# Add elements at the end of the array

print "\nPush Function";

push(@coins,qw/ddd eee fff ggg/);

push(@coins, "Penny","priya");

print "\n Second Statement : @coins";

print "\n";

# Add one element at the beginning of the array

print "\n Unshift Function";

unshift(@coins, "Dollar");

print "\n Third Statement : @coins";

http://csetube.weebly.com/

Page 30: Fosslab Manual

http://csetube.tk/

print "\n";

# Remove one element from the last of the

array. print "\n Pop Function";

pop(@coins);

print"\nFourthStatement

@coins"; print "\n";

:

# Remove one element from the beginning of the

array. print "\n Shift Function";

shift(@coins);

print"\nFifthStatement

@coins"; print "\n";

print "@coins";

#splice function,you can delete or replace elements within the

array. #delete one element at index 1

print "\n Using Splice Function";

@browser=("System",

"Solutions"); print "\n @browser";

print "\n";

#replacing elements at index 1,2

@browser = ("System", "Logic",

"Logic",

:

"Solutions"); splice(@browser, 1, 2, "Helios",

"Matheson"); print "\n @browser";

17. Program to perform Sub-routine to check biggest number

Example 1:

sub maximum

{

if ($_[0] > $_[1])

{

print $_[0];

}

else

{

print $_[1];

}

}

$biggest = &maximum(37, 24);

http://csetube.weebly.com/

Page 31: Fosslab Manual

http://csetube.tk/

Example 2:

sub maximum

{

if ($_[0] > $_[1])

{

$_[0];

}

else

{

$_[1];

}

}

$biggest = &maximum(37, 24);

$biggest2 =&maximum(100,123);

print "\nThe biggest amomg 37 and 24 is $biggest";

print "\nthe biggest among 100 and 123 is

$biggest2"; 3.Program to return the values

sub get_list

{

return 5..10;

}

@list = &get_list;

print "@list";

18. Program to Open the File

# < indicate that file has to be opened in read-only mode

# > sign indicates that file has to be opened in writing

mode Entities Definition

< or r Read Only Access

> or w Creates, Writes, and Truncates

>> or a Writes, Appends, and Creates

+< or r+ Reads and Writes

+> or w+ Reads, Writes, Creates, and

Truncates +>> or a+ Reads, Writes, Appends,

and Creates Sample:

#!/usr/bin/perl

open(DATA, "<sample.txt");

http://csetube.weebly.com/

Page 32: Fosslab Manual

http://csetube.tk/

while(<DATA>)

{

print "$_";

}

19. Example which opens an existing file file1.txt and read

it line by line and generate another copy file2.txt

#!/usr/bin/perl

# Open file to read

open(DATA1, "<file1.txt");

# Open new file to write

open(DATA2, ">file2.txt");

# Copy data from one file to another.

while(<DATA1>)

{

print DATA2 $_;

}

close( DATA1 );

close( DATA2 );

#delete a file file3.txt using unlink function

unlink ("/strawberry/perl/file3.txt");

20.Program to returns the key intersection of two

hashes sub intersection

{

my ($hasha, $hashb) = @_;

my %newhash;

foreach my $key (keys %{$hasha})

{

$newhash{$key} = $$hasha{$key} if (exists $$hashb{$key});

}

return %newhash;

}

%hasha = ( 'a' =>

'b', 'b' => 'b',

'c' => 'b');

print %hasha;

print "\n";

http://csetube.weebly.com/

Page 33: Fosslab Manual

http://csetube.tk/

%hashb = ( 'b' => 'b',

'c' => 'b',

'd' => 'b');

print %hashb;

print "\n";

%newhash = intersection(\%hasha, \%hashb);

print "\n";

print %newhash;

21. Print out lines of other files with the use of

arrays #!/usr/bin/perl

print "content-type: text/html \n\n"; #The header

$text = "sample.txt";

open (text) or die "Can't open the file!";

@fileinput = <text>;

print $fileinput[0];

print $fileinput[1];

print $fileinput[2];

print $fileinput[3];

print $fileinput[4];

print $fileinput[5];

print $fileinput[6];

print $fileinput[7];

print $fileinput[8];

print $fileinput[9];

close (text);

22. PERL - Copying File

We can duplicate a file using the copy function. Copy takes two values the

URL of the file to be copied and the URL of the new file. Since we want to

duplicate the file in this example

22.1 Example for copying and moving and delete function

#!/usr/bin/perl

use File::Copy;

print "\n Copying the content present from file1 to

file2"; $filetobecopied = "file1.txt";

$newfile = "file2.txt";

copy($filetobecopied, $newfile) or die "File cannot be copied.";

http://csetube.weebly.com/

Page 34: Fosslab Manual

http://csetube.tk/

print "\n Now open the new

file"; print "\n Move function";

$oldlocation = "sample.txt";

$newlocation = "f:/keerthi/sample.txt";

move($oldlocation, $newlocation);

# unlink function to delete specific files from your web

server. print "\n Delete function";

$file = "F:/keerthi/sample.txt";

if (unlink($file) == 0)

{

print "\nFile deleted successfully.";

}

else

{

print "\nFile was not deleted.";

}

APPLICATION USING PERL

1.create the table in perl that will be automatically updated

in database using mysql

1.1 First create the database as follows in

mysql [linuxpert@localhost ~]$ mysql -u root -

p Enter password:

Welcome to the MySQL monitor. Commands end with ; or

\g. Your MySQL connection id is 2

Server version: 5.1.45 Source distribution

Type 'help;' or '\h' for help. Type '\c' to clear the current input

statement. mysql> show databases;

+--------------------+

| Database |

+--------------------+

| information_schema |

| mysql |

| test |

+--------------------+

3 rows in set (0.25 sec)

http://csetube.weebly.com/

Page 35: Fosslab Manual

http://csetube.tk/

mysql> create database student;

Query OK, 1 row affected (0.02

sec) mysql> show databases;

+--------------------+

| Database |

+--------------------+

| information_schema |

| mysql |

| student |

| test |

+--------------------+

4 rows in set (0.00 sec)

mysql> use student;

Database changed

mysql> connect;

Connection id: 3

Current database: student

mysql> show tables;

Empty set (0.00 sec)

now the table is empty . To create the table we use the following procedure

1.2 The following packages should be used to connect PERL with

Mysql (use new terminal)

[linuxpert@localhost ~]$ rpm -q perl-DBI

perl-DBI-1.609-4.fc13.i686

[linuxpert@localhost ~]$ rpm -q perl-DBD-MySQL

perl-DBD-MySQL-4.013-3.fc13.i686

1.3 Write the PERL script to connect with mysql as

follows #!usr/bin/perl

use DBI; #to use the build in package we use "Use", DBI is the build

in package in perl

my $dbh=DBI->connect("dbi:mysql:student","root",""); #connect

to database

if(!$dbh)

{

die("error:$!");

}

http://csetube.weebly.com/

Page 36: Fosslab Manual

http://csetube.tk/

$sth=$dbh->prepare("create table students(rollno int,sname varchar(50))");

# create the table

$sth->execute();

$dbh->disconnect;

1.4 Run the Perl script

[linuxpert@localhost ~]$ perl connect.pl

now see the tables in database

(“student”) mysql> show tables;

+-------------------+

| Tables_in_student

| +-------------------+

| students | +-------

------------+

1 row in set (0.00 sec)

2. insert the values in perl that will be automatically updated

in database using mysql as follows

#!usr/bin/perl

use DBI; #to use the build in package we use "Use", DBI is the build

in package in perl

my $dbh=DBI->connect("dbi:mysql:student","root",""); #connect

to database

if(!$dbh)

{

die("error:$!");

}

$sth=$dbh->prepare("insert into students values(100,'thamarai')"); # create

the table

$sth->execute();

$dbh->disconnect;

2.1 compile the perl

[linuxpert@localhost ~]$ perl dbinsert.pl

now the output is

mysql> select * from students;

+--------+----------+

http://csetube.weebly.com/

Page 37: Fosslab Manual

http://csetube.tk/

| rollno | sname | +-

-------+----------+ |

100 | thamarai | +--

------+----------+

1 row in set (0.00 sec)

2.2 insert the values in perl using execute statement

#!usr/bin/perl

use DBI; #to use the build in package we use "Use", DBI is the build

in package in perl

$rollno=200;

$sname="selvi";

my $dbh=DBI->connect("dbi:mysql:student","root",""); #connect

to database

if(!$dbh)

{

die("error:$!");

}

$sth=$dbh->prepare("insert into students values(?,?)"); # create the

table $sth->execute($rollno,$sname);

$dbh->disconnect;

compile the program as

[linuxpert@localhost ~]$ perl dbinsert1.pl

now the output is

mysql> select * from students;

+--------+----------+

| rollno | sname | +-

-------+----------+ |

100 | thamarai |

| 200 | selvi | +-----

---+----------+

2 rows in set (0.08 sec)

http://csetube.weebly.com/

Page 38: Fosslab Manual

http://csetube.tk/

CGI PROGRAMMING

EXAMPLE -1

type the following in terminal

[linuxpert@localhost ~]$ su

Password:

[root@localhost linuxpert]# cd /var/www/cgi-

bin [root@localhost cgi-bin]# gedit

type the following in gedit

#!/usr/bin/perl

use CGI;

$cgi=new CGI;

print $cgi->header,

$cgi->start_html,

$cgi->h1("A simple

Example"), $cgi->end_html;

type the following in the same terminal

[root@localhost cgi-bin]# chmod +x form.cgi

go to browser and type the following URL

http://localhost/cgi-bin/form.cgi

U will get the output

as EXAMPLE -2

in terminal

[linuxpert@localhost ~]$

su Password:

[root@localhost linuxpert]# cd

/var/www/html [root@localhost html]# gedit

type the following in gedit editor

<html>

<head>

<title>LOGIN</title></head>

<body>

<form action="/cgi-bin/form2.cgi"

method="post"> <p>

"Enter student roll no"<input type="text" name="rollno"></p>

<p>"enter the student name"<input type="text" name="sname"></p>

<p>"click here to submit"<input type="submit" name="submit"></p>

http://csetube.weebly.com/

Page 39: Fosslab Manual

http://csetube.tk/

</form>

</body>

save the page as form.html & close

it type the following URL in

browser http://localhost/form.html

then type the following in the terminal

[root@localhost html]# cd /var/www/cgi-

bin [root@localhost cgi-bin]# gedit

type the following in gedit

#!/usr/bin/perl

use CGI;

$cgi=new CGI;

use DBI;

$rollno=$cgi->param('rollno');

$name=$cgi->param('sname');

my $dbh=DBI->connect("dbi:mysql:student","root","");

my $sth=$dbh->prepare("insert into students

values(?,?)"); $res=$sth->execute($rollno,$name);

$dbh->disconnect;

if($res)

{

print $cgi->header, $cgi-

>start_html, $cgi-

>h1("Record created"),

$cgi->end_html;

}

save that file as form2.cgi

close that file & open a same terminal type as

[root@localhost cgi-bin]# chmod +x form2.cgi

In new browser type the following

http://localhost/form.html

we get the screen as

now check the database as

mysql> select * from students;

+--------+---------------+

http://csetube.weebly.com/

Page 40: Fosslab Manual

http://csetube.tk/

| rollno | sname |

+-------- +--------------- +

| 100 | thamarai |

| 200 | selvi |

| NULL | abcd |

| 71 | thamaraiselvi |

+-------- +--------------- +

4 rows in set (0.00 sec)

http://csetube.weebly.com/

Page 41: Fosslab Manual

http://csetube.tk/

Ex No. 10 PHP with MYSQL

Aim:

To create a login form and test the connectivity with MYSQL

Algorithm:

1. linuxpert@localhost ~]$ su

Password: admin123

[root@localhostlinuxpert]#cd

/var/www/html [root@localhost html]# gedit

2. type the following in gedit and save it as form.html

<html>

<head>

<title>LOGIN</title></head>

<body>

<form

method="post"> <p>

action="connect.php"

"Enter course no"<input type="text" name="cid"></p>

<p>"enter the coursename"<input type="text" name="cname"></p>

<p>"click here to submit"<input type="submit"

name="submit"></p> </form>

</body>

3. Type the following in gedit and save it as connect.php

<?php $cid=$_POST['cid'];

$cname=$_POST['cname'];

$con=@mysql_connect("localhost","root","")or die (mysql-error());

echo "connected to database";

$db=@mysql_select_db("student",$con)or die(mysql_error()); echo

"selected database";

$str="insert into courses values($cid,'$cname')";

$res=@mysql_query($str)

die(mysql_error()); if($res>0)

{

or

http://csetube.weebly.com/

Page 42: Fosslab Manual

http://csetube.tk/

echo "Record created";

}

?>

4. Type the following in the browser

http://localhost/form.html

5. Now go to terminal

[linuxpert@localhost ~]$ mysql -u root -p\

> > Enter password:

Welcome to the MySQL monitor. Commands end with ; or

\g. Your MySQL connection id is 28

Serverversion:5.1.45Source

distribution mysql> show databases;

+--------------------+

| Database |

+--------------------+

| information_schema |

| mysql |

| student |

| test |

+--------------------+

4 rows in set (0.11 sec)

mysql> use student ;

Reading table information for completion of table and column

names You can turn off this feature to get a quicker startup with -A

Database changed

mysql> connect

Connection id: 29 Current

database: student mysql>

show tables;

+-------------------+

| Tables_in_student |

+-------------------+

| course |

| courses |

| students |

+-------------------+

http://csetube.weebly.com/

Page 43: Fosslab Manual

http://csetube.tk/

3 rows in set (0.00 sec)

mysql> select * from courses;

+------ +-------+

| cid | cname |

+------ +-------+

| 1 | java |

| 1 | java |

+------ +-------+

2 rows in set (0.02 sec)

Example 2. Create Login Page

1 Create Login Page (HomePage.php)

<table width="300" border="0" align="center"

cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">

<tr>

<form name="form1" method="post"

action="checklogin.php"> <td>

<table width="100%" border="0" cellpadding="3" cellspacing="1"

bgcolor="#FFFFFF">

<tr>

<td colspan="3"><strong>Member Login

</strong></td> </tr>

<tr>

<td width="78">Username</td>

<td width="6">:</td>

<td width="294"><input name="myusername" type="text"

id="myusername"></td>

</tr>

<tr>

<td>Password</td>

<td>:</td>

<td><input name="mypassword" type="text"

id="mypassword"></td> </tr>

<tr>

<td>&nbsp;</td>

<td>&nbsp;</td>

http://csetube.weebly.com/

Page 44: Fosslab Manual

http://csetube.tk/

<td><input type="submit" name="Submit"

value="Login"></td> </tr>

</table>

</td>

</form>

</tr>

</table>

2 Create Validation Page

(checklogin.php) <?php

$host="localhost"; // Host name

$username="root"; // Mysql default

username //$password=""; // Mysql No

password $db_name="my_db"; // Database

name $tbl_name="members"; // Table name

// Connect to server and select databse. mysql_connect("$host",

"$username")or die("cannot connect");

mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form

$myusername=$_POST['myusername'];

$mypassword=$_POST['mypassword'];

$sql="SELECT * FROM $tbl_name WHERE

username='$myusername'and

password='$mypassword'"; $result=mysql_query($sql);

// Mysql_num_row is counting table

row $count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row

must be 1 row

if($count==1)

echo "Welcome To Our Web Page";

else

echo "Wrong Username or Password";

?>

http://csetube.weebly.com/

Page 45: Fosslab Manual

http://csetube.tk/

Ex No. 11 Python programming with MYSQL

Aim:

To demonstrate the Python program connectivity with MYSQL

Algorithm:

1. Write a Hello World Python Program Create

helloworld.py program as shown below. $ vim

helloworld.py

#!/usr/bin/python

# Hello world python program

print "Hello World!";

2. Verify Python Interpreter Availability

Make sure python interpreter is installed on your system as shown

below.

$ whereis python

python: /usr/bin/python /usr/bin/python2.5 /usr/bin/python2.6

/etc/python

/etc/python2.5 /etc/python2.6 /usr/lib/python2.4

/usr/lib/python3.0 /usr/lib/python2.5 /usr/lib/python2.6

/usr/local/lib/python2.5 /usr/local/lib/python2.6

/usr/include/python2.5 /usr/include/python2.6

/usr/share/python

/usr/share/man/man1/python.1.gz $ which python

/usr/bin/python

3. Execute Python Program

You can either execute using “python helloworld.py”

or “./helloworld.py”.

$ python helloworld.py

Hello World!

( or )

$ chmod u+x helloworld.py

$ ./helloworld.py

Hello World!

http://csetube.weebly.com/

Page 46: Fosslab Manual

http://csetube.tk/

Note: As python is an interpreted language, you don‟t have the compilation

step similar to the C program.

4. Write a sample program in

programming #Sample python program

x=5;

y=5;

print ("x:",x);

print("y:",y);

z=x+y;

print("z:",z);

5. StringConcatenationin

programming #String concatenation

worda='computer';

wordb='science';

print("worda is ",worda);

print("wordb is",wordb);

wordc=worda+" " +wordb;

print("wordc is",wordc);

wordd=worda*3;

print("wordd is ",wordd);

str = 'HelloWorld!'

length=len(str);

print ("str :",str);

print("length:",length);

python

python

print ("first character is",str[0]);

print ("print character from 2rd to 6th :", str[2:7] );

print ("Prints string starting from 3rd character:",str[2:]);

print ("Prints string two times",str * 2);

print ("Prints concatenated string :",str + "TEST"

); print(str[-1]); #print last character print(str[-

6]);#print character from last 6th position

print(str[:-2]);# Everything except the last two characters

6. Write a python program to perform function in

Lists #Python Lists

#!/usr/bin/python

print("\t \t \t Python Lists");

http://csetube.weebly.com/

Page 47: Fosslab Manual

http://csetube.tk/

list = [ 'abcd', 786 , 2.23, 'john', 70.2

] tinylist = [123, 'john']

print("Prints complete list:",list);

print("Prints first element of the list : ",list[0]);

print("Prints elements starting from 2nd to 4th:",list[1:3]);

print("Prints elements starting from 3rd element:",list[2:]);

print("Prints list two times:",tinylist * 2);

print("Prints concatenated lists: ", list + tinylist

); #modify the 4th elements in the list

print("Before modifying the 4th element in list

:",list[4]); list[4]='efgh';

print("4th element in list

:",list[4]); print(" complete

list:",list); #Appending new

elements list.append('ijkl');

print("After appending list:",list);

#deleting an element in list

del list[2];

print("List :",list);

7. Write a python program to perform functions in tuples

#Python Tuples

print("\t \t \t Python tuples");

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2

) tinytuple = (123, 'john')

print("\ncomplete tuple :",tuple);

print("Prints first element of the tuple:", tuple[0]);

print("Prints elements starting from 1nd to 3th:", tuple[1:4]);

print("Prints elements starting from 3rd element:",

tuple[2:]); print("Prints tuple two times:", tinytuple * 2 );

print ("concatenated tuple:",tuple + tinytuple );

8. Write a python program to perform functions in Dictionary.

#Python Dictionary

tinydict = {'name': 'john','code':6734, 'dept':

'sales'} print ("Python Dictionary:" );

print ("complete dictionary",tinydict );

print ("Key :",tinydict.keys()); # Prints all the keys

http://csetube.weebly.com/

Page 48: Fosslab Manual

http://csetube.tk/

print ("values:",tinydict.values()); # Prints all the values

9. Write a python Program to select odd number from the

lists #!/usr/bin/python

#program to select odd number from the list

a=[11,12,13,14,15,16,17,18,19,20,21,31,44,45,10];

print("List is:",a);

n=len(a);

print("length:",n);

i=0;

print("Odd number");

for i in range(len(a)):

if(a[i]%2==1):

print(a[i]);

10. Conditional statement in Python

>>> x = int(raw_input("Please enter an integer: "))

>>> if x < 0:

... x = 0

... print 'Negative changed to zero'

... elif x == 0:

... print 'Zero'

... elif x == 1:

... print 'Single'

... else:

... print 'More'

11. For Statement in Python

>>> # Measure some strings:

... a = ['cat', 'window', 'defenestrate']

>>> for x in a:

...print

len(x) cat 3

window 6

12. The Range() and Len() in Python

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']

>>> for i in range(len(a)):

... print i, a[i]

...

x,

http://csetube.weebly.com/

Page 49: Fosslab Manual

http://csetube.tk/

OUTPUT:

0 Mary

1 had

2a

3 little

4 lamb

13. Prime Number using Python.

>>> for n in range(2, 10):

... for x in range(2, n):

... if n % x == 0:

... print n, 'equals', x, '*', n/x

... break

... else:

... # loop fell through without finding a factor

... print n, 'is a prime number'

..

OUTPUT:

2 is a prime number

3 is a prime number

4 equals 2 * 2

5 is a prime number

6 equals 2 * 3

7 is a prime number

8 equals 2 * 4

9 equals 3 * 3

14. Fibonacci Series using Python

>>> def fib(n): # write Fibonacci series up to n

... """Print a Fibonacci series up to n."""

... a, b = 0, 1

... while b < n:

... print b,

... a, b = b, a+b

...

>>> # Now call the function we just defined:

... fib(2000)

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

http://csetube.weebly.com/

Page 50: Fosslab Manual

http://csetube.tk/

15. Set operations in Python

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']

>>> fruit = set(basket) # create a set without duplicates

>>> fruit

set(['orange', 'pear', 'apple', 'banana'])

>>> 'orange' in fruit # fast membership testing

True

>>> 'crabgrass' in fruit

False

>>> # Demonstrate set operations on unique letters from two words

...

>>> a = set('abracadabra')

>>> b = set('alacazam')

>>> a # unique letters in a

set(['a', 'r', 'b', 'c', 'd'])

>>> a - b # letters in a but not in

b set(['r', 'd', 'b'])

>>> a | b # letters in either a or b

set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])

>>> a & b # letters in both a and b

set(['a', 'c'])

>>> a ^ b # letters in a or b but not

both set(['r', 'd', 'b', 'm', 'z', 'l'])

16. Modules And Error Handling In

Python import sys

try:

f = open('myfile.txt')

s = f.readline()

i = int(s.strip())

except IOError as (errno, strerror):

print "I/O error({0}): {1}".format(errno,

strerror) except ValueError:

print "Could not convert data to an

integer." except:

print "Unexpected error:", sys.exc_info()[0]

raise

http://csetube.weebly.com/

Page 51: Fosslab Manual

http://csetube.tk/

17.Finally class in Python

>>> def divide(x, y):

... try:

... result = x / y

... except ZeroDivisionError:

... print "division by zero!"

... else:

... print "result is", result

... finally:

... print "executing finally clause"

...

>>> divide(2, 1)

result is 2

executing finally clause

>>> divide(2, 0)

division by zero!

executing finally clause

>>> divide("2", "1")

executing finally clause

Traceback (most recent call last):

File "<stdin>", line 1, in ?

File "<stdin>", line 3, in divide

TypeError: unsupported operand type(s) for /: 'str' and 'str'

18. Simple Class Program in python

>>> class Complex:

... def __init__(self, realpart, imagpart):

... self.r = realpart

... self.i = imagpart

...

>>> x = Complex(3.0, -4.5)

>>> x.r, x.i

(3.0, -4.5)

19. Module Program in Python (Fibonacci Series)

A module is a file containing Python definitions and statements. The file name

is the module name with the suffix .py appended. Within a module, the

module‟s name (as a string) is available as the value of the

http://csetube.weebly.com/

Page 52: Fosslab Manual

http://csetube.tk/

global variable __name__. For instance, use your favorite text editor

to create a file called fibo.py in the current directory with the

following contents:

Step 1:

Fibo.py

def fib(n): # write Fibonacci series up to

n a, b = 0, 1

while b <

n: print b,

a, b = b, a+b

Step 2:

>>> import fibo

Step 3:

>>> fibo.fib(1000)

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

http://csetube.weebly.com/

Page 53: Fosslab Manual

http://csetube.tk/

Ex No. 12 Setting Up The Complete Network Interface

Aim:

To set up the complete network interface using ifconfig command like setting

gateway, DNS, IP tables.

Algorithm:

ifconfig

1. Check for network manager status

$service NetworkManager status

2. Login as superuser

$su –

3. Check ip address and note it down

#ifconfig

4. Now stop the network manager service

#service NetworkManager stop

#ifconfig

5. Next stop the local network service also

#service network stop

#service network

#ifconfig

6. Check network status

#service network status

7. Now configure ip address

#ifconfig eth0 192.168.1.12 netmask

255.255.255.0 #ifconfig

8. Next enable the loop up

#ifconfig lo up

9. Try stopping network

again #ifdown eth0

#ifconfig

10. Bring up the network service

#ifconfig eth0

up #ifconfig

service

http://csetube.weebly.com/

Page 54: Fosslab Manual

http://csetube.tk/

11. Repeat step 7 for setting ip address

Note : The ip address which u set must be unique. U can set the ip address

which you have noted down in the beginning of the exercise.

Gateway

1. Check for existing gateway

#route –n

2. Delete default gateway

#route del default

3. Add default gateway

again #route add default

gw 192.168.1.1

#route –n

Domain Name Server (DNS)

1. Edit resolv.conf file and add the below

lines #vi /etc/resolv.conf

nameserver 192.168.1.173

nameserver 4.2.2.2

#ifconfig

#route –n

2. Check the resolv.conf file

#cat ../etc/resolv.conf

Configuring eth0

1. Open eth0 configuration file

#vi /etc/sysconfig/network-scripts/ifcfg-eth0

2. Edit the following lines

BOOTPROTO=”static”

(below onboot edit the following lines)

IPADDR=192.168.1.12 (use ur ip add)

NETMASK=255.255.255.0

http://csetube.weebly.com/

Page 55: Fosslab Manual

http://csetube.tk/

NETWORK=192.168.1.0

#ifconfig

3. Start the eth0 service

ifup eth0

#ifconfig

#route –n

4. Edit the network file under

/etc #vi /etc/sysconfig/network

Add the following line

GATEWAY=192.168.1.172

5. Now restart network

service #service network

restart #ifconfig

#route –n

http://csetube.weebly.com/