You are on page 1of 52

EASWARI ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

LAB MANUAL CS2406 OPEN SOURCE LAB Year/Sem : IV B.E(CSE) /VII Academic Year: 2012-13

PREPARED BY Mr. Bharathi Raja N

APPROVED BY HOD/CSE

CS2406 C 2 OBJECTIVE:

OPEN SOURCE LAB

L T P 0 0 3

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

1. Kernel conguration, 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 congure 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 les to windows Install Common Unix Printing System(CUPS) 6. Write userspace drivers using fuse -- easier to debug and less dangerous to the system (Writing full-edged drivers is dicult at student level)

7. GUI programming : a sample programme using Gambas since the students have VB knowledge. However, one should try using GTK or QT 8. Version Control System setup and usage using RCS, CVS, SVN 9. Text processing with Perl: database e.g., MYSQL simple programs, connecting with

10. Running PHP : simple applications like login forms after setting up a LAMP stack 11. Running Python : some simple exercise e.g. Connecting with MySql database 12. Set up the complete network interface usinf ifcong command like setting gateway, DNS, IP tables, etc.,

LIST OF EXPERIMENTS
Ex No. 1 Kernel Conguration, 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 CONTENT BEYOND THE SYLLABUS:
1. Sample Django application for displaying Hello world message with Current time. 2. Create a new directory named templates in blog directory

Ex No. 1 Kernel Conguration, 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 Makele vi Makele 5. Look for the line EXTRAVERSION and append a name ex. 2.6.35.7-mykernel 6. make menucong (choose the desired kernel options) 7. make bzImage (builds the kernel) 8. su 9. cp arch/x86/boot/bzImage /boot/vmlinuz-2.6.35.7 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

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)

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 conguration $./congure 8. Do make $make 9. Login as superuser $su 10.Install webattery package #make install 11.Check for webattery package #which webattery

Ex No. 4 Packet Management System Aim: To build and maintain RPM or DEB packages, serve packages over http or ftp and also to congure 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 les 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 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 conguration le so that the clients can use the conguration le for installing qmail packages from the server $su #cd /etc/yum.repos.d/ #ls l #vi qmail.repo Type the following lines into the le [qmail] name=Q-Mail packages baseurl=http://localhost/qmail enabled=1 gpgcheck=0 save the le :wq 20. View the qmail.repo le #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 YUM fedora.repo, fedora-updates.repo 1. Login as superuser and move to /etc/yum.repos.d/ $su #cd /etc/yum.repos.d

#ls l 2. Edit fedora.repo le #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 le 3. Edit fedora-updates.repo #vi fedora-updates.repo Change enabled=0 and save the le 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 nd the le rpmfusion-free-release-14.0.4.noarch.rpm and copy the path 2. In the terminal login as superuser $su 3. N o w y o u h a v e t o i n s t a l l t h e r p m f u s i o n - f r e e release-14.0.4.noarch.rpm by pasting the path after rpm #rpm ivh http://fosslab/f14repo/rpmfusion/i386/free/rpmfusionfree-release-14.0.4.noarch.rpm 4. N e x t y o u h a v e t o i n s t a l l t h e r p m f u s i o n - n o n f r e e release-14.0.4.noarch.rpm by pasting the path after rpm #rpm ivh http://fosslab/f14repo/rpmfusion/i386/free/rpmfusionnonfree-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 le 7. Edit rpmfusion-free-updates.repo Change enabled=0 and save the le 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 le 9. Edit rpmfusion-nonfree-updates.repo Change enabled=0 and save the le 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*

Ex No. 5 Installing Various Software Packages Aim: To install samba and share les 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 refox and type the following #open refox 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 #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 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

Ex No. 6 FUSE - File System in User Space Aim: To write userspace drivers using fuse 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 le and view it 8. Then look for log.c and view it 9. Now try to fuse cags $pkg-cong fuse --cags 10.Then fuse libs $pkg-cong fuse --libs 11. Perform makele $make 12. Look for bbfs le (coloured green) 13. Move to examples folder $cd ../examples 14. View the mountdir and rootdir directories $ls al mountdir $ls al rootdir 15. Move to rootdir folder and create some empty les $cd rootdir/ $touch myle -- easier to debug and less

$ls l 16. Move back to examples folder and check the no of les in mountdir $cd .. $ls l mountdir 17.Check the les in rootdir/ $ls l rootdir/ 18.Now call the fuse bbfs $ ..src/bbfs rootdir/ mountdir/ 19.Now check the no of les under mountdir/ $ls l mountdir/ 20. Now mount the lesystem to see the fuse working $mount 21. Next unmount the fuse and check for the no of les in mountdir/ $fusermount u mountdir/ $ls l $mount $tail f bbfs.log

