Foss Lab Manual
Foss Lab Manual
P INstItute Of techNOlOGy
cOImbatOre-641048
LAB MANUAL
Prepared Verified
By By
2 MySQL Installation
3 Apache Installation
5 Python Programming
7 NS2 Installation
2
LINUX
INSTALLATION
3
INTRODUCTION TO OPEN SOURCE SOFTWARE
Popular distributions:
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
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
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.
6
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
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
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
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.
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
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
11
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 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
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.
PulseAudio IcedTea
system-config-firewall NetworkManager
Codeina Better laptop support
13
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.
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.
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
Features of Fedora 13 include:
16
Basic Installation Steps:
2. Skip the media test by pressing the tab and return keys on the
keyboard.
17
18
3. Click the "Next" button on the welcome screen.
19
4. Select the appropriate language, then click the "Next" button.
20
5. Select the appropriate keyboard layout, then click the "Next" button.
21
6. When prompted, click the "Re-initialize drive" button.
22
7. When prompted, click the "Re-initialize" button.
23
8. Enter a fully qualified hostname, then click the "Next" button.
24
25
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
12. The current partitioning layout is presented. If the OS is to be used for
27
disk"button.
28
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
15. Selecting the repositories will require you to enter your network
30
31
16. Once the repositories are selected, select the "Customize Now" option
17. Select the appropriate package groups and optional packages for your
32
33
18. Wait while the installation completes.
When the machine has restarted, click the "Forward" button on the
welcome screen.
34
35
20. Accept the license agreement by clicking the "Forward" button.
36
21. Enter login user details, then click the "Forward" button.
22. Set the appropriate date-time information, then click the "Forward"
button.
37
23. Decide if you want to send a hardware profile to the Fedora project,
38
39
24. Click the username you defined previously.
40
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
42
MySQL
INSTALLATIO
N
MYSQL INSTALLATION
……………………………………………………
43
[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
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)
44
if you get a "no acceptable C compiler found in $PATH" Error
Install a c compiler, example: gcc
Using MySQL
45
----------------------------------------
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
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
APACHE
INSTALLATIO
N
47
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
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
49
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.
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:
50
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.
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
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.
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
./install.bindist.sh
52
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:
53
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.
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.
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
./configure
# ./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
make[1]: Leaving directory `/home/ryan/dl/apache_guide/httpd-2.0.36'#
# 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
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
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
/usr/local/apache/bin/apachectl start
57
PHP
&
MySQL
Connectivity
58
CONNECT PHP WITH MYSQL
[linuxpert@localhost ~]$ su
Password: admin123
<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
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";
}
?>
http://localhost/form.html
60
when u press the submit button
61
now go to terminal
62
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| student |
| test |
+--------------------+
4 rows in set (0.11 sec)
mysql> connect
Connection id: 29
Current database: student
63
| courses |
| students |
+-------------------+
3 rows in set (0.00 sec)
64
</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> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
65
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
OUTPUT
67
PYTHON
68
PYTHON PROGRAMS
$ vim helloworld.py
#!/usr/bin/python
$ 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
69
3. Execute Python Program
$ python helloworld.py
Hello World!
( or )
$ ./helloworld.py
Hello World!
print ("x:",x);
print("y:",y);
z=x+y;
print("z:",z);
70
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 ("first character is",str[0]);
print ("print character from 2rd to 6th :", str[2:7] );
print ("Prints string starting from 3rd character:",str[2:]);
print ("Prints string two times",str * 2);
print ("Prints concatenated string :",str + "TEST" );
print(str[-1]); #print last character
print(str[-6]);#print character from last 6th position
print(str[:-2]);# Everything except the last two characters
#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 first element of the list : ",list[0]);
71
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 );
#Python Tuples
72
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
#!/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]);
73
11. For Statement in Python
cat 3
window 6
74
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
75
...
>>> 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'])
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
76
... print "division by zero!"
... else:
... print "result is", result
... finally:
... print "executing finally clause"
...
>>> divide(2, 1)
result is 2
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'
77
19. Module Program in Python (Fibonacci Series)
Step 2:
>>> import fibo
Step 3:
>>> fibo.fib(1000)
78
PERL
79
PERL PROGRAMS
1. Sample PERL
output:
[linuxpert@localhost ~]$ perl first.pl
thamarai
thamarai
#!/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
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:
81
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
#!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
@values=values %color; # it ill store the array values
foreach $key (@keys)
{
print "$color{$key}\n";
}
delete $color{'apple'}; # to remove specific key
#!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
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
#!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
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
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
#!usr/bin/perl
$a=100;
$b=\$a;
print "$b\n";
output:
[linuxpert@localhost ~]$ perl reference.pl
SCALAR(0x9506a68)
86
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
#!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:
87
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
#!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
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
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:
#!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
$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
#!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
[linuxpert@localhost ~]$ perl symbolicref.pl
the product is 600
92
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";
#!/usr/bin/perl
# Define an array
@coins = ("aaa","bbb","ccc");
#Array can be represent using qw format
#Display all Elements in Array
93
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
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";
Example 2:
sub maximum
95
{
if ($_[0] > $_[1])
{
$_[0];
}
else
{
$_[1];
}
}
sub get_list
{
return 5..10;
}
@list = &get_list;
print "@list";
96
18. Program to Open the File
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
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");
98
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
@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);
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
100
$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
APPLICATION USING PERL
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
102
+--------------------+
3 rows in set (0.25 sec)
now the table is empty . To create the table we use the following procedure
103
1.2 The following packages should be used to connect PERL with Mysql
(use new terminal)
#!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
$dbh->disconnect;
#!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
die("error:$!");
}
$sth=$dbh->prepare("insert into students values(100,'thamarai')"); # create
the table
$sth->execute();
$dbh->disconnect;
#!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
$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;
107
CGI PROGRAMMING
EXAMPLE -1
108
U will get the output as
109
EXAMPLE -2
in terminal
[linuxpert@localhost ~]$ su
Password:
[root@localhost linuxpert]# cd /var/www/html
[root@localhost html]# gedit
110
http://localhost/form.html
#!/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;
}
http://localhost/form.html
111
we get the screen as
112
now check the database as
| 200 | selvi |
| NULL | abcd |
| 71 | thamaraiselvi |
+--------+---------------+
4 rows in set (0.00 sec)
NS2
SIMULATOR
113
INSTALLATION
114
tar -xzf ns-allinone-2.34.tar.gz
cd ns-allinone-2.34
./install
After a long wait and a whole lot of text, you should see the installation
finish up with text like the following:
----------------------------------------------------------------------------------
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
into your PATH environment; so that you'll be able to run
itm/tclsh/wish/xgraph.
IMPORTANT NOTICES:
(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
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.
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.
117