foss lab manual

117
Dr. N.G.P INstItute Of techNOlOGy cOImbatOre-641048 Department of Computer Science and Engineering (B.E Computer Science and Engineering) LAB MANUAL OPEN SOURCE LAB Prepared Verified By By Ms.K. Thamarai Selvi Mrs. NagaLakshmi Venugopal

Upload: vsbcse

Post on 27-Nov-2014

1.885 views

Category:

Documents


42 download

TRANSCRIPT

Page 1: Foss Lab Manual

Dr. N.G.P INstItute Of techNOlOGy

cOImbatOre-641048

Department of Computer Science and Engineering

(B.E Computer Science and Engineering)

LAB MANUAL

OPEN SOURCE LAB

Prepared Verified

By By

Ms.K. Thamarai Selvi Mrs. NagaLakshmi Venugopal

Page 2: Foss Lab Manual

Index

S.No Name of The Experiment Page No

1 Linux Installation

2 MySQL Installation

3 Apache Installation

4 PHP and MySQL Connectivity

5 Python Programming

6 PERL And CGI Script

7 NS2 Instal lat ion

2

Page 3: Foss Lab Manual

LINUX LINUX

INSTALLATION INSTALLATION

3

Page 4: Foss Lab Manual

INTRODUCTION TO OPEN SOURCE SOFTWARE

Open-source software (OSS) is computer software that is available in source

code form for which the source code and certain other rights normally reserved for

copyright holders are provided under a software license that permits users to study,

change, and improve the software. Open source licenses meet the requirements of

the Open Source Definition. Some open source software is available within the

public domain. Open source software is very often developed in a public,

collaborative manner. Open-source software is the most prominent example of

open-source development and often compared to (technically defined) user-

generated content or (legally defined) open content movements. The term open-

source software originated as part of a marketing campaign for free software.

Popular distributions:

Well-known Linux distributions include:

CentOS, a distribution derived from the same sources used by Red Hat,

maintained by a dedicated volunteer community of developers with both

100% Red Hat-compatible versions and an upgraded version that is not

always 100% upstream compatible

Debian, a non-commercial distribution maintained by a volunteer developer

community with a strong commitment to free software principles

Fedora, a community distribution sponsored by Red Hat

4

Page 5: Foss Lab Manual

Gentoo, a distribution targeted at power users, known for its FreeBSD Ports-

like automated system for compiling applications from source code

Knoppix, the first Live CD distribution to run completely from removable

media without installation to a hard disk, derived from Debian

Kubuntu, the KDE version of Ubuntu.

Linux Mint, a distribution based on and compatible with Ubuntu.

Mandriva, a Red Hat derivative popular in France and Brazil, today

maintained by the French company of the same name.

openSUSE a community distribution mainly sponsored by Novell.

Oracle Enterprise Linux, which is a derivative of Red Hat Enterprise Linux,

maintained and commercially supported by Oracle.

Pardus, Turkey's national operating system developed by

TÜBİTAK/UEKAE.

PCLinuxOS, a derivative of Mandriva, grew from a group of packages into a

community-spawned desktop distribution.

Red Hat Enterprise Linux, which is a derivative of Fedora, maintained and

commercially supported by Red Hat.

Slackware, one of the first Linux distributions, founded in 1993, and since

then actively maintained by Patrick J. Volkerding.

SUSE Linux Enterprise, derived from openSUSE, maintained and

commercially supported by Novell.

Ubuntu, a popular desktop and server distribution derived from Debian,

maintained by Canonical Ltd..

Xubuntu, is the Xfce version of the popular desktop distro Ubuntu.

Commonly used by Linux users that wish to have the function of a bigger

distro such as Ubuntu or openSuse with the speed of a smaller distro.

5

Page 6: Foss Lab Manual

DistroWatch attempts to include every known distribution of Linux, whether

currently active or not; it also maintains a ranking of distributions based on page

views, as a measure of relative popularity.

Programming language support:

ABCL — an implementation of Common Lisp for the JVM

ArgoUML — ArgoUML is a modelling tool that helps you design using

UML diagrams

CLISP — a Common Lisp interpreter and bytecode-compiler

Clojure — a Lisp (not Scheme nor Common Lisp) targeting the JVM

DJGPP — a 32-bit DOS port of GCC and other GNU utilities

Dragonfly — newLISP based web development framework

Eiffel

ECL — an Common Lisp implementation designed for integration with C

Erlang - a general-purpose concurrent programming language and runtime

system

Experix — command line and stack system for data acquisition and analysis

and graphics

Forth

Free Pascal A Pascal compiler and cornerstone of the Lazarus RAD

FreeBASIC A BASIC compiler

GCC — a set of compilers for multiple programming languages and

platforms, including

o C

o C++

o Objective-C

6

Page 7: Foss Lab Manual

o Ada

o Java

o Pascal

o Fortran

GT.M is an open source MUMPS (a.k.a. M) compiler for Linux

Harbour — compiler for the xBase superset language often referred to as

Clipper

Jikes — Java compiler

LLVM — Optimizing compiler toolkit

o Clang — NSCA licensed LLVM compiler frontend for C/C++ and

Objective-C

Logo — Derivative of Lisp without parenthesis, for kids, with Turtle

Graphics

Lua - a lightweight, reflective, imperative and procedural language,

designed as a scripting language with extensible semantics as a primary

goal.

MinGW — Windows port of +GCC

