Vous êtes sur la page 1sur 83

Ex.

No: 01 Kernel Configuration, Compilation and Installation Date Aim: Download / access the latest kernel source code from kernel.org,compile the kernel and install it in the local system. Try to view the source code of the kernel. Procedure: Linux Kernel 3.0/3.01 configuration, compilation and installation in Fedora 14 or 15 : You can also follow the same steps to compile and install Linux Kernel 3.0.1 in your system. Dependencies: To compile Linux Kernel the following are required to be installed. gcc latest version, ncurses development package andsystem packages should be up-to date To install the dependencies run the following commands in terminal and type the password for the user, when prompted. For gcc $ sudo yum install gcc :

For ncurses development package $ sudo yum install ncurses-devel After installing the above packages then update your system by running the following command $ sudo yum update Now download the Linux Kernel 3.0 from kernel.org or by using the below command. If your trying with Linux Kernel 3.0.1 then just replace the name linux-3.0 with linux-3.0.1 in all commands below. $ wget http://www.kernel.org/pub/linux/kernel/v3.0/linux-3.0.tar.bz2 Once the download complete move to the directory where you have downloaded the kernel package linux-3.0.tar.bz2. Now extract the tar file to the location /usr/src/. To move to the directory, for example if the downloaded package is in your Downloads directory. Use the below command. $ cd Downloads/ To extract the tar file run the following command. Type the password for the user when prompted. $ sudo tar -xvf linux-3.0.tar.bz2 -C /usr/src/

Now move to the directory where the extracted file is, or copy and paste the below command in terminal. $ cd /usr/src/linux-3.0/ Now you can configure, compile and install Linux Kernel 3.0 in your system. Run the commands one by one and type the password for the user, when prompted. To Configure $ sudo make menuconfig The above command is used to configure the Linux kernel. Once you execute the command, you will get a pop up window with the list of menus and you can select the items for the new configuration. If your unfamiliar with the configuration just check for the file systems menu and check whether ext4 is chosen or not, if not select it and save the configuration. Check the screen shot below for menuconfig. If you like to have your existing configuration then run the below command. $ sudo make oldconfig There are other alternate configuration commands are available and you can find them in README file under linux-3.0 directory. To Compile $ sudo make The above command is used to compile the Linux Kernel. It will take some time to complete it, approximately 40 min to 50 min it depends on your system configuration. To Install $ sudo make modules_install install The above command will install the Linux Kernel 3.0 into your system. It will create some files under /boot/ directory and it will automatically make a entry in your grub.conf. The files are, System.map-3.0.0 vmlinuz-3.0.0 initramfs-3.0.0.img To make it default just modify the grub.conf or menu.lst under /boot/grub/ directory. Open the file using below command. $ sudo gedit /boot/grub/menu.lst Just check the entry for fedora 3.0.0, if it is in first place then change default=0, if not check for the exact position and give the corresponding value in default. Restart your system by default it will boot in fedora 3.0.0, you can able to see while booting if not press any key to change it. To check after booting open a terminal and type uname -r. Check the screen shot below.

Ex.No: 02 Virtualisation Environment Date :

Aim: Virtualisation environment (e.g., xen, kqemu or lguest) to test an applications, new kernels and isolate applications. It could also be used to expose students to other alternate OSs like *BSD Procedure: What is Virtualisation? Virtualisation, in computing, is the creation of a virtual (rather than actual) version of something, such as a hardware platform, operating system, a storage device or network resources. So what we are going to do is to install another operating system say 'Ubuntu' within our host operating system 'Fedora'. Now the 'Ubuntu' contained within the virtual machine is called as the guest Operating System. The software that we are going to use to perform this is the open source software called 'Qemu' Installing Ubuntu within Fedora using QEMU : 1) The first step involved here is to download the QEMU source code (if it is not already present). You can perform this download by clicking the following link Download QEMU Source code 2) Next task is to build the emulator from the source code. Go the folder where you have downloaded the source code in the terminal and enter the following two commands: $ tar -zxvf qemu-0.14.0.tar.gz $ cd qemu-0.14.0 3) Next we are going to configure the qemu script such that it is built for i386 architecture. However it supports various other architectures like ARM, PPC, SPARC etc. Enter the following command: $ ./configure --target-list=i386-softmmu (Before doing this make sure you have installed Header files and libraries for zlib development. If you haven't then go to 'Add/Remove software' app in Fedora and do it and then configure your script) 4) Once you are done with configuring now you have to install it. For doing so, you must login as root in your terminal using the 'su' command. After that use the 'make' command to install it. $ su Password: (This is not a command, but will come when you enter su) # make install 5) Now you have installed qemu. Next step is to create the virtual machine. The first step in that is to create a Virtual Hard disk image for that. For our Ubuntu OS let us a create an Hard disk of size 10 GB. To create that go to a folder where you want to create the hard disk image and enter the following: $ qemu-img create ubuntu.img 10G 3

$ ls -lh ubuntu.img (To check) 6)So you have created the hard disk. What next??? Yes..To install Ubuntu into it. You have to download ubuntu and place its .iso image in the current working directory. Then execute the following commands qemu -hda ubuntu.img --boot d -cdrom ./ubuntu-10.10-desktop-i386.iso -m 512 In the above command, '-hda' option specifies the disk image file, '-cdrom' is the CD-ROM or iso image to be used and '-m' option specifies the memory to be allocated for the guest OS. In this case it is 512 MB of RAM. Now our Virtual machine is ready. Just got to install ubuntu in it. The screenshot is given below:

Ex. No: 03 Compiling from source Date Aim: Compiling from source: learn about the various build systems used like the auto* family, cmake, ant etc. instead of just running the commands. This could involve the full process like fetching from a cvs and also include autoconf, automake etc. Procedure: :

How to download, compile, and install CMake on Linux


CMake is a cross-platform, open-source build system. CMake is a family of tools designed to build, test and package software. Here are the simple steps to download, configure, compile, and install CMake on a Linux machine. I have tested these instructions on Debian/Ubuntu Linux distributions but they should work on all Linux machines where compilers and make utilities are installed. Please take a look at configuring Ubuntu Linux after installation to configure your Debian/Ubuntu Linux box for the required tools. Please make sure you check the downloaded file's integrity before unzipping it. '#' (w/o quotes) in front of commands below means you have to run the command as root user (or use sudo instead if your system supports that).

Download:
$ wget http://www.cmake.org/files/v2.8/cmake-2.8.3.tar.gz

Extration of cmake source code from downloaded file:


$ tar xzf cmake-2.8.3.tar.gz $ cd cmake-2.8.3

Configuration:
If you want to see the available conifuration options, run command below.
$ ./configure --help

In order to configure cmake before installation, run command below.


$ ./configure --prefix=/opt/cmake

We basically instructed the install script to install CMake in /opt/cmake.

Compilation:
$ make

Installation:
# make install

Verification:
After installation without any errors you can verify the installation by running the command below:
$ /opt/cmake/bin/cmake -version

The output should look something like below (depending upon cmake version you are installing).
cmake version 2.8.3

Installing ant in Linux


Step 1: Download ant from http://ant.apache.org/bindownload.cgi. I have downloaded apache-ant-1.7.1bin.zip for this tutorial. Step 2: Login to your Linux box and create a directory "ant" under /usr/local. [root@RoseIndiaLinux local]# mkdir ant [root@RoseIndiaLinux local]# cd ant [root@RoseIndiaLinux ant]# pwd /usr/local/ant [root@RoseIndiaLinux ant]# Step 3: Copy apache-ant-1.7.1-bin.zip onto your Linux box in /usr/local/ant directory. Step 4: Extract the zip file apache-ant-1.7.1-bin.zip) using unzip command. [root@RoseIndiaLinux ant]# unzip apache-ant-1.7.1-bin.zip Above command will extract the content of the zip file and will create a new directory apacheant-1.7.1 Step 5: Set path in the .bash_profile 6

Open the file /root/.bash_profile and add the following codes: export ANT_HOME=/usr/local/ant/apache-ant-1.7.1 export JAVA_HOME=/opt/java/jdk1.6.0_06 export PATH=${PATH}:${ANT_HOME}/bin Step 6: Logout and login again to your Linux box. Now ant available on your box.