Ex No. 7 GUI Programming Using GAMBAS2 Aim: To create a login form for booking train ticket using GAMBAS2 Algorithm: 1. 2. 3. 4. 5. 6. Go to Applications ! Programming Under Programming ! Gambas2 In the Gambas2 environment select New Project Next select the location of the project to be created In the next step give a name for your project Now after your project is created you have to create forms for your project 7. The dierent tools are available under the toolbox 8. Add the appropriate tools to your form 9. Next add the appropriate code for the dierent controls placed on the form 10.Save the project 11.Run the project

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. Download CollabNetSubversionEdge-1.3.2_linux-x86_64.tar.gz to downloads folder 5. G o t o P l a c e s ! D o w n l o a d s a n d e x t r a c t CollabNetSubversionEdge-1.3.2_linux-x86_64.tar.gz 6. Login as superuser and edit sudo $su #visudo 7. In the visudo le 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 $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

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 rst.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 ~]$ perl scalar.pl Camel 42243 3. Array in PERL #!usr/bin/perl my @animal=("cow","Bualo","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 cow Bualo 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 ~]$ perl hash.pl red 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) { print "$color{$key}\n"; } delete $color{'apple'}; # to remove specic 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 ioop.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"; $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 xed )in perl #!usr/bin/perl my @animals=("cow","bualo","camel",123,100,243,300); foreach $key(@animals) { print "$key\n"; } output: [linuxpert@localhost ~]$ perl foreach.pl cow bualo camel 123 100 243 300 11. String operation: #!usr/bin/perl $a="hello"; $b="world"; 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 specied location in array, to access the single element output: [linuxpert@localhost ~]$ perl arrayvariable.pl ARRAY(0x8358a70) hello 122 200 hello 122 12.4 Hash variable in perl #!usr/bin/perl %color=('apple'=>"red",'banana'=>"yellow",'orange'=>"orange"); $h=\%color; print "$h\n";#print the reference address @keys=keys %$h; 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 apple orange red 12.5 Magic variable in perl #!usr/bin/perl %color=('apple'=>"red",'banana'=>"yellow",'orange'=>"orange"); $h=\%color; 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 #!usr/bin/perl sub sayHello() { print "Hello\n"; } &sayHello(); output: [linuxpert@localhost ~]$ perl function.pl Hello 13.1 function with 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 ~]$ perl functionparam.pl 25 13.2 Find Maximum value using function #!usr/bin/perl sub max() { $max=shift @_; # shift function remove the rst 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: [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"; } 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 "\nQualication :$Education"; 16. Program to perform array releted function #!/usr/bin/perl # Dene 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 f 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"; print "\n"; # Remove one element from the last of the array.

print "\n Pop Function"; pop(@coins); print "\nFourth Statement : @coins"; print "\n"; # Remove one element from the beginning of the array. print "\n Shift Function"; shift(@coins); print "\nFifth Statement : @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", "Logic", "Solutions"); print "\n @browser"; print "\n"; #replacing elements at index 1,2 @browser = ("System", "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); 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 le has to be opened in read-only mode # > sign indicates that le has to be opened in writing mode Entities Denition < 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"); while(<DATA>) { print "$_"; } 19. Example which opens an existing le le1.txt and read it line by line and generate another copy le2.txt #!/usr/bin/perl # Open le to read open(DATA1, "<le1.txt"); # Open new le to write open(DATA2, ">le2.txt"); # Copy data from one le to another.

while(<DATA1>) { print DATA2 $_; } close( DATA1 ); close( DATA2 ); #delete a le le3.txt using unlink function unlink ("/strawberry/perl/le3.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"; %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 les 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 le!"; @leinput = <text>; print $leinput[0]; print $leinput[1]; print $leinput[2];

print $leinput[3]; print $leinput[4]; print $leinput[5]; print $leinput[6]; print $leinput[7]; print $leinput[8]; print $leinput[9]; close (text); 22. PERL - Copying File We can duplicate a le using the copy function. Copy takes two values the URL of the le to be copied and the URL of the new le. Since we want to duplicate the le 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 le1 to le2"; $letobecopied = "le1.txt"; $newle = "le2.txt"; copy($letobecopied, $newle) or die "File cannot be copied."; print "\n Now open the new le"; print "\n Move function"; $oldlocation = "sample.txt"; $newlocation = "f:/keerthi/sample.txt"; move($oldlocation, $newlocation); # unlink function to delete specic les from your web server. print "\n Delete function"; $le = "F:/keerthi/sample.txt"; if (unlink($le) == 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) mysql> create database student; Query OK, 1 row aected (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:$!"); } $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; +--------+----------+ | 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)

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> </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 le as form2.cgi close that le & 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; +--------+---------------+ | rollno | sname | +--------+---------------+ | 100 | thamarai | | 200 | selvi |

| NULL | abcd | | 71 | thamaraiselvi | +--------+---------------+ 4 rows in set (0.00 sec)

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@localhost linuxpert]# 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 action="connect.php" method="post"> <p> "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) or die(mysql_error()); if($res>0) { 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 Server version: 5.1.45 Source 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 o 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 | +-------------------+ 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> <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"; ?>

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! Note: As python is an interpreted language, you dont have the compilation step similar to the C program. 4. Write a sample program in python programming #Sample python program