Mono development platform — Multi-platform .NET implementation (C#)

based on the ECMA/ISO standards

MMIXware — simulator for MMIXAL language and MMIX processor

Objective Caml — a practical and fast functional OO language

ODB — a compiler-based object-relational mapping (ORM) system for C++

OpenCOBOL — an open source implementation of the COBOL

programming language

OpenJDK — Sun's Java Development Kit based completely on free and

open source code

Parser — a language for dynamic website creation

7

Page 8: Foss Lab Manual

Perl — a programming language strong on text processing

PHP — a scripting language designed for web site applications

PCC — a BSD licensed C compiler

Processing - a visual programming language based on Java

Prolog — Logic programming

Python — a high-level scripting language

Refal - a functional programming language

REXX - an interpreted programming language

Rhino — a JVM-based JavaScript engine

Ruby — a high-level scripting language

o Ruby on Rails — Ruby-based web development framework

SBCL — a high-performance Common Lisp implementation

Spidermonkey — C/C++ JavaScript engine of the Mozilla project

StarUML — a software modeling tool

Tcl/Tk — a high-level scripting language with a graphical toolkit

Wavemaker - a visual, drag and drop web development platform based on

Java and Spring/Hibernate.

8

Page 9: Foss Lab Manual

INTRODUCTION TO LINUX OPERATING SYSTEM

Linux refers to the family of Unix-like computer operating systems using the

Linux kernel. Linux can be installed on a wide variety of computer hardware,

ranging from mobile phones, tablet computers and video game consoles, to

mainframes and supercomputers. Linux is a leading server operating system, and

runs the 10 fastest supercomputers in the world. Use of Linux by end-users or

consumers has increased in recent years, partly owing to the popular Ubuntu,

Fedora, and openSUSE distributions and the emergence of netbooks with pre-

installed Linux systems and smartphones running embedded Linux.

The development of Linux is one of the most prominent examples of free and open

source software collaboration; typically all the underlying source code can be used,

freely modified, and redistributed, both commercially and non-commercially, by

anyone under licenses such as the GNU General Public License. Typically Linux is

packaged in a format known as a Linux distribution for desktop and server use.

Linux distributions include the Linux kernel and all of the supporting software

required to run a complete system, such as utilities and libraries, the X Window

System, the GNOME and KDE desktop environments, and the Apache HTTP

Server. Commonly used applications with desktop Linux systems include the

Mozilla Firefox web-browser, the OpenOffice.org office application suite and the

GIMP image editor.

9

Page 10: Foss Lab Manual

The name "Linux" comes from the Linux kernel, originally written in 1991 by

Linus Torvalds. The main supporting user space system tools and libraries from

the GNU Project (announced in 1983 by Richard Stallman) are the basis for the

Free Software Foundation's preferred name GNU/Linux.

STANDARD INSTALLATION OF FEDORA 14

Fedora is an RPM-based, general purpose collection of software including an

operating system based on the Linux kernel, developed by the community-

supported Fedora Project and sponsored by Red Hat. The Fedora Project's mission

is to lead the advancement of free and open source software and content as a

collaborative community.

One of Fedora's main objectives is not only to contain software distributed under a

free and open source license, but also to be on the leading edge of such

technologies. Fedora developers prefer to make upstream changes instead of

applying fixes specifically for Fedora—this ensures that their updates are available

to all Linux distributions. In 2008, Linus Torvalds, author of the Linux kernel,

started that he used Fedora because it had fairly good support for the PowerPC

processor architecture which he favored at the time.

Fedora Features

There are some really neat, new features in Fedora that do work well. they're going

to be more exiting for system administrators and developers than they are someone

just running Fedora at home.

Easily the most important of these is the arrival of of Simple Protocol for

Independent Computing Environment (SPICE). This is a desktop presentation

10

Page 11: Foss Lab Manual

service protocol, like Microsoft's RDP (Remote Desktop Protocol) and Citrix's

ICA (Independent Computing Architecture), that you use to run thin-client

desktops.

SPICE will let you support remote desktops from a Fedora server, and eventually a

Red Hat Enterprise Linux (RHEL) server. Each remote desktop will run as a

Kernel Virtual Machine (KVM).

SPICE is being very useful in schools or anywhere that needs centralized control

or inexpensive desktops. It may prove a new and interesting way to get users on a

Linux "desktop."

Fedora also includes a new interface: MeeGo. This is the interface for the MeeGo

operating system, which is meant for netbooks, Mobile Internet Devices (MID)

and embedded devices. While not as well known or as mature as Android, MeeGo

shows great promise. By making it available on Fedora, developers can develop

applications for MeeGo.

Distribution

Package Kit, the default package manager front-end on Fedora

The Fedora Project distributes Fedora in several different ways:

Fedora DVD/CD set – a DVD or CD set of all major Fedora packages at

time of shipping;

Live images – CD or DVD sized images that can be used to create a Live

CD or boot from a USB flash drive and optionally install to a hard disk;

Minimal CD – used for installing over HTTP, FTP or NFS.

11

Page 12: Foss Lab Manual

The Fedora Project also distributes custom variations of Fedora which are called

Fedora spins. These are built from a specific set of software packages and have a

combination of software to meet the requirements of a specific kind of end user.

Fedora spins are developed by several Fedora special interest groups. It is also

possible to create Live USB versions of Fedora using Fedora Live USB creator.

Fedora Core:

Fedora Core 1 was the first version of Fedora and was released on November 6,

2003. It was codenamed Yarrow. Fedora Core 1 was based on Red Hat Linux 9

and shipped with version 2.4.19 of the Linux kernel, version 2.4 of the GNOME

desktop environment, and K Desktop Environment 3.1.

Fedora Core 2 was released on May 18, 2004, codenamed Tettnang. It shipped

with Linux 2.6, GNOME 2.6, KDE 3.2, and SELinux. XFree86 was replaced by

the newer X.org, a merger of the previous official X11R6 release, which

additionally included a number of updates to Xrender, Xft, Xcursor, fontconfig

libraries, and other significant improvements.

Fedora Core 3 was released on November 8, 2004, codenamed Heidelberg. This

was the first release of Fedora Core to include the Mozilla Firefox web browser, as

well as support for the Indic languages. Fedora Core 3 shipped with GNOME 2.8

and KDE 3.3. It was the first release to include the new Fedora Extras repository.

Fedora Core 4 was released on June 13, 2005, with the codename Stentz. It

shipped with Linux 2.6.11, KDE 3.4 and GNOME 2.10. This version introduced

the new Clearlooks theme. It also shipped with the OpenOffice.org 2.0 office suite,

as well as Xen, a high performance and secure open source virtualization

framework.

12

Page 13: Foss Lab Manual

Fedora Core 5 was released on March 20, 2006, with the codename Bordeaux, and

introduced the Fedora Bubbles artwork.It was the first Fedora release to include

Mono and tools built with it such as Beagle, F-Spot and Tomboy. It also

introduced new package management tools such as pup and pirut (see Yellowdog

Updater, Modified).

Fedora Core 6 was released on October 24, 2006, codenamed Zod. This release

introduced the Fedora DNA artwork, replacing the Fedora Bubbles artwork used in

Fedora Core 5. This version introduced support for the Compiz compositing

window manager and AIGLX.

Fedora 7, codenamed Moonshine, was released on May 31, 2007. The biggest

difference between Fedora Core 6 and Fedora 7 was the merging of the Red Hat

"Core" and Community "Extras" repositories, and the new build system put in

place to manage those packages.

Fedora 7 featured GNOME 2.18 and KDE 3.5, a new theme entitled Flying High,

OpenOffice.org 2.2 and Firefox 2.0. Fast user switching was fully integrated and

enabled by default. Also, there were a number of updates to SELinux.

Fedora 8, codenamed Werewolf, was released on November 8, 2007.

Some of the new features and updates in Fedora 8 included:

PulseAudio

system-config-firewall

Codeina

IcedTea

NetworkManager

Better laptop support

13

Page 14: Foss Lab Manual

Fedora 8 also included a new desktop artwork entitled Infinity, and a new

desktop theme called Nodoka. A unique feature of Infinity is that the

wallpaper can change during the day to reflect the time of day.

Fedora 9, codenamed Sulphur, was released on May 13, 2008.

Some of the new features of Fedora 9 included:

GNOME 2.22.

KDE 4.0 , which is the default interface as part of the KDE spin.

OpenJDK 6 has replaced IcedTea.

Data Persistence in USB images.

Fedora 9 featured a new artwork entitled Waves which, like Infinity in

Fedora 8, changes the wallpaper to reflect the time of day.

Fedora 10, codenamed Cambridge, was released on November 25, 2008. It

flaunts the new Solar artwork. Its features include:

Faster startup using Plymouth

Support for ext4 filesystem

LXDE Desktop Environment (LXDE Spin)

GNOME 2.24

KDE 4.1 (KDE Spin)

Page 15: Foss Lab Manual

Fedora 11, codenamed Leonidas, was released on June 9, 2009. This was the

first release whose artwork is determined by the name instead of by

users voting on themes.

Some of the features in Fedora 11 are:

ext4 as the default file system

GCC 4.4

GNOME 2.26

KDE 4.2 (KDE Spin)

2.6.29 Linux kernel

fprint - support for systems with fingerprint readers

Fedora 12, codenamed Constantine, was released on November 17, 2009.

Some of the features in Fedora 12 are:

Optimized performance.

Improved WebCam support (Cheese)

Automatic bug reporting tool (abrt)

Bluetooth on demand

Many virtualization enhancements (KVM, libvirt, libguestfs)

GCC 4.4, GNOME 2.28 & GNOME Shell preview

KDE 4.3, KDE 4.4

Fedora 13, codenamed Goddard, was released on May 25, 2010. During

early development, Fedora project-leader Paul Frields anticipated "looking

at the fit and finish issues. We have tended to build a really tight ship with

Fedora, but now we want to make the décor in the cabins a little more

sumptuous and to polish the deck chairs and railings."

15

Page 16: Foss Lab Manual

Features of Fedora 13 include:

Automatic printer-driver & Automatic language pack installation

Redesigned user-account tool

A new way to install Fedora over the Internet

Updates to NFS

Inclusion of Zarafa Open Source edition

KDE PulseAudio Integration

New command-line interface for NetworkManager

Fedora 14, codenamed Laughlin, was released on November 2, 2010.

Features of Fedora 14 include:

Updated Boost to the upstream 1.44 release

Addition of the D compiler (LDC) and D standard runtime library

(Tango)

Updated Fedora's Eclipse stack to Helios releases

Inclusion of virt-v2v tool

Inclusion of Spice framework for VDI deployment

NetBeans IDE updated to the 6.9 release

Inclusion of a tech preview of the GNOME Shell environment

16

Page 17: Foss Lab Manual

Basic Installation Steps:

1. Boot from the DVD.

2. Skip the media test by pressing the tab and return keys on the

keyboard.

17

Page 18: Foss Lab Manual

18

Page 19: Foss Lab Manual

3. Click the "Next" button on the welcome screen.

19

Page 20: Foss Lab Manual

4. Select the appropriate language, then click the "Next" button.

20

Page 21: Foss Lab Manual

5. Select the appropriate keyboard layout, then click the "Next" button.

21

Page 22: Foss Lab Manual

6. When prompted, click the "Re-initialize drive" button.

22

Page 23: Foss Lab Manual

7. When prompted, click the "Re-initialize" button.

23

Page 24: Foss Lab Manual

8. Enter a fully qualified hostname, then click the "Next" button.

9. Select the appropriate timezone by clicking on the nearest city on the

map, then click the "Next" button.

24

Page 25: Foss Lab Manual

25

Page 26: Foss Lab Manual

10. Enter the root password, then click the "Next" button.

11. Select the "Use All Space" option, uncheck the "Encrypt system"

option and check the "Review and modify partitioning layout" option,

then click the "Next" button.

26

Page 27: Foss Lab Manual

12. The current partitioning layout is presented. If the OS is to be used for

an Oracle installation, make sure the swap partition is at least 2G

(2048M) in size. Once you are happy with the partition structure, click

the "Next" button followed by the "Format" and "Write changes to

27

Page 28: Foss Lab Manual

disk"button.

28

Page 29: Foss Lab Manual

13. Accept the default boot loader settings by clicking the "Next" button.

14. Select the appropriate packages to install and check all three

additional repositories.

29

Page 30: Foss Lab Manual

15. Selecting the repositories will require you to enter your network

configuration. Select the appropriate network interface, highlight the

"System eth0" adapter and click the "Edit" button. Click on the the

"IPv4 Settings" tab, select the appropriate method and enter the

required information. When complete, click the "Apply" and "Close"

buttons.

30

Page 31: Foss Lab Manual

31

Page 32: Foss Lab Manual

16. Once the repositories are selected, select the "Customize Now" option

and click the "Next" button.

17. Select the appropriate package groups and optional packages for your

installation and click the "Next" button.

32

Page 33: Foss Lab Manual

33

Page 34: Foss Lab Manual

18. Wait while the installation completes.

19. When the installation is complete, restart the machine as instructed.

When the machine has restarted, click the "Forward" button on the

welcome screen.

34

Page 35: Foss Lab Manual

35

Page 36: Foss Lab Manual

20. Accept the license agreement by clicking the "Forward" button.

36

Page 37: Foss Lab Manual

21. Enter login user details, then click the "Forward" button.

22. Set the appropriate date-time information, then click the "Forward"

button.

37

Page 38: Foss Lab Manual

23. Decide if you want to send a hardware profile to the Fedora project,

then click the "Finish" button.

38

Page 39: Foss Lab Manual

39

Page 40: Foss Lab Manual

24. Click the username you defined previously.

40

Page 41: Foss Lab Manual

25. Enter the password and click the "Log In" button.

26. After you've logged in, you are presented with the default Fedora

desktop.

41

Page 42: Foss Lab Manual

42

Page 43: Foss Lab Manual

MySQLMySQL

INSTALLATIO INSTALLATIONN

MYSQL INSTALLATION

…………………………………………………………………………………………………………

43

Page 44: Foss Lab Manual

[root@server root]# cd /root

[root@server root]# mkdir /root/files /data /data/mysql

[root@server root]# cd files

[root@server root]# wget http://www.d9x.net/downloads/unix/mysql-

4.0.12.tar.gz

[root@server root]# tar xzvf mysql-4.0.12.tar.gz

[root@server root]# cd mysql-4.0.12

if your using FreeBSD use "adduser" instead of "useradd".

[root@server root]# groupadd mysql

[root@server root]# useradd -g mysql mysql

[root@server root]# ./configure --prefix=/usr/local/mysql

--datadir=/data/mysql

DataDir is where your mysql databases will be stored including the database

which contains all mysql user accounts,

you can easily backup all databases/users by saving the contents of this

folder. /data/mysql

NOTE: If you see ERROR: No curses/termcap library found" find where

libncurses.so.5 is installed on your system and add the following flag to your

configure statement : --with-named-curses-libs=/usr/lib/libncurses.so.5 (or

where ever it may be)

if you get a "mod_auth_dbm" Error

Copy the ndbm.h file from /usr/include to the /usr/include/db1 directory (or

install db1-devel)

44

Page 45: Foss Lab Manual

if you get a "no acceptable C compiler found in $PATH" Error

Install a c compiler, example: gcc

if you get "libmysql.c:1349: warning: passing arg 5 of `gethostbyname_r'

from incompatible pointer type" Error

you need to install a c++ compiler, install: libstdc++-devel, gcc-c++ (same

version as gcc)

[root@server root]# make

[root@server root]# make install

[root@server root]# ./scripts/mysql_install_db

[root@server root]# ln -s /usr/local/mysql/share/mysql/mysql.server

/sbin/mysqld

[root@server root]# chown -R mysql:mysql /data/mysql

[root@server root]# chown -R mysql:mysql /usr/local/mysql

Start, Stop & Restart MySQL

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

[root@server root]# mysqld start

[root@server root]# mysqld stop

[root@server root]# mysqld restart

Using MySQL

45

Page 46: Foss Lab Manual

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

Export Database:

[root@server root]# /usr/local/mysql/bin/mysqldump -u root -p

database_name > database_name.sql

Import Database:

[root@server root]# /usr/local/mysql/bin/mysql -u root -p database_name <

database_name.sql

Set root password:

[root@server root]# /usr/local/mysql/bin/mysqladmin -u root -p password

NEW_PASS

NOTE: When it prompts you to enter the password, just hit Enter

if you don't see an error, the password was successfully changed.

Uninstalling MySQL

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

[root@server root]# rm -rf /usr/local/mysql

[root@server root]# rm -rf /data/mysql

[root@server root]# rm -rf /sbin/mysqld

46

Page 47: Foss Lab Manual

APACHEAPACHE

INSTALLATIO INSTALLATIONN

47

Page 48: Foss Lab Manual

APACHE INSTALLATION

Introduction

The Apache Web server is arguably the most popular Web server in use on

the Internet today. Here are some of the reasons why Apache is so popular;

you don't have to be running Windows to run Apache. It was developed on

various Unix/Linux/BSD platforms, and then recently ported to Win32.

Internet Information Server, a Web server made by Microsoft for the

Windows NT platform, is made for use in the "Windows-only" world. While

IIS has many features, it’s lack of portability limits it’s market share.

Another reason for Apache's widespread acceptance is its overall stability.

While you can slow down an Apache Web server, you can rarely, if ever,

kill one. The Apache Web server service is near bulletproof. Lastly, it's

relatively fast. I say "relatively" as it's relative to what you're doing with it.

If you're hosting a pretty plain Web site with mostly static content, Apache

is a fireball. If you throw tons of CGI scripts at it, while making database

calls at the same time, you're going to slow it down. Though much of the

slowdown will come from your scripts themselves, and not from Apache.

Apache evolved out of the NCSA https project to its current status as one of

the fastest, most efficient, and most functional web servers in existence

today.

Apache has been shown to be substantially faster, more stable, and more

feature-full than many other web servers. Although certain commercial

48

Page 49: Foss Lab Manual

servers have claimed to surpass Apache's speed (it has not been

demonstrated that any of these "benchmarks" are a good way of

measuring WWW server speed at any rate). The developers of Apache feel