Introduction to Autoconf
Autoconf is an extensible package of M4 macros that produce shell scripts to automatically configure software source code packages. These scripts can adapt the packages to many kinds of UNIX-like systems without manual user intervention. Autoconf creates a configuration script for a package from a template file that lists the operating system features that the package can use, in the form of M4 macro calls. Producing configuration scripts using Autoconf requires GNU M4. You should install GNU M4 (at least version 1.4.6, although 1.4.13 or later is recommended) before configuring Autoconf, so that Autoconf's configure script can find it. The configuration scripts produced by Autoconf are self-contained, so their users do not need to have Autoconf (or GNU M4). Autoconf is a tool for producing shell scripts that automatically configure software source code packages to adapt to many kinds of Posix-like systems. The configuration scripts produced by Autoconf are independent of Autoconf when they are run, so their users do not need to have Autoconf. The configuration scripts produced by Autoconf require no manual user intervention when run; they do not normally even need an argument specifying the system type. Instead, they individually test for the presence of each feature that the software package they are for might need. (Before each check, they print a one-line message stating what they are checking for, so the user doesn't get too bored while waiting for the script to finish.) As a result, they deal well with systems that are hybrids or customized from the more common Posix variants. There is no need to maintain files that list the features supported by each release of each variant of Posix. For each software package that Autoconf is used with, it creates a configuration script from a template file that lists the system features that the package needs or can use. After the shell code to recognize and respond to a system feature has been written, Autoconf allows it to be shared by many software packages that can use (or need) that feature. If it later turns out that the shell code needs adjustment for some reason, it needs to be changed in only one place; all of the configuration scripts can be regenerated automatically to take advantage of the updated code. Those who do not understand Autoconf are condemned to reinvent it, poorly. The primary goal of Autoconf is making the user's life easier; making the maintainer's life easier is only a secondary goal. Put another way, the primary goal is not to make the generation of configure automatic for package maintainers (although patches along that front are welcome, since package maintainers form the user base of Autoconf); rather, the goal is to make configure painless, portable, and predictable for the end user of each autoconfiscated package. And to this degree, 7

Autoconf is highly successful at its goal most complaints to the Autoconf list are about difficulties in writing Autoconf input, and not in the behavior of the resulting configure. Even packages that don't use Autoconf will generally provide a configure script, and the most common complaint about these alternative home-grown scripts is that they fail to meet one or more of the GNU Coding Standars (see Configuration) that users have come to expect from Autoconfgenerated configure scripts. The Metaconfig package is similar in purpose to Autoconf, but the scripts it produces require manual user intervention, which is quite inconvenient when configuring large source trees. Unlike Metaconfig scripts, Autoconf scripts can support cross-compiling, if some care is taken in writing them. Autoconf does not solve all problems related to making portable software packagesfor a more complete solution, it should be used in concert with other GNU build tools like Automake and Libtool. These other tools take on jobs like the creation of a portable, recursive makefile with all of the standard targets, linking of shared libraries, and so on. See The GNU Build System, for more information. Autoconf imposes some restrictions on the names of macros used with #if in C programs (see Preprocessor Symbol Index). Autoconf's development tree is accessible via git; see the Autoconf Summary for details, or view the actual repository. Anonymous CVS access is also available, see README for more details. Patches relative to the current git version can be sent for review to the Autoconf Patches mailing list, with discussion on prior patches archived; and all commits are posted in the read-only Autoconf Commit mailing list, which is also archived.

Downloading Autoconf
GNU Autoconf releases can be found on http://ftp.gnu.org/gnu/autoconf/ [via http] and ftp://ftp.gnu.org/gnu/autoconf/ [via FTP]. It can also be found on one of our FTP mirrors. You can also order a CD-ROM from the FSF or use other methods to obtain a copy. Third party macros can be downloaded from the Autoconf Macro Archive. Alpha/beta releases of Autoconf can be found in ftp://alpha.gnu.org/pub/gnu/autoconf/, and the latest in-development sources for Autoconf can always be fetched through git, using either of:
git clone git://git.sv.gnu.org/autoconf git clone http://git.sv.gnu.org/r/autoconf.git

You can also view the git tree on the web. Alternatively, there is a read-only CVS mirror here:
cvs -d :pserver:anonymous@pserver.git.sv.gnu.org:/autoconf.git \ co -d autoconf HEAD

DO NOT use Autoconf sources from these locations for production use. 8

Snapshot tarballs of development sources for Autoconf can be found at http://meyering.net/ac/autoconf-ss.tar.gz, signed. DO NOT use Autoconf sources from these locations for production use. #rpm q webattery Webattery-1.2.6.fc14.i686 #webattery No Battery #which webattery /usr/bin/webattery Webattery sample for Compiling from source 1. Download webattery-<version>-src.rpm to /home/fosslab folder 2. cd /home/fosslab 3. rpm -ivh webattery-<version>-src.rpm 4. The above command creates a directory rpmbuild under the home folder /home/fosslab ex: /home/fosslab/rpmbuild 5. cd /home/fosslab/rpmbuild/SOURCES/ 6. Extract the source file using the command $tar zxvf webattery-1.2.tar.gz 7. cd webattery-1.2/ 8. ./configure (checks for the necessary tools/libraries for the build environment and creates the Makefile) 9. make (compiles all the source files and creates the executable binaries) 10. make install 11. which webattery (prints the location of the binary executable)

Ex. No: 04 Introduction to packet management system Date Aim: Introduction to packet management system : Given a set of RPM or DEB, how to build and maintain, serve packages over http or ftp. and also how do you configure client systems to access the package repository Procedure: The RPM Package Manager (RPM) is an open packaging system, which runs on Fedora as well as other Linux and UNIX systems. Red Hat, Inc. and the Fedora Project encourage other vendors to use RPM for their own products. RPM is distributed under the terms of the GPL (GNU General Public License). The RPM Package Manager only works with packages built to work with the RPM format. RPM is itself provided as a pre-installed rpm package. For the end user, RPM makes system updates easy. Installing, uninstalling and upgrading RPM packages can be accomplished with short commands. RPM maintains a database of installed packages and their files, so you can invoke powerful queries and verifications on your system. The RPM package format has been improved for Fedora 14. <What is RPM> RPM stands for Red Hat Package Manager. However, these days RPM isn't only Red Hat specific because many other Linux distros use RPM for managing their software. For example, both Mandriva and SuSE use RPM for software management. With RPM, you can install, upgrade and uninstall software on Linux, as well as keep track of already installed RPM packages on your system. This can be done because RPM keeps a database of all software that was installed with it. RPM uses software packages that have (surprise) the .rpm extension. An RPM package contains the actual software that gets installed, maybe some additional files for the software, information on where the software and its files get installed, and a list of other files you need to have on your system in order to run this specific piece of software. When you use RPM for installing the software package, RPM checks if your system is suitable for the software the RPM package contains, figures out where to install the files the package provides, installs them on your system, and adds that piece of software into its database of installed RPM packages. Note that different Linux distros may keep their software and the files related to that software in different directories. That's why it's important to use the RPM package that was made for your distribution. For example, if you install a SuSE specific software package on a Red Hat system, RPM may put the files from that package into wrong directories. In the worst case the result is that the program doesn't find all the files it needs and doesn't work properly. :

10

There are some good graphical programs for installing RPM packages, but in this tuXfile I'll discuss the fool-proof command line method for installing software. Note that you need to be root when installing software in Linux. When you've got the root privileges, you use the rpm command with appropriate options to manage your RPM software packages. <Installing and upgrading RPM packages> For installing a software package, you use the rpm command with -i option (which stands for "install"). For example, to install an RPM package called software-2.3.4.rpm: # rpm -i software-2.3.4.rpm If you already have some version installed on your system and want to upgrade it to the new version, you use -U option instead (which stands for "upgrade"). For example, if you have software-2.3.3.rpm installed and want to upgrade it: # rpm -U software-2.3.4.rpm If all goes well, the files in your package will get installed into your system and you can happily run your new program. But where is your new program? Note that rpm doesn't usually create a special directory for the software package's files. Instead, the different files from the package get placed into appropriate existing directories on your Linux system. Executable programs go usually into /bin, /usr/bin, /usr/X11/bin, or /usr/X11R6/bin after installing with rpm. But how can you run your new program if you don't know where the executable is? Sometimes the program gets automatically added into your menu, but usually you can just run the program by typing its name at the command prompt. In most cases you don't have to know where the program was installed because you don't have to type the whole path when running the program, only the program's name is needed <Removing software installed with RPM> To remove software that was installed with RPM, you use the -e option (which stands for "erase"): # rpm -e software-2.3.4 Note that when installing software, you have to type the name of the RPM package. But when removing software, you don't have to type the whole name of the package that contained the software. You don't have to type the .rpm extension when removing software. Probably you don't have to type the version number, either, so this would do exactly the same as the above: # rpm -e software This rpm -e command uses the RPM database to check where all the files related to this software were installed and then automatically removes all of those files. After removing the program files, it also removes the program from the database of installed software. The principal benefit of open source software is, as its name implies, access to the inner workings of an application. Given the source, you can study how an application works; change, improve, and extend its operation; borrow and repurpose code (per the limits of the application's license); and port the application to novel and emergent platforms.