x=5; y=5; print ("x:",x); print("y:",y); z=x+y; print("z:",z); 5. String Concatenation in python 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); print ("rst 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"); list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print("Prints complete list:",list); print("Prints rst 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 rst 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 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 x, 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] ... 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 nding 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 b(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 dened: ... b(2000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 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('myle.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 17.Finally class in Python >>> def divide(x, y): ... try: ... result = x / y ... except ZeroDivisionError: ... print "division by zero!" ... else: ... print "result is", result ... nally: ... print "executing nally clause" ... >>> divide(2, 1) result is 2 executing nally clause >>> divide(2, 0) division by zero! executing nally clause >>> divide("2", "1") executing nally 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 le containing Python denitions and statements. The le name is the module name with the sux .py appended. Within a module, the modules name (as a string) is available as the value of the global variable __name__. For instance, use your favorite text editor to create a le called bo.py in the current directory with the following contents: Step 1: Fibo.py def b(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b Step 2: >>> import bo Step 3: >>> bo.b(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

Ex No. 12 Setting Up The Complete Network Interface Aim: To set up the complete network interface using ifcong command like setting gateway, DNS, IP tables. Algorithm: ifcong 1. Check for network manager status $service NetworkManager status 2. Login as superuser $su 3. Check ip address and note it down #ifcong 4. Now stop the network manager service #service NetworkManager stop #ifcong 5. Next stop the local network service also #service network stop #service network #ifcong 6. Check network status #service network status 7. Now congure ip address #ifcong eth0 192.168.1.12 netmask 255.255.255.0 #ifcong 8. Next enable the loop up #ifcong lo up 9. Try stopping network service again #ifdown eth0 #ifcong 10. Bring up the network service #ifcong eth0 up #ifcong 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 le and add the below lines #vi /etc/resolv.conf nameserver 192.168.1.173 nameserver 4.2.2.2 #ifcong #route n 2. Check the resolv.conf le #cat ../etc/resolv.conf Conguring eth0 1. Open eth0 conguration le #vi /etc/syscong/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 NETWORK=192.168.1.0 #ifcong 3. Start the eth0 service ifup eth0 #ifcong #route n 4. Edit the network le under /etc #vi /etc/syscong/network Add the following line

GATEWAY=192.168.1.172 5. Now restart network service #service network restart #ifcong #route n

CONTENT BEYOND THE SYLLABUS:


1. Sample Django application for displaying Hello world message with Current time. 2. Create a new directory named templates in blog directory Introduction Django is an web application framework, written in Python, which follows the Model-View-Controller (MVC) Pattern. It is named after Django Reinhardt, a gypsy jazz guitarist from the 1930sto early 1950s. To this day, hes considered one of the best guitarists of all time. Django is pronounced JANG-oh. Rhymes with FANG-oh. It was originally developed to manage several news-oriented sites for The World Company of Lawrence, Kansas, etc., and was released publicly under BSD license by July 2005. In June 2008, It was announced that a newly formed Django Software Foundation will take care of Django in the future. The Django framework components Object-relational mapper Dene your data models entirely in Python. You get a rich, dynamic databaseaccess API for free but you can still write SQL if needed. Automatic admin interface Save yourself the tedious work of creating interfaces for people to add and update content. Django does that automatically, and it's production-ready. Elegant URL design Design pretty, cruft-free URLs with no framework-specic limitations. Be as exible as you like. Template system Use Django's powerful, extensible and designer-friendly template language to separate design, content and Python code. Cache system Hook into memcached or other cache frameworks for super performance caching is as granular as you need. Internationalization Django has full support for multi-language applications, letting you specify translation strings and providing hooks for language-specic functionality. The Programs

3. Sample Django application for displaying Hello world message with Current time. Create a project # Get into project folder which you created now. # Note: When you run django-admin.py startproject mysite, Django will automatically create a new directory containing four les: * __init__.py, which will be empty. This le is required to tell Python that the directory is a Python module and can be imported (and imported from). * manage.py, which provides a number of convenience functions for working with the project. * settings.py, which will be the projects settings le. * urls.py, which will be the projects root URL conguration. Next you could check the project whether you have installed successfully or not by running the django's inbuilt development server named runserver Now open the url http://127.0.0.1:8000/ in your browser. You will get the following output.

Create an application
Get into project mysite. And create an application
#

Note:
When you run django-admin.py startapp web, Django creates a sub-directory of your project directory, and creates the following les: web/ __init__.py models.py tests.py views.py __init__.py, which serves the same purpose as at the project level. models.py, which should hold the applications model classes. views.py, which is for any custom views the application wants to provide. Create a new directory named templates in blog directory # Get into project folder which you created now.
*********

You might also like