that it is better to have a mostly-fast free server than an extremely fast server

that costs thousands of dollars. Apache is run on sites that get millions of

hits per day, and they have experienced no performance difficulties. Apache

is run on over 10 million Internet servers (as of May 2002). It has been

tested thoroughly by both developers and users. The Apache Group

maintains rigorous standards before releasing new versions of their server,

and their server runs without problems on over one half of all WWW servers

available on the Internet. When bugs do show up, they release patches and

new versions as soon as they are available.

Installation Options

I’ll cover three methods of installing Apache under Linux. The three

methods are:

·Binary installation

·Using an RPM (Red Hat Package Manager) – recommended for

people running Red Hat Linux

·Building from source

Apache Installation Guide

We recommend using the RPM installation method. This is the easiest way

to install Apache for people that are new to Linux.

49

Page 50: Foss Lab Manual

Download the Software

You can download Apache from the Apache Software Foundation web site

located at

http://www.apache.org, in source and binary forms. While your

downloading Apache, you may

want to browse over the documentation.

What you need

To install Apache, you will need the following things:

1. A computer running Linux

2. Root access on this computer

3. For binary and source installations, the tar and gunzip Unix utilities

Binary Installation

A binary is pre-configured, which means someone else has gone to the

trouble of configuring and building the software for you. There are,