11

However, such liberal access is not always wanted. For instance, a user may not want the onus of building from source code. Instead, he or she may simply want to install the software much like a traditional "shrink-wrapped" application: insert media, run setup, answer a few prompts, and go. Indeed, for most computer users, such pre-built software is preferred. Pre-built code is less sensitive to system vagaries and thus more uniform and predictable. In general, a pre-built, open source application is called a package and bundles all the binary, data, and configuration files required to run the application. A package also includes all the steps required to deploy the application on a system, typically in the form of a script. The script might generate data, start and stop system services, or manipulate files and directories. A script might also perform operations to upgrade existing software to a new version. Because each operating system has its idiosyncrasies, a package is typically tailored to a specific system. Moreover, each operating system provides its own package manager, a special utility to add and remove packages from the system. For example, Debian Linux-based systems use the Advanced Package Tool (APT), while Fedora Linux systems use the RPM Package Manager. The package manager precludes partial and faulty installations and "uninstalls" by adding and removing the files in a package atomically. The package manager also maintains a manifest of all packages installed on the system and can validate the existence of prerequisites and co-requisites beforehand. If you're a software developer or a systems administrator, providing your application as a package makes installations, upgrades, and maintenance much easier. Here, you learn how to use the popular RPM Package Manager to bundle a utility. For purposes of demonstration, you'll bundle the networking utility wget, which downloads files from the Internet. The wget utility is useful but isn't commonly found standard in distributions. (An analog, curl, is often included in distributions.) Be aware that you can use RPM to distribute most anythingscripts, documentation, and dataand perform nearly any maintenance task. Building wget manually The wget utility, like many other open source applications, can be built manually. Understanding that process is the starting point for bundling wget in a package. Per the general convention, building wget requires four steps: 1. 2. 3. 4. Download and unpack the source. Configure the build. Build the code. Install the software.

You can download the latest version of the wget source code from ftp.gnu.org. The rest of the steps require the command line, as shown in Listing 1. Listing 1. Installing wget
$ tar xzf wget-latest.tar.gz $ cd wget-1.12 $ ./configure configure: configuring for GNU Wget 1.12

12

checking for a BSD-compatible install... /usr/bin/install -c checking whether build environment is sane... yes checking for a thread-safe mkdir -p... build-aux/install-sh -c -d checking for gawk... no checking for mawk... no checking for nawk... no ... $ make $ sudo make install

./configure

queries the system and sets compilation options suitable for the hardware and software detected. make compiles the code, and sudo make install installs the code in system directories. By default, the directories are rooted at /usr/local, although you can change the target root with the --prefix=/some/full/path/name option to ./configure. To convert this process to RPM, you place the source in a repository and write a configuration file to dictate where to find the source to be compiled and how to build and install the code. The configuration file, called a spec file, is the input to a utility called rpmbuild. The spec file and the binaries are packaged by rpmbuild into an RPM. When another user downloads your RPM, the rpm utility reads the spec file and installs the package per your prewritten instructions.

Building your first RPM Before you continue, one word of caution. In the past, packages were built by root, the superuser, because root was the only user able to access the system source code repository. However, this approach was potentially hazardous. Because root can alter any file on the system, it was easy to inadvertently alter a running system by adding extraneous files or removing important files during interim builds of an RPM. More recently, the RPM system changed to allow any user to build RPMs in a home directory. Building an RPM without the privileges of root prevents changes to core system files. Here, the more modern approach is shown. To build an RPM, you must:

Set up a directory hierarchy per the rpmbuild specifications. Place your source code and supplemental files in the proper locations in the hierarchy. Create your spec file. Build the RPM. You can optionally build a source RPM to share your source code with

others. To begin, build the hierarchy. In a directory in your home directorysay, $HOME/mywget creates five subdirectories:

BUILD. BUILD is used as scratch space to actually compile the software. RPMS. RPMS contains the binary RPM that rpmbuild builds. SOURCES. SOURCES is for source code. SPECS. SPECS contains your spec file or filesone spec file per RPM you want to 13

build.

SRPMS. SRPMS contains the source RPM built during the process.

At a minimum, you need source code in SOURCES and a spec file in SPECS. Copy your source, ideally bundled as a tarball, into the SOURCES directory, as shown in Listing 2. If necessary, rename the tarball to include the version number of the application to differentiate it from others. The naming convention is package-version.tar.gz. In the case of wget, you would use:

Listing 2. Copying your source


$ $ $ $ $ $ $ $ cd ~ mkdir mywget cd mywget mkdir BUILD RPMS SOURCES SPECS SRPMS cd SOURCES cp wget-latest.tar.gz . mv wget-latest.tar.gz wget-1.12.tar.gz cd ..

Next, create the spec file. A spec file is nothing more than a text file with a special syntax. Listing 3 shows an example of a spec file. Listing 3. Sample spec file
# This is a sample spec file for wget %define %define %define %define %define _topdir /home/strike/mywget name wget release 1 version 1.12 buildroot %{_topdir}/%{name}-%{version}-root %{buildroot} GNU wget GPL %{name} %{version} %{release} %{name}-%{version}.tar.gz /usr Development/Tools

BuildRoot: Summary: License: Name: Version: Release: Source: Prefix: Group:

%description The GNU wget program downloads files from the Internet using the commandline. %prep %setup -q %build ./configure make

14

%install make install prefix=$RPM_BUILD_ROOT/usr %files %defattr(-,root,root) /usr/local/bin/wget %doc %attr(0444,root,root) /usr/local/share/man/man1/wget.1

Let's walk through the spec file from top to bottom. Lines 1-5 define a set of convenience variables used throughout the rest of the file. Lines 7-15 set a number of required parameters using the form parameter: value. As you can see in line 7 and elsewhere, variables can be evaluated and combined to produce the value of a setting. The parameter names are largely self-evident, but BuildRoot merits some explanation to differentiate it from the BUILD directory you already created. BuildRoot is a proxy for the final installation directory. In other words, if wget is ultimately installed in /usr/local/bin/wget and other subdirectories in /usr/local, such as /usr/local/man for documentation, BuildRoot stands in for /usr/local during the RPM build process. Once you set BuildRoot, you can access its value using the RPM_BUILD_ROOT environment variable. You should always set BuildRoot in your spec file and check the contents of that directory to verify what is going to be installed by the package. Here are a few tips:

Do not use ./configure --prefix=$RPM_BUILD_ROOT. This command builds the entire package, assuming that the final location of the files is the build root. It is likely that this would cause any program that needs to locate its installed files at run time to fail, because when your RPM is finally installed on a user's system, the files aren't under the build root anymorethat's just a temporary directory on your build system. Do not include a path in the definition of Source. Version and Release are especially important. Each time you change your application's code or data and make a new RPM available, be sure to increment the values of Version and Release to reflect major and minor changes, respectively. You may find it helpful to bump the release number each time you build an RPM, even if for your own use, to keep attempts separate. The next section starts with %description. You should provide a concise but clear description of the software here. This line is shown whenever a user runs rpm -qi to query the RPM database. You can explain what the package does, describe any warnings or additional configuration instructions, and more. The %prep, %build, and %install sections are next, consecutively. Each section generates a shell script that is embedded into the RPM and run subsequently as part of the installation. %prep readies the source code, such as unpacking the tarball. Here, %setup -q is a %prep macro to automatically unpack the tarball named in Source. The instructions in the %build section should look familiar. They are identical to the steps you used to configure and launch the build manually. The %install section is identical, too. 15

However, while the target of the manual build was the actual /usr/local directory of your system, the target of the %install instruction is ~/mywget/BUILD.
%files

lists the files that should be bundled into the RPM and optionally sets permissions and other information. Within %files, you can use the %defattr macro to define the default permissions, owner, and group of files in the RPM; in this example, %defattr(-,root,root) installs all the files owned by root, using whatever permissions found when RPM bundled them up from the build system. You can include multiple files per line in %files. You can tag files by adding %doc or %config to the line. %doc tells RPM that the file is a documentation file, so that if a user installs the package using --excludedocs, the file is not be installed. %config tells RPM that this is a configuration file. During upgrades, RPM will attempt to avoid overwriting a user's carefully modified configuration with an RPM-packaged default configuration file. Be aware that if you list a directory name under %files, RPM includes every file under that directory.

Revving the RPM Now that your files are in place and your spec file is defined, you are ready to build the actual RPM file. To build it, use the aptly named rpmbuild utility: $ rpmbuild -v -bb --clean SPECS/wget.spec

This command uses the named spec file to build a binary package (-bb for "build binary") with verbose output (-v). The build utility removes the build tree after the packages are made (-clean). If you also wanted to build the source RPM, specify -ba ("build all") instead of -bb. (See the rpmbuild man page for a complete list of options.)

rpmbuild performs these steps:


Reads and parses the wget.spec file. Runs the %prep section to unpack the source code into a temporary directory. Here, the temporary directory is BUILD. Runs the %build section to compile the code. Runs the %install section to install the code into directories on the build machine. Reads the list of files from the %files section, gathers them up, and creates a binary RPM (and source RPM files, if you elect). If you examine your $HOME/mywget directory, you should find a new directory named wget1.12-root. This directory is the proxy for the target destination. You should also find a new

16

directory named RPMS/i386, which should in turn contain your RPM, named wget-1.121.i386.rpm. The name of the RPM reflects that this is wget version 1.12 for the i386 processor. To verify that the RPM contains the proper files, you can use the rpm command, as shown in Listing 4.

Listing 4. Verifying the RPM contents


$ rpm -Vp missing .M....G. missing .M....G. missing missing missing missing missing missing . . . RPMS/i386/wget-1.12-1.i386.rpm /usr/local/bin/wget /usr/local/etc c /usr/local/etc/wgetrc /usr/local/share /usr/local/share/info d /usr/local/share/info/wget.info /usr/local/share/locale /usr/local/share/locale/be /usr/local/share/locale/be/LC_MESSAGES d /usr/local/share/locale/be/LC_MESSAGES/wget.mo

The command rpm -Vp RPMS/i386/wget-1.12-1.i386.rpm verifies the package against the files on the system. Although there are seemingly lots of errors, each is a clue that the contents of the RPM file are correct. If you are expecting a file to be installed and it does not appear in the output, it was not included in the package. In that event, review the spec file and make sure the file is enumerated in the %files section. After you've verified the RPM, you can distribute the file to coworkers. Once your colleagues receive the file, they should run rpm to install wget on their own systems: $ sudo rpm -i wget-1.12-1.i386.rpm

Other uses for RPM This brief introduction merely scratches the surface of what's possible with RPM. Although it is most often used to install software and attendant files, you can package most anything, from system scripts to source code to documentation. And as you'll see in the second installment of this series, you can also use RPM to patch source code as well as rebuild and reinstall software. The RPM distribution format is found on many Linux systems and is the preferred method to install binary software on Red Hat and Fedora systems, among others. If you build it and package it with RPM, they will come.

17

Ex. No: 05 Installing various software packages Date :

Aim: Installing various software packages, either the package is yet to be installed or an older version is existing. The student can practice installing the latest version. Of course, this might need internet access. Install samba and share files to windows Install Common Unix Printing System(CUPS) Procedure: There are basically two ways to install software from the Fedora repositories; from the GUI using PackageKit and from the command line using yum. Because the yum approach is simpler, throughout this document we describe that method. However, there are a number of details with respect to yum that are useful to know, and some users feel more comfortable with a graphical user interface. Hence, this appendix A normal user on Linux can't install much software, you need to become the root user to gain the rights to do so. This goes a long way towards protecting you from accidents (just about anything that does go wrong, you've done deliberately). Sometimes, you can temporarily get root-user rights by typing in the root password, when prompted, when you try to do something that requires those rights (such as picking system administration configuration items from a menu, or installing something directly from a webpage). Other times you open a command line terminal, and do it all in there, manually. You can see an example of the first situation by picking an administration item from the system menu. Try one, and then cancel the requester that pops up (i.e. do nothing to reconfigure your system, just look at how it asks you to enter a password).

A screenshot of menus & sub-menus

18

A screenshot of the password entry window You use the left mouse button for all of this, and only click once on your choice. Sub-menus open if you pause for a moment where they branch out from (there's a little arrow/triangle in the menus indicating where a sub-menu starts from). The right mouse button is for doing alternative options, the left mouse button is what you use for the normal action. Double-clicks are for opening things from icons on the desktop, itself (that's the background behind any windows, and between the bars at the top and bottom of the screen), or inside file listers. Everything else is a single-click. Don't ask me which menu items to use, read through your menus and figure it out for yourself. They're in the menu bar at the very top of the screen, and that's menus in the plural. Look through all of them, not just one of them. They're called a menu on purposeyou look through the choices on offer, and they're laid out in logically-grouped sections. Installing stuff in the other way, manually via the command line, goes through the following process: 1. Open a terminal (find it in your menus). 2. Become the root user by typing su - (that's ess you space dash, and hitting enter). 3. Type in the root password, when prompted, and hit enter. 4. Type other command lines, as appropriate (see further below), and hitting enter at the end of each line. 5. Close the terminal window when you're finished. To install a program that's in one of the Fedora file repositories, you can use the yum command, followed by the name of the package you want to install (e.g. yum install pidgin), hit enter, watch any progress messages, and follow the prompts that appear after a while. If it needs to do something, you'll get asked about it (such as, downloading and installing the package, and any other packages it requires to go with it). It's a yes/no question, you hit y or n, and then the enter key. No's the default response (that's why it's shown as a capital N). If you just hit enter without typing y or n, you've answered no.

19

A screenshot of installing pidgin in a terminal window

If there's nothing to do, perhaps because it's already installed, it'll go through the motions and drop back to the command line prompt, waiting for your next command. If it can't do it, you'll get some sort of message about why, and get dropped back at the command line prompt for you to enter your next command. If it can do it, you'll get some progress reports as it goes about its business, then you'll get dropped back to the command line prompt, at the end, for your next command. You can install several packages at once, just by listing them one after another (e.g. yum install pidgin firefox evolution). And you can install software that you've already downloaded with a few variations on the prior instructionsyou use a localinstall option with yum, instead of install, and you write the whole filename, instead of just the package name (e.g. yum localinstall pidgin-2.0.0-0.1.fc5.rpm). You need to be working in the directory that you saved the file to, or write the filepath (to where you saved it) along with the filename. Tip: You can use the tab key to finish some of your typing. e.g. Once I'd got as far as typing the file name, I'd start typing in pidg and hit the tab key, and it'd complete the rest of the filename.

Occasionally, you might encounter problems. Two common ones are not being able to use a repo, or not being able to find a package file that's needed. Yum will try to use several different repos, automatically, before giving up. You don't have to do anything to resolve this issue. If it 20

doesn't manage to get a response, or can't find some of the package files it needs, the simplest solution is to try again, later on. You might have struck a time when the file repositories aren't ready for use. If yum gets stuck trying to use repo after repo, or one takes ages apparently doing nothing, you can break out of it by holding down the CTRL key and tapping the c key. You might have to do that several times.
Installing Software with the GUI
Launch the PackageKit application by selecting Administration->Add/Remove Software from the System menu:

Figure A.1. Launching PackageKit

There may be a delay before the controls on the window that appears may be used. This delay may be brief or lengthy, depending on what you have done earlier. The data used by PackageKit is cached, and if it is stale, new data will be downloaded, which may take several minutes. Type in the name of the package you wish to install in the text box at the upper left, and select the Find button. There may be a delay, and you may need to click the Find button a second time. The package (perhaps with several others) will appear to the right. The closed box indicates that the package is not installed on your system.

21

Figure A.2. Searching for Software