however, a few things you should keep in mind:

1. Binaries are compiled for a particular operating system. In other words,

you must use a binary built specifically for FreeBSD on your FreeBSD

machine and a Linux binary on your Linux machine. You need to be sure to

50

Page 51: Foss Lab Manual

grab the correct binary; if you don't see a binary for your particular operating

system, you must choose a different method of installation.

2. Apache binaries are usually a version or two behind the current source

distribution. This means you don't reap the benefits of the latest bug fixes

and feature enhancements.

3. Because binaries are pre-configured, you don't have much opportunity to

alter the way the software works. If you're a newcomer, you may not care

about this loss of flexibility. Fortunately most Apache binaries include a full

source distribution, providing you with the best of both worlds -- play now,

learn later.

Now let's install a binary. Point your browser at

http://www.apache.org/dist/httpd/binaries/

and download the binary for your operating system (in our case, Linux).

You'll most likely be presented with a directory containing multiple versions

of Apache in various compressed forms. For the purposes of this guide, I'll

assume you've downloaded the gzip'd form of the latest 2.0.x Apache binary

(currently that's httpd-2.0.35-i686-pc-linux-rh72.tar.gz). If there is a

README associated with the file you're downloading, you may want to

review it for any interesting installation tidbits or possible bugs.

If you can't find a binary for your operating system, choose either the RPM

Installation (if you are running Red Hat Linux) or Build from Source

method. Now let's uncompress the archive using the handy combination of

51

Page 52: Foss Lab Manual

gunzip and tar. You should replace the "httpd-2.0.35-i686-pc-linux-

rh72.tar.gz" text below with the name of the

gzip'd file you downloaded.

gunzip < httpd-2.0.35-i686-pc-linux-rh72.tar.gz | tar xvf –

Some of you may be lucky enough to have a version of tar that is capable of

taking care of both tasks.

tar xvzf httpd-2.0.35-i686-pc-linux-rh72.tar.gz

Either way, you should end up with an httpd-2.0.x directory, with x being

the particular subversion of Apache you downloaded. Move into the newly

created directory.

cd httpd-2.0.x

As of Apache 1.3.11, binary distributions contain an install script called

install.bindist.sh. If your binary does not seem to contain such an install

script, take a look at the README.bindist and/or INSTALL.bindist

documents for further information; if these documents don't outline a simple

installation method, you'll probably want to use one of the other methods I

cover in this guide.

If you've not already done so, you'll need to become root. You can become

root by typing su, then the root password. Then go ahead and run the install

script.

./install.bindist.sh

52

Page 53: Foss Lab Manual

This command should install the various bits of the Apache distribution into

the appropriate locations; the default is usually to install everything under

/usr/local/apache (confirm this by consulting your README.bindist and/or

INSTALL.bindist documents). That's all there is to it on installing binaries.

RPM Installation

Those of you running Red Hat Linux may want to take advantage of

Red Hat's RPM ("RedHat Package Manager") system. Almost identical to a

binary, an RPM is further customized to play nicely with other RPMs and

provide a consistent interface to installing, updating, and removing binaries.

For Linux newcomers or when installing a small standard component, RPMs

are simple and reliable. Bear in mind that an Apache RPM may already be

installed on your system depending on how Linux was originally installed

on your computer. To find out, at the shell prompt, type:

rpm -qa | grep apache

If you see something like apache-1.3.9xxx, an Apache RPM has already

been installed. You can also type that command typing httpd instead of

apache to see if it’s installed. If you don't have an Apache RPM, you must

obtain one. Red Hat 7.3 ships apache-1.3.23- 11.src.rpm in the

RedHat/RPMS directory on the installation CD. Or, point your browser at

ftp://ftp.redhat.com/pub/redhat/redhat-7.3-en/os/i386/RedHat/RPMS and

download it. If you've not already done so, you'll need to become root.

Navigate to the same directory as the .rpm file you obtained, and then type

the following command, substituting the name of the .rpm you're using for

example: apache-1.3.23-11.src.rpm.

53

Page 54: Foss Lab Manual

rpm -ivh apache-1.3.23-11.src.rpm

RPM should grind away, displaying its progress with a primitive #######

progress bar. Barring any errors, you're done.

Build from Source

Building Apache from source may seem like a daunting task to newcomers,

but the Apache developers have done a wonderful job of making the task

about as simple as could be. Just three more commands than a binary

installation and you skip the arduous task of figuring out which binary is the

right one for your particular operating system. Point your browser at

http://www.apache.org/dist/httpd/ and download the gzip'd form of the

current version of Apache (2.0.36 at the time of this writing). Now let's

uncompress that archive using gunzip and tar. You should replace the httpd-

2.0.36.tar.gz below with the name of the gzip'd file you downloaded.

gunzip < httpd-2.0.36.tar.gz | tar xvf –

You should end up with an httpd-2.0.x directory, x being the particular sub-

version of Apache you downloaded. Move into the newly created directory.

cd httpd-2.0.x

Now we'll use the the configure and make commands to configure, make,

and install Apache. If you've not already done so, now would be the time to

become root.

54

Page 55: Foss Lab Manual

./configure

Your screen should look something like:

# ./configure

checking for chosen layout... Apache

checking for working mkdir -p... yes

checking build system type... i686-pc-linux-gnu

checking host system type... i686-pc-linux-gnu

checking target system type... i686-pc-linux-gnu

Configuring Apache Portable Runtime library ...

...

config.status: executing default commands

Unless errors were reported (not warnings), your Apache installation is now

configured and we can move on. This is where things get a bit ugly.

Make'ing Apache produces screenfulls of output.

Make

Your screen should look something like:

# make

Making all in srclib

make[1]: Entering directory `/home/ryan/dl/apache_guide/httpd-

2.0.36/srclib'

Making all in apr

make[2]: Entering directory `/home/ryan/dl/apache_guide/httpd-

2.0.36/srclib/apr'

...

55

Page 56: Foss Lab Manual

make[1]: Leaving directory `/home/ryan/dl/apache_guide/httpd-2.0.36'#

Finally, you're ready to install your Apache build.

# make install

Now Apache is installed.

Starting Apache

Let's take your new Apache installation out for a spin.

If you installed Apache using a binary or from scratch, as root, type:

/usr/local/apache/bin/apachectl start

If you used an RPM, as root, type:

/sbin/service httpd start

Point your browser at your brand new Web server, http://localhost/. If

everything worked you should see the default home page.

Customize

Apache uses some rather easy to understand text files for configuration. On

a Red Hat system,you'll find them in /etc/httpd/conf. Quite a few Linux

distributions place them in this same place, but if you can't find such a

directory, do a search for "httpd.conf". Once you find these, you've

found the main config files. If you're new to Linux, and need help finding

this file, here's how you can find it.

56

Page 57: Foss Lab Manual

1.Login as root

2.Type: cd /

3.Type: find -name httpd.conf

Now you should see where the file is located. When you move into the

directory containing

httpd.conf, you should see these three files:

·httpd.conf – This has the settings for the overall configuration for the

server.

·access.conf – This file contains all the security settings for Apache.

·srm.conf – This file contains the MIME definitions and default document

names for files on the server.

Restarting Apache

Whevever you make changes to the server configuration files, such as

httpd.conf, they won't take effect until the server is restarted. In Linux,

Apache can be restarted depending on how you installed it. If you installed

Apache using a binary or from scratch, as root, type:

/usr/local/apache/bin/apachectl start

If you used an RPM, as root, type:

/sbin/service httpd start

After being restarted the changes will have taken effect.

57

Page 58: Foss Lab Manual

PHP PHP & &

MySQL MySQL ConnectivityConnectivity

58

Page 59: Foss Lab Manual

CONNECT PHP WITH MYSQL

[linuxpert@localhost ~]$ su

Password: admin123

[root@localhost linuxpert]# cd /var/www/html

[root@localhost html]# gedit

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>

59

Page 60: Foss Lab Manual

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";

}

?>

TYPE THE FOLLOWING IN THE BROWSER

http://localhost/form.html

60

Page 61: Foss Lab Manual

when u press the submit button

61

Page 62: Foss Lab Manual

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

62

Page 63: Foss Lab Manual

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 |

63

Page 64: Foss Lab Manual

| 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

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>

64

Page 65: Foss Lab Manual

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

65

Page 66: Foss Lab Manual

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";

?>

66

Page 67: Foss Lab Manual

OUTPUTOUTPUT

67

Page 68: Foss Lab Manual

PYTHON PYTHON

68

Page 69: Foss Lab Manual

PYTHON PROGRAMS

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 pythonpython: /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

69

Page 70: Foss Lab Manual

3. Execute Python Program

You can either execute using “python helloworld.py” or “./helloworld.py”.

$ python helloworld.pyHello World!

( or )

$ chmod u+x helloworld.py

$ ./helloworld.pyHello World!

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 python programming

#Sample python programx=5;y=5;

print ("x:",x);print("y:",y);

z=x+y;print("z:",z);

70

Page 71: Foss Lab Manual

5. String Concatenation in python programming

#String concatenationworda='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 ("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 characterprint(str[-6]);#print character from last 6th positionprint(str[:-2]);# Everything except the last two characters

6. Write a python program to perform function in Lists

#Python Lists#!/usr/bin/pythonprint("\t \t \t Python Lists");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]);

71

Page 72: Foss Lab Manual

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 listprint("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 listdel 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 );

72

Page 73: Foss Lab Manual

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

#Python Dictionarytinydict = {'name': 'john','code':6734, 'dept': 'sales'}print ("Python Dictionary:" );print ("complete dictionary",tinydict ); print ("Key :",tinydict.keys()); # Prints all the keysprint ("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 lista=[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'

73

Page 74: Foss Lab Manual

11. For Statement in Python

>>> # Measure some strings:... a = ['cat', 'window', 'defenestrate']>>> for x in a:... print x, len(x)

cat 3window 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 Mary1 had2 a3 little4 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'..

74

Page 75: Foss Lab Manual

OUTPUT:

2 is a prime number3 is a prime number4 equals 2 * 25 is a prime number6 equals 2 * 37 is a prime number8 equals 2 * 49 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

15. Set operations in Python

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']>>> fruit = set(basket) # create a set without duplicates>>> fruitset(['orange', 'pear', 'apple', 'banana'])>>> 'orange' in fruit # fast membership testingTrue>>> 'crabgrass' in fruitFalse>>> # Demonstrate set operations on unique letters from two words

75

Page 76: Foss Lab Manual

...>>> a = set('abracadabra')>>> b = set('alacazam')>>> a # unique letters in aset(['a', 'r', 'b', 'c', 'd'])>>> a - b # letters in a but not in bset(['r', 'd', 'b'])>>> a | b # letters in either a or bset(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])>>> a & b # letters in both a and bset(['a', 'c'])>>> a ^ b # letters in a or b but not bothset(['r', 'd', 'b', 'm', 'z', 'l'])

16. Modules And Error Handling In Python

import systry: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

17.Finally class in Python

>>> def divide(x, y):... try:... result = x / y... except ZeroDivisionError:

76

Page 77: Foss Lab Manual

... print "division by zero!"

... else:

... print "result is", result

... finally:

... print "executing finally clause"

...>>> divide(2, 1)result is 2executing finally clause>>> divide(2, 0)division by zero!executing finally clause>>> divide("2", "1")executing finally clauseTraceback (most recent call last):File "<stdin>", line 1, in ?File "<stdin>", line 3, in divideTypeError: 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)

77

Page 78: Foss Lab Manual

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

78

Page 79: Foss Lab Manual

PERL PERL

79

Page 80: Foss Lab Manual

PERL PROGRAMS

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

thamarai

thamarai

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

80

Page 81: Foss Lab Manual

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

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 ~]$ perl hash.pl red

81

Page 82: Foss Lab Manual

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;

82

Page 83: Foss Lab Manual

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

foreach $key (@keys)

{

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

83

Page 84: Foss Lab Manual

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

84

Page 85: Foss Lab Manual

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 ~]$ perl foreach.pl

cow

buffalo

camel

123

100

243

300

85

Page 86: Foss Lab Manual

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)

86

Page 87: Foss Lab Manual

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','thamarai');

$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:

[linuxpert@localhost ~]$ perl arrayvariable.pl

ARRAY(0x8358a70)

hello 122 200 thamarai

122

87

Page 88: Foss Lab Manual

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

}

88

Page 89: Foss Lab Manual

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

89

Page 90: Foss Lab Manual

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 first element in array and the

remaining element will be stored in $max

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

{

90

Page 91: Foss Lab Manual

$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:

91

Page 92: Foss Lab Manual

[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";

}

92

Page 93: Foss Lab Manual

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

93

Page 94: Foss Lab Manual

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";

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

94

Page 95: Foss Lab Manual

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

95

Page 96: Foss Lab Manual

{

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";

96

Page 97: Foss Lab Manual

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");

while(<DATA>)

{

print "$_";

}

97

Page 98: Foss Lab Manual

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) = @_;

98

Page 99: Foss Lab Manual

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 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!";

99

Page 100: Foss Lab Manual

@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.";

print "\n Now open the new file";

print "\n Move function";

100

Page 101: Foss Lab Manual

$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.";

}

101

Page 102: Foss Lab Manual

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 |

102

Page 103: Foss Lab Manual

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

3 rows in set (0.25 sec)

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

103

Page 104: Foss Lab Manual

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();

104

Page 105: Foss Lab Manual

$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)

{

105

Page 106: Foss Lab Manual

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;

106

Page 107: Foss Lab Manual

$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)

107

Page 108: Foss Lab Manual

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

108

Page 109: Foss Lab Manual

U will get the output as

109

Page 110: Foss Lab Manual

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

110

Page 111: Foss Lab Manual

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

111

Page 112: Foss Lab Manual

we get the screen as

112

Page 113: Foss Lab Manual

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)

NS2 NS2 SIMULATORSIMULATOR

113

Page 114: Foss Lab Manual

INSTALLATIONINSTALLATION

INTRODUCTION TO NETWORK SIMULATOR NS-2

NETWORK SIMULATOR-2 is designed to run from on most UNIX

based operating systems.Ns is a discrete event simulator targeted at

networking research. Ns provides substantial support for simulation of TCP,

routing, and multicast protocols over wired and wireless (local and satellite)

networks.

Download a copy of ns-allinone-2.34.tar.gz. Then from the command

prompt there, execute the following:

114

Page 115: Foss Lab Manual

tar -xzf ns-allinone-2.34.tar.gz

cd ns-allinone-2.34

./install

(If this fails, try the Distribution Specific instructions)

After a long wait and a whole lot of text, you should see the installation

finish up with text like the following:

Nam has been installed successfully.

Ns-allinone package has been installed successfully.

Here are the installation places:

tcl8.4.11: /home/pcraven/ns-allinone-2.29/{bin,include,lib}

tk8.4.11: /home/pcraven/ns-allinone-2.29/{bin,include,lib}

otcl: /home/pcraven/ns-allinone-2.29/otcl-1.11

tclcl: /home/pcraven/ns-allinone-2.29/tclcl-1.17

ns: /home/pcraven/ns-allinone-2.29/ns-2.29/ns

nam: /home/pcraven/ns-allinone-2.29/nam-1.11/nam

xgraph: /home/pcraven/ns-allinone-2.29/xgraph-12.1

gt-itm: /home/pcraven/ns-allinone-2.29/itm, edriver, sgb2alt, sgb2ns,

sgb2comns, sgb2hierns

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

Please put /home/myusername/ns-allinone-

2.29/bin:/home/myusername/ns-allinone-

2.29/tcl8.4.11/unix:/home/myusername/ns-allinone-2.29/tk8.4.11/unix

115

Page 116: Foss Lab Manual

into your PATH environment; so that you'll be able to run

itm/tclsh/wish/xgraph.

IMPORTANT NOTICES:

(1) You MUST put /home/myusername/ns-allinone-2.29/otcl-1.11,

/home/myusername/ns-allinone-2.29/lib,

into your LD_LIBRARY_PATH environment variable.

If it complains about X libraries, add path to your X libraries

into LD_LIBRARY_PATH.

If you are using csh, you can set it like:

setenv LD_LIBRARY_PATH <paths>

If you are using sh, you can set it like:

export LD_LIBRARY_PATH=<paths>

(2) You MUST put /home/myusername/ns-allinone-2.29/tcl8.4.11/library

into your TCL_LIBRARY environmental

variable. Otherwise ns/nam will complain during startup.

(3) [OPTIONAL] To save disk space, you can now delete directories

tcl8.4.11

and tk8.4.11. They are now installed under /home/myusername/ns-

allinone-2.29/{bin,include,lib}

After these steps, you can now run the ns validation suite with

cd ns-2.29; ./validate

116

Page 117: Foss Lab Manual

For trouble shooting, please first read ns problems page

http://www.isi.edu/nsnam/ns/ns-problems.html. Also search the ns

mailing list archive

for related posts.

At this point, you should follow the advice here and update your

environment variables. You should also add ns-allinone-2.29/bin to you

path. This has links to all the executables created by NS-2. Since the Tcl

scripts may call these executables (like nam or xgraph), it is a good idea to

have them in the path.

You can test the installation by doing the following:

cd ns-2.29

./validate

Note that this validation takes a really long time. If it starts out ok, you

probably have a good installation.

At this point, you can see Getting Started with NS-2 .

117