Click on the check box next to the package you wish to install. A blue plus sign will appear over the box indicating that is has been selected to install.

Figure A.3. Selecting a package to install

You may repeat the process if you wish to install additional packages. When you have selected the packages you wish, click the Apply button at the lower right to install the packages. Depending on how your system has been configured, you may be prompted to enter the password for the administrative user. If the package is unsigned, or is from a repository you have not used before, you may be prompted for this password again. As a general rule, only administrators may install software. 22

Figure A.4. Authorizing the installation

Enter the root password and click Authenticate. The package will then be installed. When the installation is complete, the package wll be shown as an open box, indicating that the package is installed. For some applications, the application's icon may be displayed instead of the open box. The Apply button will be disabled, indicating that there are no pending actions to apply.

Figure A.5. Package is installed The Find button searches not only the name of the package, but also the package description. Some common words may reveal several packages, some perhaps not those intended. For example, if you typed in "circuit" with the intent of finding circuit design applications, you may also find applications referring to wired communications circuits as well as racing circuits!

23

Figure A.6. Searching the description

Sometimes you may want to try several variations of a word or phrase. If, for example, you are looking for an SSTV application, trying "slowscan" or "slow scan" will fail:

Figure A.7. Searching the description - failure

The developer of the slow scan application used the word "slow-scan" in his description. PackageKit is not smart enough to guess what you meant or what the original developer was thinking.

Figure A.8. Searching the description - success

24

SAMBA - Windows Linux file Sharing Notes


Some basic notes on using SAMBA on a home network with linux and windows machines, like my home network setup.

Running SAMBA on a Linux machine


To start, stop or restart samba,
/etc/init.d/smd start /etc/init.d/smd stop /etc/init.d/smd restart

All options for the SAMBA goes to /etc/samba/smb.conf This is my smb.conf Notable changes I made are: My linux machine is a gateway server with two ethernet interfaces eth0 and eth1. For security reasons I set up SAMBA to run only on the internal interface
interfaces = 192.168.0.1/24 127.0.0.1/24 bind interfaces only = Yes

Also set hosts allow to only allow internal and localhoist


hosts allow = 127. 192.168.0. hosts deny = *

SAMBA authentification
For the file access permissions for the shares to work, you have to set up the SAMBA username/password by running smbpasswd program on the linux box. Then on the Windows machine login with the username/password created above with smbpasswd. Otherwise the file sharing will not work.

SAMBA Linux to Windows Sharing


Set up the shares in /etc/samba/smb.conf as follows
[musak] comment = music from linux boxen path = /var/stuff/media/musak read only = Yes

On the windows machine access it as \\192.168.0.1\musak where 192.168.0.1 is the IP address of the linux machine. If you want to share CD/DVD drive 25

[dvd] comment = dvd drive on linux boxen writable = No locking = No path = /mnt/cdrom2

SAMBA Windows to Linux Sharing


First turn on file sharing. Go to Start->Setting->Control Panel and open "Network" and in the first tab called "Configuration" click on "File and Pring Sharing..." and om the Dialog Box that comes up check "I want to be able to give others access to my files" Now go to the file explorer and right click on the folder you want to sgare, and from the menu that pops up slect "Sharing..." and from the "Manual Properties" Dialog Box that comes up select the second tab "Sharing" and select "Shared as" which will enable all the text boxes, fill in the "Share Name" "Comments" and selct "Read Only" "Full" or "Depends on Password" and enter a password. This is the password that will give access to this share. Also note the "Share Name", lets name it "MYSHARE". Also find out the hostname of the Windows machine. Go to Start->Setting->Control Panel and Open "Network" and in the second tab "Identification" note the "Computer Name", This is the name to use from Linux to access shares on this machine. Let it be "MYWINBOX" Now go to the Linux machine. Crete mount point for the share.
mkdir /mnt/winstuff

Mount the share named "MYSHARE" on Windows hos namedt "MYWINBOX" smbmount \\MYWINBOX\MYSHARE /mnt/winstuff This will prompt you for the password for the share, enter the password and after that if you go to /mnt/winstuff you can access all files on the Windows folder. Printer Configuration Tool allows users to configure a printer. This tool helps maintain the printer configuration file, print spool directories, print filters, and printer classes. Fedora 12 uses the Common Unix Printing System (CUPS). If a system was upgraded from a previous Fedora version that used CUPS, the upgrade process preserves the configured queues. Using Printer Configuration Tool requires root privileges. To start the application, select System (on the panel) >Administration>Printing, or type the command system-config-printer at a shell prompt.

26

Figure 23.1. Printer Configuration Tool

The following types of print queues can be configured: AppSocket/HP JetDirect a printer connected directly to the network through HP JetDirect or Appsocket interface instead of a computer. Internet Printing Protocol (IPP) a printer that can be accessed over a TCP/IP network via the Internet Printing Protocol (for example, a printer attached to another Fedora system running CUPS on the network). LPD/LPR Host or Printer a printer attached to a different UNIX system that can be accessed over a TCP/IP network (for example, a printer attached to another Fedora system running LPD on the network). Networked Windows (SMB) a printer attached to a different system which is sharing a printer over an SMB network (for example, a printer attached to a Microsoft Windows machine). Networked JetDirect a printer connected directly to the network through HP JetDirect instead of a computer.
Important If you add a new print queue or modify an existing one, you must apply the changes for them to take effect.

Clicking the Apply button prompts the printer daemon to restart with the changes you have configured. Clicking the Revert button discards unapplied changes.

23.1. Adding a Local Printer


To add a local printer, such as one attached through a parallel port or USB port on your computer, click the New Printer button in the main Printer Configuration Tool window to display the window in Figure 23.2, Adding a Printer . 27

Figure 23.2. Adding a Printer Click Forward to proceed. Enter a unique name for the printer in the Printer Name field. The printer name can contain letters, numbers, dashes (-), and underscores (_); it must not contain any spaces. You can also use the Description and Location fields to further distinguish this printer from others that may be configured on your system. Both of these fields are optional, and may contain spaces. Click Forward to open the New Printer dialogue (refer to Figure 23.3, Adding a Local Printer). If the printer has been automatically detected, the printer model appears in Select Connection. Select the printer model and click Forward to continue. If the device does not automatically appear, select the device to which the printer is connected (such as LPT #1 or Serial Port #1) in Select Connection.

Figure 23.3. Adding a Local Printer

Next, select the printer type. Refer to Section 23.5, Selecting the Printer Model and Finishing for details.

28

Ex. No: 06 Write userspace drivers using fuse Date Aim: GUI programming: a sample programme using Gambas since the students have VB knowledge. However, one should try using GTK or QT Procedure: Filesystem in Userspace (FUSE) is a loadable kernel module for Unix-likecomputeroperating systems that lets non-privileged users create their own file systems without editing kernel code. This is achieved by running file system code in user space while the FUSE module provides only a "bridge" to the actual kernel interfaces. Filesystem in Userspace :

A flow-chart diagram which shows how FUSE works

FUSE is a three-part system. The first of those parts is a kernel module which hooks into the VFS code and looks like a filesystem module. It also implements a special-purpose device which can be opened by a user-space process. It then spends its time accepting filesystem requests, translating them into its own protocol, and sending them out via the device interface. Responses to requests come back from user space via the FUSE device, and are translated back into the form expected by the kernel. In user space, FUSE implements a library which manages communications with the kernel module. It accepts filesystem requests from the FUSE device and translates them into a set of function calls which look similar (but not identical) to the kernel's VFS interface. These functions have names like open(), read(), write(), rename(), symlink(), etc. Finally, there is a user-supplied component which actually implements the filesystem of interest. It fills a fuse_operations structure with pointers to its functions which implement the required operations in whatever way makes sense. This interface is not well documented, but the example 29

filesystem provided with FUSE (which implements a simple sort of loopback filesystem) is reasonably easy to follow. FUSE Filesystem in User Space #rpm qa | grep fuse // checking file system Libconfuse using this we can develop fuse. #wget http://192.168.1.172/fosslab/samples/fuse.gz #tar zxvf fuse.gz #cd fuse #pwd /home/fosslab/fuse #ls Select fuse_tutorial.tgz #tar zxvf fuse_tutorial.tgz #firefox index.html #cd src #ls (src) #pkg-config fuse-_cflags -D FILE_OFFSET_BITS=64 I/usr/include/fuse #pkg-config fuselibs `-pthread L/lib lfuse lrt ldl #make // we will get bbfs obj file in green color // using for extracting

Make: bbfs is up to date #cd .../example/ #ls l..

30

Eg dir #ls rootdir/ #ls mountdir/ #../src/bbfs rootdir/ mountdir/ About to call fuse_main #fusermount u mountdir #mount . . . . #ll rootdir/ #ll mountdir/ #touch rootdit/myfile.txt #ll mountdir/

31

Ex. No: 07 GUI Programming Date Aim: GUI programming: a sample programme using Gambas since the students have VB knowledge. However, one should try using GTK or QT Procedure: Gambas is a GUI-based programming environment that brings the ease and charm of early versions of Visual Basic into the Linux environment. :

Gambas programming
Now we need to make the program DO something. Let's start with the menus. Click on the "Quit" entry in the File menu and a text area should appear with the cursor in the middle of a prenamed subroutine called PUBLIC SUB Quit_Click(). Whatever code we put in here will run when the user clicks the Quit item (easy, isn't it?). Enter the following code: FMain.Close and save the project. Run the project now and the Quit menu option should close the form for us. Gambas Basic is an object-oriented language, which means that all our controls, including the form itself, carry baggage around with them in the form of properties and methods. Properties are settings that we can change, while methods are things that can be made to happen. One of the things that can be made to happen to the form is closing, and we just made it happen. Objectoriented programming can either be incredibly easy or horrendously difficult, depending on how far you want to go with it, but friendly user interfaces like this would be virtually impossible without it. Add the following code to the other menu items: Clear -- TextArea1.Text = " " Copy -- Clipboard .Copy(TextArea1.Text) Paste -TextArea1.Text = Clipboard.Paste() In this case, Text is a property of the control called TextArea1, and Copy and Paste are methods associated with the system object Clipboard. Run the program and check that your code works so far. Programming the word count Programming our word count button is going to be a little more difficult, but not much. If you know some Basic or Visual Basic already you will find that most of it works in a predictable way within Gambas. If not, check the Web or hunt up a good book. There are a variety of ways we can get Basic to count the words in our box, but for the sake of simplicity I will do it by running through all the text one character at a time, counting the number of spaces, and adding one. The result won't be perfect, but it should be close enough. Click on the Count Words! button and

32

enter the following code after PUBLIC SUB Button1_Click(). Gambas will take care of the spaces and capitalization. DIM i, w AS Integer FOR i = 1 TO Len(TextArea1.Text) IF Mid(TextArea1.Text, i, 1) = " " THEN w=w+1 NEXT Label1.Text = w + 1 Here we are defining two variables as integers (whole numbers) and calling them i and w. As newly defined variables they start off with a value of zero. The Len() function gives us the number of characters in our text area, and the Mid() function pulls out each new character in turn. If it is a space character, the variable w is increased by one. Having looked through all the characters, we add 1 to the value of w for the last word (which isn't followed by a space) and put the final value in the label.Check if your program is working, make any corrections that are necessary, and save it. Packaging and distribution At this stage we have a working Gambas project file, but the only people who can use it are those who already have Gambas installed. That leaves out a lot of users! To make your program more portable for distribution, there are two steps you can carry out: 1. Make an executable file 2. Package the file for distribution as a .deb To make an executable file, go to the Project menu and select "Make Executable." Within a few seconds this will create a file called XXX.gambas, where XXX is your project name, inside your project directory. This can be copied and distributed to anyone who has a runtime version of Gambas installed, which includes by default most of the major Linux distributions. A second option, "Project/Make Source Archive' will just bundle together all the files associated with the program into a single compressed .gz file. To make the application more portable still, it can be bundled into an installation package. "Project/Make Installation Package" gives the user the option of making installation packages for any or all of the major distros: Debian, Fedora, Mandriva, OpenSUSE, and of course Ubuntu. A wizard then takes the user through the necessary steps: the creator's name and email address are added, the appropriate group is chosen for repository storage, and a default Applications menu category and position is specified for each distro package. Gambas then compiles the necessary files into a distributable which can be uploaded to a repository.

33

Packaging and distribution

What next? Now you know how to do simple Gambas programming, what next? There are any number of easy projects you can cut your teeth on. Unfortunately Gambas support on the web is a little sparse, and the built-in help is little more than a list of commands, but a Google search for 'Visual Basic' will bring up many tutorials and books that you should be able to adapt to Gambas relatively easily. Later, when you want to extend your skills, here are some topics to look into:

Saving and opening text files Graphics -- using Gambas to make patterns and designs in a drawing area Connecting with and modifying a mySQL database Control groups and arrays: connecting one piece of code with many different controls Multimedia: using Gambas to create sound, music and video players Games: from simple text games with random numbers and a timer through to complex movements and designs.

34

Ex. No: 08 Version Control System setup and usage using RCS, CVS, SVN Date : Aim: Version Control System setup and usage using RCS, CVS, SVN Procedure: Keeping a version history of files under /etc is essential for maintaining a healthy system. The benefits of tracking changes to /etc include:

Documentation: The log messages that are attached to configuration changes serve as documentation. These log messages record who made the change, when and why. Understanding the contents of a config file becomes much easier if you have a full history of the changes that were made to this file. Troubleshooting: Misconfiguration can result in a variety of problems. When a service starts to misbehave, one of the things you can do to troubleshoot the issue is to check the version history of its config file. There, you can see if any changes were made around the time frame in which the problem happened. If you spot a change that may be causing the issue, you can easily revert it to fix the problem. You can set up your own repository to track changes to /etc, or you can use a tool called etckeeper to handle the setup for you. This tool supports multiple version control systems, including Git, Mercurial and Bazaar. It integrates with the package management systems of a number of Linux distros, including APT (used by Debian, Ubuntu), YUM (RedHat, CentOS, Fedora), Pacman (Arch Linux). Using etckeeper instead of rolling your own has some advantages:

etckeeper integration with package managers means than you don't need to manually commit changes in /etc after installing packages. etckeeper comes pre-configured with a list of files that live in /etc but usually do not benefit from version control (like some cache files).

Installing etckeeper
To install etckeeper on Debian or Ubuntu, run:
$ sudo apt-get install etckeeper

If you use another Linux distro, search the packcage list in your package manager. If etckeeper supports your system, you will probably find it there. Otherwise, you can download the source from the official site of etckeeper.

Configuring etckeeper
Next, let's configure etckeeper. Open /etc/etckeeper/etckeeper.conf in your favorite editor. The first option that you need to look at is VCS, which is the version control system you want to 35

use. By default it's set to git, but you can change it to hg or bzr depending on your preference. I use git myself, but most of this article should apply to etckeeper regardless of the version control system you choose. Another option that I recommend looking at is AVOID_COMMIT_BEFORE_INSTALL. By default, etckeeper will automatically commit any pending changes when you install packages. I find this behavior undesirable, as it may commit unfinished changes. I disable it by setting AVOID_COMMIT_BEFORE_INSTALL to 1. If you installed etckeeper from source, have a look at HIGHLEVEL_PACKAGE_MANAGER and LOWLEVEL_PACKAGE_MANAGER and change them depending on the package manager of your system.

Using etckeeper
With this, we are done with configuring etckeeper. Let's create a repository now:
$ cd /etc $ sudo etckeeper init $ sudo etckeeper commit "Initial import"

This will create an empty repository and then commit the contents of your /etc directory to it. From here, using etckeeper is not different from using the version control system you selected. Let's say you want to change your MySQL config; you can edit the file and then commit it as usual:
$ cd /etc $ sudo vi /etc/mysql/my.cnf $ sudo git commit -m "Commit message"

36

Ex. No: 09 Text processing with Perl Date :

Aim: Text processing with Perl: simple programs, connecting with database e.g., MYSQL Procedure:

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

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 37

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

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 38

red orange

6.

for deletion 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 @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";

39

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

9. While loop (until) in perl


#!usr/bin/perl $a=0; until($a>10) #is equal to while { print "$a\n"; $a++; }

Output:
[linuxpert@localhost ~]$ perl unless.pl a less than 10[linuxpert@localhost ~]$ perl until.pl 0 1 84 2 3 4 5 6 40

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 41

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

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 42

ARRAY(0x8358a70) hello 122 200 thamarai 122 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

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

43

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:
[linuxpert@localhost ~]$ perl functionparam.pl 25

44

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

45

Output:
91 [linuxpert@localhost ~]$ perl symbolicref.pl the product is 600

14. Program to check greater among 3 numbers


#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

46

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

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

48

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 { if ($_[0] > $_[1]) { $ _ [ 0 ] ; } e l s e { 49 $_[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";

Example3: Program to return the values sub get_list { return 5..10; } @list = &get_list; print "@list"; 96

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 EntitiesDefinition < or rRead Only Access > or wCreates, Writes, and Truncates >> or aWrites, 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

50

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

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

52

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

53

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 +--------------------+ 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 | +--------------------+ 54

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

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 $dbh->disconnect;

55

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

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

57

CGI PROGRAMMING
EXAMPLE -1 Type the following in terminal [linuxpert@localhost ~]$ su Password: [root@localhost linuxpert]# cd /var/www/cgi-bin [root@localhost cgi-bin]# gedit Type the following in gedit #!/usr/bin/perl use CGI; $cgi=new CGI; print $cgi->header, $cgi->start_html, $cgi->h1("A simple Example"), $cgi->end_html;

Type the following in the same terminal [root@localhost cgi-bin]# chmod +x form.cgi Go to browser and type the following URL http://localhost/cgi-bin/form.cgi

U will get the output as

58

EXAMPLE -2 In terminal
[linuxpert@localhost ~]$ su Password: [root@localhost linuxpert]# cd /var/www/html [root@localhost html]# gedit Type the following in gedit editor <html> <head> <title>LOGIN</title></head> <body> <form action="/cgi-bin/form2.cgi" method="post"> <p> "Enter student roll no"<input type="text" name="rollno"></p> <p>"enter the student name"<input type="text" name="sname"></p> <p>"click here to submit"<input type="submit" name="submit"></p> </form> </body> Save the page as form.html & close it.

Type the following URL in browser http://localhost/form.html


Then type the following in the terminal [root@localhost html]# cd /var/www/cgi-bin [root@localhost cgi-bin]# gedit Type the following in gedit #!/usr/bin/perl use CGI; $cgi=new CGI; use DBI; $rollno=$cgi->param('rollno'); $name=$cgi->param('sname'); 59

my $dbh=DBI->connect("dbi:mysql:student","root",""); my $sth=$dbh->prepare("insert into students values(?,?)"); $res=$sth->execute($rollno,$name); $dbh->disconnect; if($res) { print $cgi->header, $cgi->start_html, $cgi->h1("Record created"), $cgi->end_html; } Save that file as form2.cgi Close that file & open a same terminal type as [root@localhost cgi-bin]# chmod +x form2.cgi In new browser type the following http://localhost/form.html

we get the screen as

60

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)

61

Ex. No: 10 Running PHP Date :

Aim: Running PHP: simple applications like login forms after setting up a LAMP stack Procedure: 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 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()); 62

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

When u press the submit button

63

Now go to terminal [linuxpert@localhost ~]$ mysql -u root -p\ >> Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 28 Server version: 5.1.45 Source distribution mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | student | | test | +--------------------+ 4 rows in set (0.11 sec) 64

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

65

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

66

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

67

OUTPUT:

68

Ex. No: 11 Running Python Date :

Aim: Running Python: some simple exercise e.g. connecting with MySql database Procedure:

1. Write a Hello World Python Program


Create helloworld.py program as shown below. $ vim helloworld.py #!/usr/bin/python # Hello world python program print "Hello World!";

2. Verify Python Interpreter Availability


Make sure python interpreter is installed on your system as shown below. $ whereis python python: /usr/bin/python /usr/bin/python2.5 /usr/bin/python2.6 /etc/python /etc/python2.5 /etc/python2.6 /usr/lib/python2.4 /usr/lib/python3.0 /usr/lib/python2.5 /usr/lib/python2.6 /usr/local/lib/python2.5 /usr/local/lib/python2.6 /usr/include/python2.5 /usr/include/python2.6 /usr/share/python /usr/share/man/man1/python.1.gz $ which python /usr/bin/python 69

3. Execute Python Program


You can either execute using python helloworld.py or ./helloworld.py. $ python helloworld.py Hello World! ( or ) $ chmod u+x helloworld.py $ ./helloworld.py Hello World!

69

Note: As python is an interpreted language, you dont have the compilation step similar to the C program.

4. Write a sample program in python programming


#Sample python program x=5; y=5; print ("x:",x); print("y:",y); z=x+y; print("z:",z); 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" ); 70

print(str[-1]); #print last character print(str[-6]);#print character from last 6th position print(str[:-2]);# Everything except the last two characters

6. Write a python program to perform function in Lists


#Python Lists #!/usr/bin/python print("\t \t \t Python Lists"); list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print("Prints complete list:",list); print("Prints 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 );

#modify the 4th elements in the list print("Before modifying the 4th element in list :",list[4]); list[4]='efgh'; print("4th element in list :",list[4]); print(" complete list:",list);

#Appending new elements list.append('ijkl'); print("After appending list:",list);

#deleting an element in list del list[2]; print("List :",list); 71

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

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


#Python Dictionary tinydict = {'name': 'john','code':6734, 'dept': 'sales'} print ("Python Dictionary:" ); print ("complete dictionary",tinydict ); print ("Key :",tinydict.keys()); # Prints all the keys print ("values:",tinydict.values()); # Prints all the values

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


#!/usr/bin/python #program to select odd number from the list a=[11,12,13,14,15,16,17,18,19,20,21,31,44,45,10]; print("List is:",a); n=len(a); print("length:",n); i=0; print("Odd number"); for i in range(len(a)): if(a[i]%2==1): print(a[i]); 72

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

11. For Statement in Python


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

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


>>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>>for i in range(len(a)): ... print i, a[i] ... OUTPUT: 0 Mary 1 had 2a 3 little 4 lamb 73

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 OUTPUT: 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3

14. Fibonacci Series using Python


>>>def fib(n): # write Fibonacci series up to n ... """Print a Fibonacci series up to n.""" ... a, b = 0, 1 ... while b < n: ... print b, ... a, b = b, a+b >>># Now call the function we just defined: ... fib(2000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 74

15. Set operations in Python


>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> fruit = set(basket) # create a set without duplicates >>> fruit set(['orange', 'pear', 'apple', 'banana']) >>> 'orange' in fruit # fast membership testing True >>> 'crabgrass' in fruit False >>># Demonstrate set operations on unique letters from two words 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'])

16. Modules And Error Handling In Python


75

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

17.Finally class in Python


>>>def divide(x, y): ... try: ... result = x / y ... except ZeroDivisionError: 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 76

>>> divide("2", "1") executing finally clause Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in divide TypeError: unsupported operand type(s) for /: 'str' and 'str'

18. Simple Class Program in python


>>>class Complex: ... def __init__(self, realpart, imagpart): ... self.r = realpart ... self.i = imagpart ... >>> x = Complex(3.0, -4.5) >>> x.r, x.i (3.0, -4.5) 77

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 modules name (as a string) is available as the value of the global variable __name__. For instance, use your favorite text editor to create a file called fibo.py in the current directory with the following contents: Step 1: Fibo.py def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b Step 2: 77

>>> import fibo Step 3: >>> fibo.fib(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

78

Ex.No: 12 Set up the complete network interface Date :

Aim: To set up Network Interface using 'ifconfig' command and the related system files. Introduction: A Network interface is the point of interconnection between a computer and a private or public network. A network interface is generally a network interface card (NIC). Ethernet is a family of computer networking technologies for local area networks (LANs) commercially introduced in 1980. Standardized in IEEE 802.3 , Ethernet has largely replaced competing wired LAN technologies. Gateway is a node that allows you to gain entrance into a network and vice versa. On the Internet the node which is the stopping point can be a gateway or a host node. A computer that controls the traffic your network or your ISP (Internet Service Provider) receives is a node. DNS (Domain name server), the system that automatically translates Internet addresses to the numeric machine addresses that computers use Iptables is a user space application program provided by the Linux kernel firewall (implemented as different Netfilter modules) ,that allows us to configure the tables and the chains and rules it stores. Iptables requires elevated privileges to operate and must be executed by user root , otherwise it fails to function. On most Linux systems, iptables is installed as /usr/sbin/iptables and documented in its man page , which can be opened using man iptables when installed. Prerequisites : To enable networking, you must configure your network interface card or cards with an IP address and netmask. The kernel must have support for your cards compiled in, either as modular support or direct support. To set your cards up, do the following. Assume your network as 192.168.2.0, IP=192.168.x.y, broadcast=192.168.x.y, netmask=255.255.255.0, gateway192.168.x.y, nameserver=192.168.x.y Note:- Please replace 'x' & 'y' with the relevant numbers from your network. Procedure : Step 1 : Learn about your network & tools required a) Basic Information 1. Determine your machines IP address from your network administrator 2. Your network mask. This determines which portion of the IP address specifies the subnetwork number and which portion specifies the host. Class C (most networks) 255.255.255.0 79

3. Your network address which is your IP address bit wise anded with the network mask. 4. Your broadcast address. Used to broadcast packets to every machine on your subnet. 5. Your gateway address. The address of the machine that is your gateway to the outside world. In many cases: Ex: IP: 192.168.2.100 Gateway: 192.168.2.201 6. Your nameserver address. Translates host names into IP addresses. 192.168.2.205 b) Configuration tools There are many network configuration tools today. They are: netconf A GUI interactive interface linuxconf A GUI interactive interface which includes netconf configuration. netconfig A GUI step by step interface ifconfig A text based program to configure the network interface. Type "man ifconfig" for info. These programs will modify values in the following files: /etc/sysconfig/network - Defines your network and some of its characteristics. /etc/HOSTNAME - Shows the host name of this host. IF your name is "myhost" then that is exactly the text this file will contain. /etc/resolv.conf - Specifies the domain to be searched for host names to connect to, the nameserver address, and the search order for the nameservers. /etc/hosts - Shows addresses and names of local hosts. /etc/networks - Provides a database of network names with network addresses similar to the /etc/hosts file. This file is not required for operation. /etc/sysconfig/network-scripts/ifcfg-eth* - There is a file for each network interface. This file contains the IP address of the interface and many other setup variables. c) Analysis Tools netstat - Displays information about the systems network connections, including port connections, routing tables, and more. The command "netstar -r" will display the routing table. traceroute - This command can be used to determine the network route from your computer to some other computer on your network or the internet. To use it you can type "route IPaddress" of the computer you want to see the route to. nslookup - Used to query DNS servers for information about hosts. arp - This program lets the user read or modify their arp cache. tcpdump - This program allows the user to see TCP traffic on their network. dig(1) - Send domain name query packets to name servers for debugging or testing. Try the above tools. Step 2 : Configuring the Network You can use one of the above tools or configure the network the old fashioned way as follows: 1. First to use networking on any permanent basis you should setup the 80

file /etc/sysconfig/network similar to the example shown below. 2. Assign an ip address with "ifconfig eth0 192.168.x.y netmask 255.255.255.0 up". 3. Tell your machine that a hub is ready for information with the command "route add -net 192.168.0.0 netmask 255.255.255.0 eth0" 4. To contact hosts outside your network if a machine with IP address 192.168.x.y is the gateway use the command "route add default gw 192.168.x.y eth0" 5. If using a dialup connection use the command "route add default ppp0" The word default says if the packet is not for a machine on your local network, send it to the default device. These settings are not permanent, but go away the next time you boot. They are normally set up in the directory /etc/sysconfig/network-scripts. Add the network interface to the file /etc/sysconfig/network-scripts/ifcfg-eth*. For example the file ifcfgeth0 if for the first ethernet interface, ifcfg-eth1 for the second, and so on. The lines given below are from ifcfg-eth0: (Assuming 192.168.2.100 as your machine IP) DEVICE="eth0" IPADDR="192.168.2.100" NETMASK="255.255.0.0" ONBOOT="yes" BOOTPROTO="none" Unless you know what you're doing it is best to use a network configuration tool. Step 3 : Configuring an interface for multiple IP addresses If you want to configure your network card to act as more than one IP address, issue the following command: ifconfig dummy 192.168.1.102 netmask 255.255.255.0 This uses the dummy system interface capability supported in the kernel to setup another virtual interface which operates at IP address 192.168.1.102. Substitute the IP address that you want your virtual interface to be with an appropriate netmask for your network. To disable this, issue the following command. ifconfig dummy down Another way to use multiple IP addresses on one ethernet card is to set up a new file in your /etc/sysconfig/network-scripts directory. Copy your ifcfg-eth0 role to ifcfg-eth0:0. Edit that file and rename the device to "eth0:0" and the IP address to the desired IP address. You may also want to modify BROADCAST, NETWORK, or NETMASK. You can continue adding IP addresses by using :1, :2, etc such as ifcfg-eth0:2. Sample of ifcfg-eth0:1 for the IP : 192.168.2.101 DEVICE="eth0:1" IPADDR="192.168.2.101" NETMASK="255.255.0.0" ONBOOT="yes" BOOTPROTO="none" To make it effective, you must reboot your system or issue the command "/etc/rc.d/init.d/network restart" as root. Step 4: Gaining familiarity with Networking files and configuring for DNS /etc/sysconfig/network 81

The /etc/inittab file contains the entry "si::sysinit:/etc/rc.d/rc.sysinit" which causes the system at startup to run the rc.sysinit script. The rc.sysinit file expects to find the file /etc/sysconfig/network if networking is to be enabled. The network file looks like this: Make the changes as per the highlighted lines. NETWORKING=yes FORWARD_IPV4=false HOSTNAME=yourname.collegename.com DOMAINNAME=collegename.com GATEWAY=192.168.x.y GATEWAYDEV=eth0 Where GATEWAYDEV is the network interface card that is attached to the network the gateway machine is on. The GATEWAY is the actual IP address of the gateway machine.(Assuming 192.168.2.100 as your machine IP) /etc/hosts - Defines local hosts. 127.0.0.1 localhost localhost.localdomain 192.168.1.100 yourname.collegename.com yourname /etc/named.conf - Used for domain name service to configure named. Other files used are dependent on this file. This file is explained further in the DNS section /etc/resolv.conf - Specifies the domain to be searched for host names to connect to, the nameserver address, and the search order for the nameservers. domain collegename.com search collegename.com mynet.net nameserver 192.168.1.100 nameserver 192.168.199.1 nameserver 192.168.1.10 The third line specifies that DNS should be tried on your machine first then use the normal nameserver on the fifth line. The fourth line specifies that my machine is running nameservices on another network which is using interface 192.168.199.1. This assumes the nameserver is set up on your machine. You can add additional nameservers like google DNS nameserver 8.8.8.8 nameserver 8.8.4.4 Step 5: Routing Setting up of Gateway Routing table information is used to route incoming and outgoing network diagrams to other machines. On most simple configurations, there are three routes. One for sending packets to your own machine, one for sending packets to other machines on your network and one for sending packets to other machines outside your network through the gateway. Two programs (ifconfig and route) are used to configure these parameters. They are described in more detail in the routing section. Static routes: IP (Internet Protocol) uses a routing table to determine where packets should be sent. First the packet is examined to see if its' destination is for the local or remote network. If it is to be sent to a remote network, the routing table is consulted to 82

determine the path. If there is no information in the routing table then the packet is sent to the default gateway. Static routes are set with the route command and with the configuration file: /etc/sysconfig/network-scripts/route-eth0 DEVICE=eth0 BOOTPROTO=static IPADDR=192.168.x.y NETMASK=255.255.255.0 GATEWAY=XXX.XXX.XXX.XXX HOSTNAME=node-name.name-of-domain.com DOMAIN=name-of-domain.com Define route with with the 'route' command: Examples: route add default gw XXX.XXX.XXX.XXX dev eth0 route add -net XXX.XXX.XXX.0 netmask 255.255.255.0 gw XXX.XXX.XXX.XXX dev eth0 Where XXX.XXX.XXX.XXX is the gateway to the internet as defined by your ISP or network operator. Note :- If a mistake is made just repeat the route command substituting "del" in place of "add". Step 6: Managing iptables Try the following .. as root user... a) You can start, stop, and restart iptables after booting by using the commands: # service iptables start # service iptables stop # service iptables restart b)To get iptables configured to start at boot, use the chkconfig command:. # chkconfig iptables on c)You can determine whether iptables is running or not via the service iptables status command. Fedora Core will give a simple status message. For example # service iptables status Firewall is stopped.

83

Vous aimerez peut-être aussi