You are on page 1of 122

ANNAMALAIAR COLLEGE OF ENGINEERING

Mudaiyur-606902

(COMPUTER SCIENCE AND ENGINEERING) (2012-2013)

CS2406 OPEN SOURCE LABORATORY

Name Roll No Year Subject

.. Reg. No .. .. Semester . ..

Open Source Laboratory

ANNAMALAIAR COLLEGE OF ENGINEERING


Mudaiyur-606902

DEPARTMENT OF

______________________

CERTIFICATE
This is Certified that the bonafied record of practical work done by Selvan/Selvi .. .Reg No Sem In the Subject of . during 2011 - 2012.

Head of the Department

Staff in-Charge

Submitted for the Practical Examination held on

...

Internal Examiner

External Examiner

Annamalaiar College Of Engineering

Open Source Laboratory

INDEX
Ex. No
1 2 3 4 5 6 7

Date

Name of the Experiment


KERNEL CONFIGURATION, COMPILATION AND INSTALLATION VIRTUALIZATION ENVIRONMENT

P.No

Sign

COMPILATION FROM SOURCE

PACKET MANAGEMENT SYSTEM

INSTALLATION OF SOFTWARE PACKAGES

WRITING USERSPACE DRIVERS USING FUSE

GUI PROGRAMMING VERSION CONTROL SYSTEM SETUP AND USAGE TEXT PROCESSING WITH PERL

8 9 10 11 12

SIMPLE APPLICATIONS USING PHP

SIMPLE APPLICATION USING PYTHON

SETTING UP THE NETWORK INTERFACE

Annamalaiar College Of Engineering

Open Source Laboratory

Ex. No. 01 Date : Aim:

KERNEL CONFIGURATION, COMPILATION AND INSTALLATION

To install latest kernel source code from kernel.org, compile the kernel and install it in the local system and also to try to view the source code of the kernel. Procedure: Step 1: Get Latest Linux kernel code Visit http://kernel.org/ and download the latest source code. File name would be Linux- x.y.z.tar.bz2, where x.y.z is actual version number. For example file inux- 2.6.25.tar.bz2 represents 2.6.25 kernel version. Use wget command to download kernel source code: $ cd /tmp $ wget http://www.kernel.org/pub/linux/kernel/v2.6/linux-x.y.z.tar.bz2 Note: Replace x.y.z with actual version number. Step 2: Extract tar (.tar.bz3) file Type the following command: # tar -xjvf linux-2.6.25.tar.bz2 -C /usr/src # cd /usr/src Step 3: Configure kernel Before you configure kernel make sure you have development tools (gcc compilers and related tools) are installed on your system. If gcc compiler and tools are not installed then use apt-get command under Debian Linux to install development tools. # apt-get install gcc Now you can start kernel configuration by typing any one of the command: $ make menuconfig - Text based color menus, radiolists & dialogs. This option also useful on remote server if you wanna compile kernel remotely. $ make xconfig - X windows (Qt) based configuration tool, works best under KDE desktop $ make gconfig - X windows (Gtk) based configuration tool, works best under Gnome Dekstop. For example make menuconfig command launches following screen: $ make menuconfig You have to select different options as per your need. Each configuration option has HELP button associated with it so select help button to get help. Step 4: Compile kernel Start compiling to create a compressed kernel image, enter: $ make

Annamalaiar College Of Engineering

Open Source Laboratory

Start compiling to kernel modules: $ make modules Install kernel modules (become a root user, use su command): $ su # make modules_install Step 5: Install kernel So far we have compiled kernel and installed kernel modules. It is time to install kernel itself.# make install It will install three files into /boot directory as well as modification to your kernel grub configuration file: System.map-2.6.25 config-2.6.25 vmlinuz-2.6.25 Step 6: Create an initrd image Type the following command at a shell prompt: # cd /boot # mkinitrd -o initrd.img-2.6.25 2.6.25 initrd images contains device driver which needed to load rest of the operating system later on. Not all computer requires initrd, but it is safe to create one. Step 7: Modify Grub configuration file - /boot/grub/menu.lst Open file using vi: # vi /boot/grub/menu.lst title Debian GNU/Linux, kernel 2.6.25 Default root kernel initrd (hd0,0) /boot/vmlinuz root=/dev/hdb1 ro /boot/initrd.img-2.6.25 savedefault boot Remember to setup correct root=/dev/hdXX device. Save and close the file. If you think editing and writing all lines by hand is too much for you, try out update-grub command to update the lines for each kernel in /boot/grub/menu.lst file. Just type the command:# updategrub Step 8: Reboot computer and boot into your new kernel Issue reboot command: # reboot

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

RESULT: Thus the latest kernel source code from the kernel.org is compiled, installed and the source code of the kernel is viewed successfully.

Annamalaiar College Of Engineering

Open Source Laboratory

Ex. No. 02 Date : Aim:

VIRTUALIZATION ENVIRONMENT

Virtualization setup with xen system and installing Freedos in virtual machine Pre-requisites: Fedora 14 installed with root access To ensure that all tools required are installed. [root@fosslab ~]# rpm -qa xen xen-4.0.1-6.fc14.i686 [root@fosslab ~]# rpm -qa virt-manager virt-manager-0.8.5-1.fc14.noarch [root@fosslab ~]# rpm -qa qemu qemu-0.13.0-0.7.rc1.fc14.i686 [root@fosslab ~]# rpm -qa libvirt libvirt-0.8.3-2.fc14.i686 [root@fosslab ~]# Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in [root@fosslab ~]# service libvirtd status libvirtd is stopped [root@fosslab ~]# service libvirtd start Starting libvirtd daemon: [ OK ] [root@fosslab ~]# selinux should be disabled - setenforce 0 [root@fosslab ~]# setenforce 0 Download Freedos iso from server Open Firefox Browser and type the url http://192.168.1.251/downloads Click the fdbasecd.iso and click on save Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Creating a virtual machine [root@fosslab ~]#virt-manager Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in In the base menu, please right click on the localhost (QEMU) to create a new VM. Please name the VM as freedos Once the name of the vm is entered, please click on forward In the next screen, select the Use ISO image option then click the Browse option. Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in In the next screen click the Browse Local option on the bottom left

Annamalaiar College Of Engineering

Open Source Laboratory

section of the screen. In the next screen please select Downloads and select fdbasecd.iso Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in In the next screen, please select yes. In the next screen, please select the CPU and RAM limits for the VM. By default they are 512M and one CPU. Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in In the next screen, please select the required size for the VM (0.2 GB) and select forward In the next screen, select finish Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in In the next screen, type 1 for to boot Freedos In the next screen, select option 1 Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in In the next screen slect the language and keyboard layout as English(US) In the next screen select Run FreeDos from CD-ROM Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in In the next screen, type fdisk for to create partition In the next screen, type Y In the next screen, type option 1 for to create dos partition Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in In the next screen, type option 1 for to create Primary dos partition Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in In the next screen, type Y Next press ESC for to quit fdisk In the next screen type setup Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in In the next screen select Reboot option In the next screen select the option Install to harddisk using FreeDOS Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in In the next screen slect the language and keyboard layout as English(US) In the next screen, select Yes Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in In the next screen type YES

Annamalaiar College Of Engineering

Open Source Laboratory

In the next screen select the option Continue eith FreeDOS installation Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in In the next screen select the option Start installation of FreeDOS 1.0 Final In the next screen select Press any key to continue Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in In the next screen press Enter After installation, select h option for Boot From first harddisk Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in In the next screen select option 3 Load FreeDOS including HIMEM XMSmemory driver Now FreeDOS running under Virtual Machine For ease in configuration please use GUI tool called virtual Machine manager (Applications-System Tools-Virtual Machine-manager)

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

RESULT: Thus the applications are tested using new kernels and isolate applications in virtualized environment successfully.

Annamalaiar College Of Engineering

Open Source Laboratory

Ex. No.03 Date : Aim:

COMPILATION FROM SOURCE

To learn about the common build systems available in Linux and to use them.

Introduction: Open source software is distributed in source code form. In case of popular software Linux distributions will often have the software packaged in their repositories. If the package is not package is not in the repository the user has to compile the software from source. To do this the user has to understand about the build system used in the project. The GNU build system, also known as the Autotools, is a suite of programming tools designed to assist in making source-code packages portable to many Unix-like systems. It can be difficult to make a software program portable: the C compiler differs from system to system; certain library functions are missing on some systems; header files may have different names. One way to handle this is write conditional code, with code blocks selected by means of preprocessor directives (#ifdef); but because of the wide variety of build environments this approach quickly becomes unmanageable. The GNU build system is designed to address this problem more manageably. Tools included in the GNU build system The GNU build system comprises the GNU utility programs Autoconf, Automake, and Libtool. Other related tools frequently used with the GNU build system are GNUs make program, GNU gettext, pkg-config, and the GNU Compiler Collection, also called GCC. GNU Autoconf Autoconf generates a configure script based on the contents of a configure.ac file which characterizes a particular body of source code. The configure script, when run, scans the build environment and generates a subordinate config.statusscript which, in turn, converts other input files and most commonly Makefile.in into output files (Makefile) which are appropriate for that build environment. Finally the make program uses Makefile to generate executable programs from source code. The complexity of the GNU build system reflects the variety of circumstances under which a body of source code may be built. Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in If a source code file is changed then it suffices to re-run make which only re- compiles that part of the body of the source code affected by the change. If a .in file has changed then it suffices to re-run config.status and make. If the body of source code is copied to another computer then it is suffices to re- run configure (which runs config.status) and make. (For this reason source code using the GNU build system is normally distributed without the files that configure generates.) If the body of source code is changed more fundamentally then configure.ac and the .in files need to be changed and all subsequent steps also followed. To process files, autoconf uses the GNU implementation of the m4 macro system. Autoconf comes with several auxiliary programs such as Autoheader, which is used to help manage C header

Annamalaiar College Of Engineering

Open Source Laboratory

files; Autoscan, which can create an initial input file for Autoconf; and ifnames, which can list C preprocessor identifiers used in the program. GNU Automake Automake helps to create portable Makefiles, which are in turn processed with the make utility. It takes its input as Makefile.am, and turns it into Makefile.in, which is used by the configure script to generate the file Makefile output. GNU Libtool Libtool helps manage the creation of static and dynamic libraries on various Unix-like operating systems. Libtool accomplishes this by abstracting the library-creation process, hiding differences between various systems (e.g. GNU/Linuxsystems vs. Solaris). Gnulib Gnulib simplifies the process of making software that uses Autoconf and Automake portable to a wide range of systems. Make In software development, make is a utility that automatically builds executable programs and libraries from source code by reading files called makefiles which specify how to derive the target program. Make can decide where to start through topological sorting. Though integrated development environments and language-specific compiler features can also be used to manage the build process in modern systems, make remains widely used, especially in Unix. Make is typically used to build executable programs and libraries from source code. Generally though, any process that involves transforming a dependency file to a target result (by executing some number of arbitrary commands) is applicable to make. To cite an example, make could be used to detect a change made to an image file (the dependency) and the target actions that result might be to convert the file to some specific format, copy the result into a content management system, and then send e-mail to a predefined set of users that the above actions were performed. Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Cmake CMake is a unified, cross-platform, open-source build system that enables developers to build, test and package software by specifying build parameters in simple, portable text files. It works in a compiler-independent manner and the build process works in conjunction with native build environments, such as make, Apple's Xcode and Microsoft Visual Studio. It also has minimal dependencies, C++ only. CMake is open source software. CMake can: Create libraries Generate wrappers Compile source code Build executable in arbitrary combination Apache Ant Apache Ant is a software tool for automating software build processes. It is similar to Make but is implemented using the Java language, requires the Java platform, and is best suited to building Java projects. The most immediately noticeable difference between Ant and Make is that Ant uses

Annamalaiar College Of Engineering

Open Source Laboratory

XML to describe the build process and its dependencies, whereas Make uses Makefile format. By default the XML file is named build.xml. Ant is an Apache project. It is open source software, and is released under the Apache Software License. Pre-requisites: To ensure that all tools required are installed. Type the following commands in terminal and type the password for root user, when prompted. [fosslab@fosslab~]$ su Password: [root@ fosslab fosslab]# rpm -qa cmake cmake-2.8.2-2.fc14.i686 [root@ fosslab fosslab]# rpm -qa ant ant-1.7.1-13.fc13.i686 [root@ fosslab fosslab]# rpm -qa java-1.6.0-openjdk-devel java-1.6.0-openjdk-devel-1.6.0.0-44.1.9.1.fc14.i686 [root@ fosslab fosslab]# exit Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Exercises: Create a directory for all the programs in the exercise. [fosslab@fosslab ~]$ mkdir build_systems [fosslab@fosslab ~]$ cd build_systems [fosslab@fosslab build_systems]$ Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in 1. Make We will be using a simple program written in C and write a makefile to compile the program. [fosslab@fosslab build_systems]$ mkdir gnumake [fosslab@fosslab build_systems]$ cd gnumake [fosslab@fosslab gnumake]$ gedit squareroot.c Type and save the following simple program for square root of a number // A simple program that computes the square root of a number #include <stdio.h> #include <stdlib.h> #include <math.h> int main (int argc, char *argv[]) { if (argc < 2) { fprintf(stdout,"Usage: %s number\n",argv[0]); return 1; } double inputValue = atof(argv[1]); double outputValue = sqrt(inputValue); fprintf(stdout,"The square root of %g is %g\n",

Annamalaiar College Of Engineering

Open Source Laboratory

inputValue, outputValue); return 0; } Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Close gedit and test it by compiling it once: [fosslab@fosslab gnumake]$ gcc squareroot.c -o squareroot -lm [fosslab@fosslab gnumake]$ . /sqaureroot 25 The square root of 25 is 5 [fosslab@fosslab gnumake]$ Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in write a simple makefile to compile the program. [fosslab@fosslab gnumake]$ gedit Makefile Type and save the following code # Commands start with TAB not spaces CC = gcc CFLAGS = -g LDFLAGS = -lm all: squareroot squareroot: squareroot.o squareroot.o: squareroot.c clean: rm -f squareroot squareroot.o Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Close gedit and test the Makefile [fosslab@fosslab gnumake]$ make make: Nothing to be done for `all'. [fosslab@fosslab gnumake]$ make clean [fosslab@fosslab gnumake]$ make gcc -g -c -o squareroot.o squareroot.c gcc -lm squareroot.o -o squareroot [fosslab@fosslab gnumake] ./squareroot 25 The square root of 25 is 5 [fosslab@fosslab gnumake] Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in 2. Cmake write a simple script for CMake to compile the previously written program. Create a new directory and copy the source code to it. [fosslab@fosslab gnumake] mkdir cmake [fosslab@fosslab gnumake] cp squareroot.c /home/fosslab/build_systems/gnumake/cmake/ Create configuration files for Cmake.

Annamalaiar College Of Engineering

Open Source Laboratory

[fosslab@fosslab gnumake] cd cmake [fosslab@fosslab cmake]$ gedit CmakeLists.txt Type and save the following code cmake_minimum_required (VERSION 2.6) project (squareroot) add_executable(squareroot squareroot.c) TARGET_LINK_LIBRARIES(squareroot m) Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in CMake is commonly use with out of source builds ie, we build the program in a directory separate from the source. We use the generated makefile to compile the program. [fosslab@fosslab cmake]$ mkdir build [fosslab@fosslab cmake]$ cd build [fosslab@fosslab build]$ cmake .. Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in make [fosslab@fosslab build]$ ./squareroot 25 The square root of 25 is 5 Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in 3. Apache Ant Create a new directory for the ant exercise. (open a nee terminal ) [fosslab@fosslab ~]$ cd build_systems [fosslab@fosslab build_systems]$ mkdir ant [fosslab@fosslab build_systems]$ cd ant [fosslab@fosslab ant]$ mkdir -p src/hello [fosslab@fosslab ant]$ gedit src/hello/HelloWorld.java Type and save the following code package hello; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } } Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in [fosslab@fosslab ant]$ mkdir -p build/classes [fosslab@fosslab ant]$ javac -sourcepath src -d build/classes/ src/hello/HelloWorld.java [fosslab@fosslab ant]$ java -cp build/classes hello.HelloWorld Hello World [fosslab@fosslab ant]$ write the ant build script. [fosslab@fosslab ant]$ gedit build.xml

Annamalaiar College Of Engineering

Open Source Laboratory

Type the following code and save <project> <target name="clean"> <delete dir="build"/> </target> <target name="compile"> <mkdir dir="build/classes"/> <javac srcdir="src" destdir="build/classes"/> </target> <target name="jar"> <mkdir dir="build/jar"/> <jar destfile="build/jar/HelloWorld.jar" basedir="build/classes"> Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in <manifest> <attribute name="Main-Class" value="hello.HelloWorld"/> </manifest> </jar> </target> <target name="run"> <java jar="build/jar/HelloWorld.jar" fork="true"/> </target> </project> Now the project can be compile and run using ant. [fosslab@fosslab ant]$ ant clean Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in [fosslab@fosslab ant]$ ant compile jar run GNU Autotools Copy the file hello-2.7.tar.gz to the buildsystems project directory and uncompress it [fosslab@fosslab ~]$ cd Downloads [fosslab@fosslab Downloads]$ mv hello-2.7.tar.gz /home/fosslab/build_systems [fosslab@fosslab Downloads]$ cd /home/fosslab/build_systems [fosslab@fosslab build_systems]$ tar -xzf hello-2.7.tar.gz [fosslab@fosslab build_systems]$ cd hello-2.7 [fosslab@fosslab hello-2.7]$ Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in [fosslab@fosslab hello-2.7]$ ./configure Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in [fosslab@fosslab hello-2.7]$ make [fosslab@fosslab hello-2.7]$ src/hello

Annamalaiar College Of Engineering

Open Source Laboratory

The program will now reside in the src directory. To install the program log in as root. [fosslab@fosslab hello-2.7]$ su Password: [root@fosslab hello-2.7]# make install Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in [root@fosslab hello-2.7]# exit exit Now the program can be run from anywhere. [fosslab@fosslab hello-2.7]$ hello Hello, world! [fosslab@fosslab hello-2.7]$

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

RESULT: Thus the various build systems using open source operating system is learned successfully.

Annamalaiar College Of Engineering

Open Source Laboratory

Ex.No.04 Date :

PACKET MANAGEMENT SYSTEM

DESCRIPTION: When Linux developers create their software they typically bundle all the executable and data files into a single file that is often called a "package" file. Package files have different formats and contain different control files that determine where the rest of the files should be placed, the permissions they should have and a list of prerequisite packages that are required for the package to function correctly. Some of this information may also be stored in a database on your system by the package management software used to install the software and is used to speed up some of the administrative functions of the package manager. Redhat, Centos and Fedora Linux software is primarily available in RedHat Package Manager (RPM) files. Regular RPM package files are used for installations in which the kernel, or master program, hasn't been customized in any way. This is the usual scenario for most departmental servers. Source RPMs are used when the kernel has been customized to add or drop support selectively for various devices or features for the sake of performance or functionality. The procedure for installing source RPMs involves recompiling source code to fit the needs of these kernel customizations. This makes life easier for the software developer who wrote the package as he or she now has only to create a single package to support all types of customizations. Both package types use standardized commands for installing the software contained inside making RPMs relatively easy to use. Software developers who want to use a universally recognizable file format across all flavors of Linux also will make their products available as TAR packages. TAR packages are generally more difficult to work with than RPM packages because the archived files within them may or may not need to be compiled and the commands to install the software may vary from package to package. Instructions are usually contained within a file inside the TAR package to help guide the installation. Where to Get Commonly Used Packages There are three commonly used sources for packages; distribution CDs; packages manually downloaded via a browser, File Transfer Protocol (FTP) client, or the wget utility; and automated downloads. Each of these methods is introduced here, but is covered in greater detail in sections to follow. Packages on Your Installation CDs Installing from your distribution CDs is usually easier than having to download files from a remote Web site, but they are never up to date for very long. We discuss using this method in more detail later. Manually Downloaded Packages The two most common ways of getting packages are by manually using FTP or a Web browser. Table 6-1 lists some common download sites that can be used. Remember to match the RPM to the distribution and version of Linux your system is running.

Automated Package Download The disadvantage of manual downloads is that the packages often won't install unless certain prerequisite packages have been installed beforehand. This can lead to the download and

Annamalaiar College Of Engineering

Open Source Laboratory

installation of several packages which can become tedious. All the major Linux distributions have automated download and update utilities. For example, Fedora uses yum and Ubuntu and Debian use apt. These are all covered in greater detail in sections to follow. How to Download Software One of the most universally performed tasks by Linux systems administrators is the downloading of software. It is usually very simple to do and the most commonly used methods are covered in this section. Getting Software Using Web-Based FTP There are numerous Web sites that provide links to software you can download. The methodology to get the software is usually the same for all: Browse the desired Web site until you find the link to the software package you need. Click on the link for the desired software package. Save the file to your hard drive Some web browsers, such as Firefox, will automatically download the file to your desktop, but where is the desktop? In Linux, your desktop is usually a sub-directory named Desktop located in your home or ~ directory. Here we see that the root user's desktop already contains a downloaded RPM file. [root@bigboy tmp]# cd ~/Desktop/ [root@bigboy Desktop]# ls ElectricFence-2.2.2-20.2.i386.rpm [root@bigboy Desktop]# pwd /root/Desktop [root@bigboy Desktop]# Getting RPMs Using Command-Line Anonymous FTP The Web based method above transparently uses anonymous File Transfer Protocol (FTP). Anonymous FTP allows you to log in and download files from a FTP server using the username anonymous or the shorter username ftp and a password that matches your e-mail address. This way anyone can access the data. Let's illustrate this with an example of using anonymous FTP to download the SSH package from download.fedora.redhat.com: 1) First we issue the FTP command targeting download.fedora.redhat.com at the command line. [root@bigboy tmp]# ftp download.fedora.redhat.com Trying 66.187.232.35... Connected to download.fedora.redhat.com (66.187.232.35). 220 Fedora FTP server ready. All transfers are logged. Name (download.fedora.redhat.com:root): anonymous 331 Please specify the password. Password: 230 Login successful. Have fun. Using binary mode to transfer files. ftp> pwd 257 "/" ftp> ls

Annamalaiar College Of Engineering

Open Source Laboratory

227 Entering Passive Mode (66,187,232,35,57,155) 150 Here comes the directory listing. drwxr-xr-x 3 ftp ftp 4096 Oct 29 15:59 pub 226 Directory send OK. ftp> 2) After we've logged in, we can use the help command to see what options we have at our disposal. ftp> help Commands may be abbreviated. Commands are: ! cr mdir proxy send $ delete mget sendport site account debug mkdir put size append dir mls pwd status ascii disconnect mode quit struct bell form modtime quote system binary get mput recv sunique bye glob newer reget tenex case hash nmap rstatus trace ccc help nlist rhelp type cd idle ntrans rename user cdup image open reset umask chmod lcd passive restart verbose clear ls private rmdir ? close macdef prompt runique cprotect mdelete protect safe ftp> FTP Commands Command Description binary Copy files in binary mode cd Change directory on the FTP server dir List the names of the files in the current remote directory exit Bye bye get Get a file from the FTP server lcd Change the directory on the local machine ls Same as dir mget Same as get, but you can use wildcards like "*" mput Same as put, but you can use wildcards like "*" passive Make the file transfer passive mode put Put a file from the local machine onto the FTP server

Annamalaiar College Of Engineering

Open Source Laboratory

pwd Give the directory name on the local machine 3) By using the Web browsing feature on the Web site ahead of time, I know that the Fedora Core 2 RPMs are located in the pub/fedora/linux/core/2/i386/os/Fedora/RPMS/ directory and will use the cd command to change my directory to there. We can use the ls command to get a listing of files in this directory. ftp> cd pub/fedora/linux/core/2/i386/os/Fedora/RPMS/ 250 Directory successfully changed. ftp> ls open* 227 Entering Passive Mode (66,187,232,35,58,3) 150 Here comes the directory listing. -rw-r--r-... ... 184281 Oct 28 23:29 openssh-3.6.1p2-34.i386.rpm 226 Directory send OK. ftp> 4) Next we get the file we need and place it in the local directory /usr/rpm. The hash command will print "#" hash signs on the screen during the download. ftp> hash Hash mark printing on (1024 bytes/hash mark). ftp> lcd /usr/rpm Local directory now /usr/rpm ftp> get openssh-3.6.1p2-34.i386.rpm local: openssh-3.6.1p2-34.i386.rpm remote: openssh-3.6.1p2-34.i386.rpm 227 Entering Passive Mode (66,187,232,35,58,25) 150 Opening BINARY mode data connection for openssh-3.6.1p2-34.i386.rpm (184281 bytes). 226 File send OK. 184281 bytes received in 3.41 secs (53 Kbytes/sec) ftp> Note: You can also use wildcards to download the RPMs you need using the mget command. You'll be prompted for each of the matching RPM files. In the next example, we just aborted this download by typing n. ftp> mget openssh-3.6* mget openssh-3.6.1p2-34.i386.rpm? n ftp> 5) Finally we use the exit command to leave FTP. ftp> exit 221 Goodbye. root@bigboy tmp]# Getting Software Using wget The wget command can be used to download files quickly when you already know the URL at which the RPM is located. This is especially convenient if you are logged into your Linux box from another machine running a Web browser. You can browse the download site for the RPM you need, right click on the desired link and select copy shortcut (Windows) or Copy

Annamalaiar College Of Engineering

Open Source Laboratory

Link Location (Linux). After you have done this, you can then select your SSH/telnet/Linux Terminal login window and type in the command wget URL. Here is an example downloading a DHCP update from Fedora. [root@bigboy tmp]# wget http://linux.stanford.edu/pub/mirrors/fedora/linux/core/2/i386/os/Fedora/RP MS/dhcp-3.0pl2-6.16.i386.rpm --17:38:36-ftp://linux.stanford.edu/pub/mirrors/fedora/linux/core/2/i386/os/Fedora/RPM S/dhcp-3.0pl2-6.16.i386.rpm => `dhcp-3.0pl2-6.16.i386.rpm.5' Resolving linux.stanford.edu... done. Connecting to linux.stanford.edu[171.66.2.18]:21... connected. Logging in as anonymous ... Logged in! ==> SYST ... done. ==> PWD ... done. ==> TYPE I ... done. ==> CWD /pub/mirrors/fedora/linux/core/2/i386/os/Fedora/RPMS ... done. ==> PASV ... done. ==> RETR dhcp-3.0pl2-6.16.i386.rpm ... done. Length: 529,890 (unauthoritative) 100%[===============================>] 529,890 889.12K/s ETA 00:00 17:38:36 (889.12 KB/s) - `dhcp-3.0pl2-6.16.i386.rpm.5' saved [529890] [root@bigboy tmp]# Installing Software From RPM Files The Fedora, Redhat and Centos versions of Linux rely heavily upon the use of software packages in the RPM format. This section covers some of the most important topics required for you to master their use. How To Install RPMs Manually There are generally two ways to install RPM files manually. The first method is by using a file previously downloaded to your hard drive, and the other is to install the RPM from some sort of removable media such as a CD-ROM drive. Using Downloaded Files Download the RPMs (which usually have a file extension ending with .rpm) into a temporary directory, such as /tmp. The next step is to issue the rpm -Uvh command to install the package. The -U qualifier is used for updating an RPM to the latest version, the -h qualifier gives a list of hash # characters during the installation and the -v qualifier prints verbose status messages while the command is run. Here is an example of a typical RPM installation command to install the MySQL server package: [root@bigboy tmp]# rpm -Uvh mysql-server-3.23.58-9.i386.rpm Preparing...

Annamalaiar College Of Engineering

Open Source Laboratory

1:mysql-server ####################### [100%] ####################### [100%] [root@bigboy tmp]# Using CD-ROMs The underlying steps to install RPMs from CDs are similar to those used when installing from your hard disk. The main difference is that you have to access your CD-ROM drive by mounting it first to the mnt/cdrom directory. Your RPMs will then be located in the CDROM's Fedora/RPMs subdirectory. The procedure is as follows: 1) Insert the CD-ROM, check the files in the /mnt/cdrom/Fedora/RPMS directory and then install the RPM. [root@bigboy tmp]# mount /mnt/cdrom [root@bigboy tmp]# cd /mnt/cdrom/Fedora/RPMS [root@bigboy RPMS]# ls filename* filename.rpm [root@bigboy RPMS]# rpm -Uvh filename.rpm Preparing... 1: filename ####################### [100%] ####################### [100%] [root@bigboy RPMS]# 2) When finished, eject the CD-ROM [root@bigboy RPMS]# cd /tmp [root@bigboy tmp]# eject cdrom [root@bigboy tmp]# Note: You can use the rpm command's --aid switch to make it search the CD-ROM for any other RPM dependencies and install them automatically. How to Install Source RPMs Sometimes the packages you want to install need to be compiled in order to match your kernel version. This requires you to use source RPM files: Download the source RPMs or locate them on your CD collection. They usually have a file extension ending with (.src.rpm) Run the following commands as root: Compiling and installing source RPMs with Fedora can be done simply with the rpmbuild command [root@bigboy tmp]# rpmbuild --rebuild filename.src.rpm Here is an example in which we install the tacacs plus package. [root@bigboy rpm]# rpmbuild --rebuild tac_plus-4.0.3-2.src.rpm Installing tac_plus-4.0.3-2.src.rpm Executing(%prep): /bin/sh -e /var/tmp/rpm-tmp.61594 + umask 022

Annamalaiar College Of Engineering

Open Source Laboratory

+ cd /usr/src/redhat/BUILD + cd /usr/src/redhat/BUILD + rm -rf tac_plus-4.0.3 + /usr/bin/gzip -dc /usr/src/redhat/SOURCES/tac_plus-4.0.3.tgz + tar -xvvf ... ... ... + umask 022 + cd /usr/src/redhat/BUILD + rm -rf tac_plus-4.0.3 + exit 0 [root@bigboy rpm]# The compiled RPM file can now be found in one of the architecture subdirectories under /usr/src/redhat/RPMS directory. For example, if you compiled an i386 architecture version of the RPM it will placed in the i386 subdirectory. You will then have to install the compiled RPMs found in their respective subdirectories as you normally would. RPM Installation Errors Sometimes the installation of RPM software doesn't go according to plan and you need to take corrective actions. This section shows you how to recover from some of the most common errors you'll encounter. Failed Dependencies Sometimes RPM installations will fail giving Failed dependencies errors which really mean that a prerequisite RPM needs to be installed. In the next example we're attempting to install the MySQL database server application, which fails because the mysql MySQL client RPM, on which it depends, needs to be installed beforehand: [root@bigboy tmp]# rpm -Uvh mysql-server-3.23.58-9.i386.rpm error: Failed dependencies: libmysqlclient.so.10 is needed by mysql-server-3.23.58-9 mysql = 3.23.58 is needed by mysql-server-3.23.58-9 [root@bigboy tmp]# Installing the MySQL client also fails because it requires the perl-DBD-MySQL package. [root@bigboy tmp]# rpm -Uvh mysql-3.23.58-9.i386.rpm error: Failed dependencies: perl-DBD-MySQL is needed by mysql-3.23.58-9 [root@bigboy tmp]# rpm -Uvh perl-DBD-MySQL-2.9003-4.i386.rpm error: Failed dependencies: libmysqlclient.so.10 is needed by perl-DBD-MySQL-2.9003-4 [root@bigboy tmp]# Strangely enough, the installation of the perl-DBD-MySQL package fails because it needs the mysql client package. To get around this problem you can run the rpm command with the -nodeps option to disable dependency checks. In the next example we install the MySQL

Annamalaiar College Of Engineering

Open Source Laboratory

client ignoring dependencies, followed by successful installation of perl-DBD-MySQL and mysql-server. [root@bigboy tmp]# rpm -Uvh --nodeps mysql-3.23.58-9.i386.rpm Preparing... ####################### [100%] 1:mysql ####################### [100%] [root@bigboy tmp]# rpm -Uvh perl-DBD-MySQL-2.9003-4.i386.rpm Preparing... ####################### [100%] 1:perl-DBD-MySQL ####################### [100%] [root@bigboy tmp]# rpm -Uvh mysql-server-3.23.58-9.i386.rpm Preparing... 1:mysql-server ####################### [100%] ####################### [100%] [root@bigboy tmp]# Note: If all the installation RPMs are located in the same directory, the rpm command can automatically install all the prerequisite RPMs using the --aid option. One of the advantages of using the yum facility is that you don't have to worry about this dependency process as much because the dependency RPMs are always downloaded and installed automatically also. Signature Keys Fedora digitally signs all its RPM files, so it's best to import their public encryption key beforehand so that the RPM installation program will be able to verify the validity of the RPM file. This is usually done automatically in newer versions of Fedora, but will need to be done manually in legacy versions. The manual method uses the rpm command as seen in the next example, but locate the key files first as their locations can vary between Fedora distributions. It is a good idea to import both the RedHat and Fedora keys: [root@bigboy tmp]# locate RPM-GPG-KEY /usr/share/rhn/RPM-GPG-KEY /usr/share/rhn/RPM-GPG-KEY-fedora [root@bigboy tmp]# rpm --import /usr/share/rhn/RPM-GPG-KEY [root@bigboy tmp]# rpm --import /usr/share/rhn/RPM-GPG-KEY-fedora [root@bigboy tmp]# If you don't install the keys you'll get a DSA signature warning that alerts you to the fact that the RPM file might be bogus: [root@bigboy tmp]# rpm -Uvh dhcp-3.0pl2-6.16.i386.rpm warning: dhcp-3.0pl2-6.16.i386.rpm: V3 DSA signature: NOKEY, key ID 4f2a6fd2 Preparing... #################################### [100%] 1:dhcp #################################### [100%] [root@bigboy tmp]# It is always good to install the key files. If they are not there, the RPMs will install with only a warning message. If the RPM's digital signature doesn't match that in the key file, the rpm

Annamalaiar College Of Engineering

Open Source Laboratory

installation program also alerts you and fails to install the RPM package at all: [root@bigboy tmp]# rpm -Uvh dhcp-3.0pl2-6.16.i386.rpm error: dhcp-3.0pl2-6.16.i386.rpm: V3 DSA signature: BAD, key ID 4f2a6fd2 error: dhcp-3.0pl2-6.16.i386.rpm cannot be installed [root@bigboy tmp]# Signatures are therefore useful because they help protect you against tampered and otherwise corrupted RPMs being installed. How to List Installed RPMs The rpm -qa command will list all the packages installed on your system [root@bigboy tmp]# rpm -qa perl-Storable-1.0.14-15 smpeg-gtv-0.4.4-9 e2fsprogs-1.27-9 libstdc++-3.2-7 audiofile-0.2.3-3 ... ... ... [root@bigboy tmp]# You can also pipe the output of this command through the grep command if you are interested in only a specific package. In this example we are looking for all packages containing the string ssh in the name, regardless of case (-i means ignore case) [root@bigboy tmp]# rpm -qa | grep -i ssh openssh-server-3.4p1-2 openssh-clients-3.4p1-2 openssh-askpass-gnome-3.4p1-2 openssh-3.4p1-2 openssh-askpass-3.4p1-2 [root@bigboy tmp]# Note: You could use the rpm -q package-name command to find an installed package because it is much faster than using grep and the -qa switch, but you have to have an exact package match. If you are not sure of the package name and its capitalization, the latter method is probably more suitable. Listing Files Associated with RPMs Sometimes you'll find yourself installing software that terminates with an error requesting the presence of a particular file. In many cases the installation program doesn't state the RPM package in which the file can be found. It is therefore important to be able to determine the origin of certain files, by listing the contents for RPMs in which you suspect the files might reside. Listing Files for Already Installed RPMs This can be useful if you have to duplicate a working server that is already in a production environment. Sometimes the installation of an application fails on the new server due to the lack of a file that resides on the old one. In this case you need to know which RPM on the old

Annamalaiar College Of Engineering

Open Source Laboratory

server contains the file. You can use the -ql qualifier to list all the files associated with an installed RPM. In this example we test to make sure that the NTP package is installed using the -q qualifier, and then we use the -ql qualifier to get the file listing. [root@bigboy tmp]# rpm -q ntp ntp-4.1.2-0.rc1.2 [root@bigboy tmp]# rpm -ql ntp /etc/ntp /etc/ntp.conf /etc/ntp/drift /etc/ntp/keys ... ... ... /usr/share/doc/ntp-4.1.2/rdebug.htm /usr/share/doc/ntp-4.1.2/refclock.htm /usr/share/doc/ntp-4.1.2/release.htm /usr/share/doc/ntp-4.1.2/tickadj.htm [root@bigboy tmp]# Listing Files in RPM Files Sometimes you make a guess and download what you think is the RPM with the missing file. You can use the -qpl qualifier to list all the files in an RPM archive to make sure before installing it: [root@bigboy updates]# rpm -qpl dhcp-3.0pl1-23.i386.rpm /etc/rc.d/init.d/dhcpd /etc/rc.d/init.d/dhcrelay /etc/sysconfig/dhcpd /etc/sysconfig/dhcrelay ... ... ... /usr/share/man/man8/dhcrelay.8.gz /var/lib/dhcp /var/lib/dhcp/dhcpd.leases [root@bigboy updates]# Listing the RPM to Which a File Belongs You might need to know the RPM that was used to install a particular file. This is useful when you have a suspicion about the function of a file but are not entirely sure. For example, the MySQL RPM uses the /etc/my.cnf file as its configuration file, not a file named /etc/mysql.conf as you'd normally expect. The following example confirms the origin of the /etc/my.cnf file. [root@zippy tmp]# rpm -qf /etc/my.cnf mysql-3.23.58-9

Annamalaiar College Of Engineering

Open Source Laboratory

[root@zippy tmp]# Uninstalling RPMs The rpm -e command will erase an installed package. The package name given must match that listed in the rpm -qa command because the version of the package is important. [root@bigboy tmp]# rpm -e package-name Which RPMs Will Start Up At Boot Time? The best way to view and configure which RPMs will start at boot time is by using the chkconfig command with the --list switch.. Automatic Updates with yum The yum automatic RPM update program comes as a standard feature of Fedora Core. It has a number of valuable features: You can configure the URLs of download sites containing the RPM repositories you need. This provides the added advantage of you choosing the most reliable sites in your part of the globe. yum makes multiple attempts to download RPMs before failing. yum automatically figures out not only the RPMs packages that need updating, but also all the supporting RPMs. It then installs them all. Note: Updating packages could cause programs written by you to stop functioning especially if they rely on the older version's features or syntax. Configuring yum The configuration parameters that affect all packages and all yum server URLs are stored in the [main] section of the /etc/yum.conf file. You generally don't need to edit this file, but it can be useful in listing packages that you don't want yum to update. # # File: /etc/yum.conf # [main] exclude=kernel perl In this example the kernel and perl packages are excluded. Configuring /etc/yum.repos.d Repository Files The /etc/yum.repos.d directory has files defining where yum should look on the Internet to find the latest Linux updates. For most common tasks you wont need to modify these files at all. If you want to know how these files affect your system, then continue reading! The configurations for each RPM repository are located in individual configuration files with the .repo file extension. This directory will be populated with files for your Linux distribution's most important repositories. You can also add your own custom files for repositories containing non-standard RPM packages. These files will have the following format: [repositoryid] name=Some name for this repository baseurl=url://path/to/repository/ The [repositoryid] is an identifier that is unique to all files in the directory and can only be one word long and is often given a name that reflects the function of the repository. For example, you may have a fedora-updates.repo file that contains a [updates], and [updates-

Annamalaiar College Of Engineering

Open Source Laboratory

source] sections that refer to URLs for updates of regular RPMs and source RPMs. You can create your own repository files using popular repository sites. The easiest way to determine the exactURLs to use as the baseurl parameter is to go to the http://fedora.redhat.com/download/mirrors.html Web site to get a listing of alternative download sites. Browse the listed sites to find the correct locations of the RPM files in the /updates or /fedora-version URL branches. Make sure that baseurl points to a URL with a /repodata sub-directory beneath it as this sub-directory contains files with instructions for yum to use in doing its updates. Be careful, this sub-directory can be located within the RPM directory or one level above them. Also remember to make the [repositoryid] in your .repo file unique to all other files. Note: yum accepts the use of variables in the configuration file. The $releasever variable refers to the current version of Fedora Core running on your server and the $basearch variable maps to the base architecture of your server which is determined automatically. Here is an example of the use of these variables. [repository-name] name=Fedora Core $releasever - $basearch - Base baseurl=http://url.com/fedora/core/$releasever/$basearch/os/ Note: It is probably best to select yum update sites that use HTTP instead of FTP. There are a number of reasons for this. FTP firewall rules are more difficult to implement than HTTP, outbound HTTP access to the Internet is often already allowed in offices, and web servers are less likely to have connection limits imposed on them, unlike FTP servers, which often have limits on the number of user logins. Note: You can list multiple URLs in a baseurl statement like this and yum will try them all. If you use multiple baseurl statements in each section then yum may act strangely, frequently only selecting the last one in the list. baseurl=url://server1/path/to/files/ url://server2/path/to/files/ url://server3/path/to/files/ Note: You can also place all your [repositoryid] sections in the yum.conf file. This was the methodology used in some older versions of yum. Note: The yum utility can be configured to match the downloaded RPMs against checksum files to help protect against file corruption and malicious forgeries. This is set using the gpgcheck variable in the .repo files. Checks are done when the value is set to 1, when set to 0, they are disabled. Here is an example: # # File: example.repo # gpgcheck=1 gpgkey=http://URL/example.key Repositories will sometimes provide you with the URL for their checksum files and it is a good idea to take advantage of them. This is a valuable feature. How to Automate yum Older versions of yum could be configured to run in the background as a daemon that was simple named yum that used a unified yum.conf file for all its configuration data. Newer

Annamalaiar College Of Engineering

Open Source Laboratory

versions use the yum-updatesd daemon instead. This uses the /etc/yum/yum-updatesd.conf configuration file which governs update frequency, the types of files to be downloaded and whether they should be automatically installed using the yum command. To get yum started, select the commands that match your OS version: 1. If using a newer version of Fedora / Redhat, make sure the yum-updatesd package is installed. [root@bigboy tmp]# yum y install yum-updatesd 2. Use the chkconfig command to get yum configured to start at boot: [root@bigboy tmp]# chkconfig yum-updatesd on [root@bigboy tmp]# chkconfig yum on 3. Use the service command to instruct the /etc/init.d yum script to start/stop yum after booting [root@bigboy tmp]# service yum-updatesd start [root@bigboy tmp]# service yum-updatesd stop [root@bigboy tmp]# service yum start [root@bigboy tmp]# service yum stop Note: Updating packages could cause programs written by you to stop functioning especially if they rely on the older version's features or syntax. The yum daemon will do updates automatically; the yum-updatesd daemon won't do this unless the yum-updatesd.conf file has been updated as shown here: # # File: /etc/yum/yum-updatesd.conf # [main] do_update = yes Creating Your Own yum Server An obvious advantage of using yum is that you can use it to update a yum server at your office with the same directory structure of the mirror download sites on the Fedora Web site. The full set of steps to do this is beyond the scope of this book, but there are some factors you should consider before doing this. A small desktop PC with about five to six gigabytes of free disk space per distribution should be sufficient to start with for a dedicated small business yum server. Large RPMs are about twenty-five megabytes in size, and they are updated infrequently, so your network load should be minimal on average with an update once or twice a week per server. In large server farms you may want to use a more robust system that can handle many more clients, but before doing so, get trend data for its network load to help your final decision. When established, you can then configure all your Fedora servers to use this local yum server for all updates which will significantly reduce your Internet congestion and the associated bandwidth costs. Note: When setting up an HTTP based yum server, you'll need to enable the viewing of directory structures so that it will be easy for someone to use his or her Web browser to navigate down the directories to double check the location of the yum files. How to Automate yum

Annamalaiar College Of Engineering

Open Source Laboratory

As of Fedora Core 6 the yum daemon has been named yum-updatesd, whereas in the past it was just called yum. To get yum started, select the commands that match your OS version: 1) Use the chkconfig command to get yum configured to start at boot: [root@bigboy tmp]# chkconfig yum-updatesd on [root@bigboy tmp]# chkconfig yum on 2) Use the service command to instruct the /etc/init.d yum script to start/stop yum after booting [root@bigboy tmp]# service yum-updatesd start [root@bigboy tmp]# service yum-updatesd stop [root@bigboy tmp]# service yum start [root@bigboy tmp]# service yum stop Keeping Your System current with Yum You can make the installed RPM packages on your system up to date with the latest patches using the yum update command. When used without listing any packages afterwards, yum will attempt to update them all. The yum update package-name command updates only a particular RPM package. It is always advisable to use yum after installing Linux to make sure the latest versions of software are installed for the sake of improved security and functionality. Here is an example of output of what to expect with yum updating your system. [root@bigboy tmp]# yum update Gathering header information file(s) from server(s) Server: Fedora Core 2 - i386 - Base Server: Fedora Core 2 - i386 - Released Updates Finding updated packages Downloading needed headers Resolving dependencies Dependencies resolved I will do the following: [install: kernel 2.4.22-1.2166.nptl.i686] [update: samba-client 3.0.2-7.FC1.i386] [update: binutils 2.14.90.0.6-4.i386] ... ... ... Is this ok [y/N]: y Getting samba-client-3.0.2-7.FC1.i386.rpm samba-client-3.0.2-7.FC1. 100% |=========================| 128 kB ... ... ... Running test transaction: Test transaction complete, Success! glibc-common 100 % done 1/127

Annamalaiar College Of Engineering

Open Source Laboratory

glibc 100 % done 2/127 Stopping sshd:[ OK ] Starting sshd:[ OK ] bash 100 % done 3/127 mozilla-nspr 100 % done 4/127 sed 100 % done 5/127 ... ... ... Completing update for pango - 65/127 Completing update for samba-client Completing update for binutils - 66/127 - 67/127 ... ... ... Completing update for XFree86-font-utils - 127/127 Kernel Updated/Installed, checking for bootloader Grub found - making this kernel the default 05:01 Installed: Updated: kernel 2.4.22-1.2166.nptl.i686 pango 1.2.5-4.i386 samba-client 3.0.2-7.FC1.i386 binutils 2.14.90.0.6-4.i386 XFree86-Mesa-libGLU 4.3.0-55.i386 initscripts [root@bigboy tmp]# Note: If you don't want to be prompted to install the files use the yum with the -y switch. Example of a yum Package Installation Here is a sample installation of an individual package using yum. In this case the RPM installed is the net-snmp-utils package: [root@bigboy tmp]# yum -y install net-snmp-utils Repository updates-released already added, not adding again Repository base already added, not adding again Setting up Install Process Setting up Repo: base repomd.xml Setting up Repo: 100% |=========================| 1.1 kB 00:00

Annamalaiar College Of Engineering

Open Source Laboratory

updates-released repomd.xml 100% |=========================| 951 B 00:00 Reading repository metadata in from local files base : ############################################ 2622/2622 primary.xml.gz MD Read 100% |=========================| 88 kB 00:00 : ################################################## 229/229 updates-re: ################################################## 229/229 Resolving Dependencies --> Populating transaction set with selected packages. Please wait. ---> Package net-snmp-utils.i386 0:5.1.2-11 set to be installed --> Running transaction check Dependencies Resolved Transaction Listing: Install: net-snmp-utils.i386 0:5.1.2-11 Downloading Packages: net-snmp-utils-5.1.2-11.i 100% |===================| 6.2 MB Running Transaction Test Finished Transaction Test Transaction Test Succeeded Running Transaction Installing: net-snmp-utils 100 % done 1/1 Installed: net-snmp-utils.i386 0:5.1.2-11 Complete! [root@bigboy tmp]# Installing Software From DEB Files

00:48 Unlike the Redhat, Fedora and Centos versions of Linux that use RPM packages, the Debian and Ubuntu versions of Linux rely on packages in the DEB format. This section covers some of the most important topics required for you to master their use. How To Install DEBs Manually There are generally two ways to install DEB files manually. The first method is by using a file previously downloaded to your hard drive, and the other is to install the DEB from some sort of removable media such as a CD-ROM drive.

Annamalaiar College Of Engineering

Open Source Laboratory

Using Downloaded Files Download the DEBs (which usually have a file extension ending with .deb) into a temporary directory, such as /tmp. The next step is to issue the dpkg --install command to install the package. Here is an example of a typical DEB installation command to install the ndiswrapper utilities package: root@u-bigboy:~# dpkg --install ndiswrapper-utils_1.8-0ubuntu2_i386.deb Selecting previously deselected package ndiswrapper-utils. (Reading database ... 70221 files and directories currently installed.) Unpacking ndiswrapper-utils (from ndiswrapper-utils_1.8-0ubuntu2_i386.deb) ... Setting up ndiswrapper-utils (1.8-0ubuntu2) ... root@u-bigboy:~# Using CD-ROMs Installing DEB files from CDROM is similar to that with Fedora / Redhat. The difference is that the CDROM device name is /media/cdrom. The following procedure installs the ndiswrapper DEB that had previously been copied to a disk.: 1. Insert the CD-ROM, check the files in the /media/cdrom directory and then install the DEB. root@u-bigboy:/tmp# mount /media/cdrom -o unhide mount: block device /dev/hdc is write-protected, mounting read-only root@u-bigboy:/tmp# cd /media/cdrom root@u-bigboy:/media/cdrom# ls ndiswrapper-utils_1.8-ubuntu2_i386.deb root@u-bigboy:/media/cdrom# dpkg --install ndiswrapper-utils_1.8ubuntu2_i386.deb Selecting previously deselected package ndiswrapper-utils. (Reading database ... 70221 files and directories currently installed.) Unpacking ndiswrapper-utils (from ndiswrapper-utils_1.8-0ubuntu2_i386.deb) ... Setting up ndiswrapper-utils (1.8-0ubuntu2) ... root@u-bigboy:~# 2. When finished, eject the CD-ROM root@u-bigboy:/media/cdrom# cd /tmp root@u-bigboy:/tmp# umount /media/cdrom root@u-bigboy:/tmp# eject cdrom root@u-bigboy:/tmp# Note: Unlike the Fedora CD / DVD sets, Ubuntu Linux is distributed on a single CD / DVD. The Ubuntu installation process downloads any additional packages it may need on demand from the Internet. It is for this reason that you may find it easier to install Ubuntu software using the APT utility which automatically download and install most of the packages you desire. The APT utility is covered in a following section. DEB Installation Errors Sometimes the installation of DEB software doesn't go according to plan and you need to

Annamalaiar College Of Engineering

Open Source Laboratory

take corrective actions. This section shows you how to recover from some of the most common errors you'll encounter. Failed Dependencies As should be expected, packages often rely on the existence of other previously installed packages. This will sometimes result in dpkg installations failing with dependency problems errors which really mean that a prerequisite DEB needs to be installed. In the next example we're trying to install the mrtg-contrib package, but it needs the mrtg package to be installed first beforehand. root@u-bigboy:/tmp# dpkg --install mrtg-contrib_2.12.2-1_all.deb Selecting previously deselected package mrtg-contrib. (Reading database ... 70759 files and directories currently installed.) Unpacking mrtg-contrib (from mrtg-contrib_2.12.2-1_all.deb) ... dpkg: dependency problems prevent configuration of mrtg-contrib: mrtg-contrib depends on mrtg (= 2.12.2-1); however: Package mrtg is not installed. dpkg: error processing mrtg-contrib (--install): dependency problems - leaving unconfigured Errors were encountered while processing: mrtg-contrib root@u-bigboy:/tmp# After installing the mrtg package, mrtg-contrib was installed correctly. You can automatically install prerequisite packages using the APT utility. This will be covered later in th echapter. How to List Installed DEBs The dpkg --list command will list all the packages installed on your system root@u-bigboy:~# dpkg --list Desired=Unknown/Install/Remove/Purge/Hold | Status=Not/Installed/Config-files/Unpacked/Failed-config/Half-installed |/ Err?=(none)/Hold/Reinst-required/X=both-problems (Status,Err: uppercase=bad) ||/ Name Version Description +++-===================-=================================================== ii ssh 4.1p1-7ubuntu4 Secure shell client and server ... ... ... root@u-bigboy:~# The output will be in six columns. The fourth column lists the name of the package, the fifth

Annamalaiar College Of Engineering

Open Source Laboratory

states the package version, and the sixth and last provides a description. The first three columns are each only a single character wide and provide very specific information about the package as outlined in Table 6-3. Column Formatting for the dpkg command Desired State State (Col. 1) Error Current (Col. 2) State 3) u i r p h Description (Col. Unknown: The package has never been installed Installed: A privileged user has requested the installation of the

package Remove: A privileged user has requested the removal of the

package. Configuration files for the package most likely remain. Purge: A previously installed package has been removed.

Configuration files for the package have probably been removed. Hold: A privileged user has requested that the package remain at

Its current version with no automatic upgrades. n Not Installed: The package is not installed i Installed: The package is installed c Configuration Files Exist: Package was installed, but the configuration files exist. u Unpacked: Files have been unpacked, but not installed

Annamalaiar College Of Engineering

Open Source Laboratory

f Failed: Configuration of the package has failed. h Halt: The package installation failed to complete Enforced Hold: Package upgrade is on hold because another

h Dependent package with a user defined hold requires this package to remain not upgraded. r Reinstallation: The package is broken and requires a reinstallation. x The package is both broken and on enforced hold. You can specify the desired package in which you are interested after the --list option to get a listing specific to that package. Here we see a single listing for the openssh-server package using this method. root@u-bigboy:~# dpkg --list openssh-server Desired=Unknown/Install/Remove/Purge/Hold | Status=Not/Installed/Config-files/Unpacked/Failed-config/Half-installed |/ Err?=(none)/Hold/Reinst-required/X=both-problems (Status,Err: uppercase=bad) ||/ Name Version Description +++-===================-=========================================================== ii openssh-server 4.2p1-7ubuntu3 Secure shell server, an rshd replacement root@u-bigboy:~# You can also pipe the output of this command through the grep command if you are interested in only a specific package. In this example we are looking for all packages containing the string dhcp in the name. root@u-bigboy:~# dpkg --list | grep dhcp ii dhcp3-client 3.0.2-1ubuntu6 DHCP Client ii dhcp3-common 3.0.2-1ubuntu6 Common files - dhcp3* packages root@u-bigboy:~#

Annamalaiar College Of Engineering

Open Source Laboratory

Listing Files Associated with DEBs Sometimes you'll find yourself installing software that terminates with an error requesting the presence of a particular file. In many cases the installation program doesn't state the DEB package in which the file can be found. It is therefore important to be able to determine the origin of certain files, by listing the contents for DEBs in which you suspect the files might reside. Listing Files for Previously Installed DEBs As stated previously, listing the files found in a package can be very useful. With dpkg, the -listiles option can provide this information easily. Here we list the files present in the openssh-server package. root@u-bigboy:~# dpkg --listfiles openssh-server ... ... ... /var/run/sshd /usr/lib/sftp-server /usr/share/doc/openssh-server root@u-bigboy:~# Listing Files in DEB Files Download sites often have packages with different functions, but similar names. It is good to be able to list the contents of a DEB package to verify you have the correct one. This can be done with the --contents option for dpkg as can be seen in this example. root@u-bigboy:/tmp# dpkg --contents openssh-server_4.2p1-7ubuntu3_i386.deb ... ... ... -rw-r--r-- root/root 10444 2006-05-17 17:43:19 ./usr/share/man/man8/sshd.8.gz -rw-r--r-- root/root 1169 2006-05-17 17:43:19 ./usr/share/man/man8/sftp-server.8.gz drwxr-xr-x root/root 0 2006-05-17 17:43:24 ./usr/share/doc/ drwxr-xr-x root/root 0 2006-05-17 17:43:24 ./usr/share/doc/opensshclient/ drwxr-xr-x root/root 0 2006-05-17 17:43:19 ./var/ drwxr-xr-x root/root 0 2006-05-17 17:43:19 ./var/run/ drwxr-xr-x root/root 0 2006-05-17 17:43:19 ./var/run/sshd/ ... ... ... root@u-bigboy:/tmp# Listing the DEB Package to Which a File Belongs

Annamalaiar College Of Engineering

Open Source Laboratory

Searching for the ownership of a particular file is also simple when using the --search option with dpkg. In this example, we see that the /etc/syslog.conf file is a part of the sysklogd package. root@u-bigboy:~# dpkg --search /etc/syslog.conf sysklogd: /etc/syslog.conf root@u-bigboy:~# Uninstalling DEBs The dpkg --remove command will erase an installed package as seen in this example. root@u-bigboy:~# dpkg --remove ndiswrapper-utils (Reading database ... 70241 files and directories currently installed.) Removing ndiswrapper-utils ... root@u-bigboy:~# Automatic DEB Updates with apt-get Like Fedora, Debian / Ubuntu Linux has its own package update application that will automatically retrieve packages from a network based repository. It is called the Advanced Package Tool (APT) and it is the most commonly used command is apt-get which we'll cover in more detail later Configuring APT APT uses the /etc/apt/sources.list file to instruct your server as to where to find the required packages on your network. The default file locations in this file refer to a few trusted APT download websites on the Internet. It is important to periodically resynchronize the APT package index files from the sources listed in the /etc/apt/sources.list file. This updates your system with listings of the most current package versions. This can be done with the apt-get update command as seen here: root@u-bigboy:/tmp# apt-get update Get:1 http://security.ubuntu.com dapper-security Release.gpg [189B] Get:2 http://us.archive.ubuntu.com dapper Release.gpg [189B] Get:3 http://us.archive.ubuntu.com dapper-updates Release.gpg [189B] ... ... ... Fetched 184kB in 2s (66.1kB/s) Reading package lists... Done root@u-bigboy:/tmp# Note: If you install Ubuntu without Internet access, only a barebones set of packages will be installed and the URL entries in the /etc/apt/sources.list file will be commented out, but the required packages will be flagged for eventual installation in the dpkg database. When you get Internet access, uncomment the URL entries and upgrade your installation with the aptget command which will update your system with the full complement of required packages downloaded from the Web. You can also create an APT server on your own network if you don't want all your Debian / Ubuntu servers to have Internet access. You'll have to update your sources.list file accordingly, but the full configuration steps are beyond the scope of this book.

Annamalaiar College Of Engineering

Open Source Laboratory

Keeping Your System current with APT The apt-get utility can be used to simultaneously upgrade all the packages on your system with the upgrade option. When used without listing any packages afterwards, apt-get will attempt to update them all. The apt-get upgrade package-name command updates only a particular DEB package. It is always advisable to use apt-get after installing Linux to make sure the latest versions of software are installed for the sake of improved security and functionality. Here is an example of output of what to expect; the -y flag causes apt-get to assume "yes" as the answer to all prompts and allows it to run non-interactively: root@u-bigboy:/tmp# apt-get -y upgrade Reading package lists... Done Building dependency tree... Done The following packages have been kept back: linux-image-386 The following packages will be upgraded: capplets-data desktop-file-utils eog gdm gnome-about ... ... ... Setting up libgtk2.0-bin (2.8.18-0ubuntu1) ... Updating the IM modules list for GTK+-2.4.0...done. Updating the gdk-pixbuf loaders list for GTK+-2.4.0...done. root@u-bigboy:/tmp# Example of an apt-get Package Installation Here is a sample installation of an individual package using yum. In this case the RPM installed is the apache Web server package: [root@ root@u-bigboy:/tmp# apt-get -y install apache Reading package lists... Done Building dependency tree... Done The following extra packages will be installed: apache-common apache2-utils libapr0 libpcre3 Suggested packages: apache-doc apache-ssl apache-perl The following NEW packages will be installed: apache apache-common apache2-utils libapr0 libpcre3 ... ... ... Creating config file /etc/apache/httpd.conf with new version Creating config file /etc/apache/srm.conf with new version Creating config file /etc/apache/access.conf with new version Creating config file /etc/apache/modules.conf with new version * Starting apache 1.3 web server...

Annamalaiar College Of Engineering

Open Source Laboratory

...done. root@u-bigboy:/tmp# Remember The Following APT Facts The APT utility's sources.list file primarily lists URLs using TCP port 80 (http://) for its updates This will have importance for your firewall rules. More details on configuring yum can be obtained by running the man sources.list and the man aptget commands. Installing Software Using tar Files Another popular software installation file format is the tar file, which can frequently be obtained from the Web sites of software developers, and online software libraries such as www.sourceforge.net. The Linux tar command is used to archive files and typically have a .tar file extension in the file name. These files are also frequently compressed in the gzip format, and when they do, their file extensions will end with .tar.gz or .tgz. The commands to extract the data from either type are similar. When a tar file is uncompressed, the command to extract the data is tar -xvf filename.tar. When the archive is compressed, the command to use is tar -xzvf filename.tar.gz. The tar file installation process usually requires you first to uncompress and extract the contents of the archive in a local subdirectory, which frequently has the same name as the tar file. The subdirectory will usually contain a file called README or INSTALL, which outlines all the customized steps to install the software. Here are the initial steps to take to install tar-based software: 1) Issue the tar command to extract the files. [root@bigboy tmp]# tar -xvzf linux-software-1.3.1.tar.gz linux-software-1.3.1/ linux-software-1.3.1/plugins-scripts/ ... ... ... linux-software-1.3.1/linux-software-plugins.spec [root@bigboy tmp]# This creates a subdirectory with the installation files inside. [root@bigboy tmp]# ls linux-software-1.3.1 linux-software-1.3.1.tar.gz [root@bigboy tmp]# 2) Use the cd command to enter the subdirectory and follow the directions listed in the INSTALL and README files: [root@bigboy tmp]# cd linux-software-1.3.1 [root@bigboy linux-software-1.3.1]# ls COPYING install-sh missing plugins

Annamalaiar College Of Engineering

Open Source Laboratory

depcomp LEGAL mkinstalldirs plugins-scripts FAQ lib linux-software.spec README Helper.pm Makefile.am linux-software.spec.in REQUIREMENTS INSTALL Makefile.in NEWS subst.in [root@bigboy linux-software-1.3.1]# Software installation with tar files can be frustrating, frequently requiring the installation of other supporting tar files, each with its own customized installation commands. RPMs, with the single standardized command format, are usually easier to use and may be the better method to use for newer Linux users. Installing Perl Modules Even if you don't know how to program in Perl, you may find yourself having to install Perl modules to get some of your software packages to work. Modules can be installed manually by downloading the TAR files from www.cpan.org, the primary Perl module site. The disadvantage is that this method doesn't automatically install any prerequisite modules you may need. Another disadvantage, though small is that the perl module names usually have a double colon (::) in their names, but the installation TAR file in which this module resides won't have the colons in its name. For example version 1.74 of the Mail::Tools module has the file name MailTools-1.74.tar.gz. Modules can also be installed automatically using the perl command. We will cover both methods in this section. Manual Installation of Perl Modules Most of the commonly used Perl modules can be downloaded from the CPAN website. The installation steps are straightforward. 1. Browse the CPAN website, identify the module package you need and then download it using a utility such as wget. [root@bigboy tmp]# wget http://www.cpan.org/authors/id/M/MA/MARKOV/MailTools-1.74.tar.gz --15:07:36-http://www.cpan.org/authors/id/M/MA/MARKOV/MailTools1.74.tar.gz => `MailTools-1.74.tar.gz' Resolving www.cpan.org... 66.39.76.93 Connecting to www.cpan.org|66.39.76.93|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 47,783 (47K) [application/x-tar] 100%[===================================>] 47,783 100.88K/s 15:07:38 (100.51 KB/s) - `MailTools-1.74.tar.gz' saved [47783/47783] [root@bigboy tmp]# 2. Extract the file from the package with the tar command. [root@bigboy tmp]# tar -xzvf MailTools-1.74.tar.gz MailTools-1.74/ MailTools-1.74/t/

Annamalaiar College Of Engineering

Open Source Laboratory

... ... ... MailTools-1.74/ChangeLog MailTools-1.74/MANIFEST [root@bigboy tmp]# 3. Enter the newly created directory with the same name as the TAR file, and install the module with the following commands. perl Makefile.PL make make test [root@bigboy tmp]# cd MailTools-1.74 [root@bigboy MailTools-1.74]# perl Makefile.PL Checking for Net::SMTP...ok Checking for Net::Domain...ok Checking for IO::Handle...ok Checking if your kit is complete... Looks good Writing Makefile for Mail [root@bigboy MailTools-1.74]# make cp Mail/Cap.pm blib/lib/Mail/Cap.pm cp Mail/Mailer/rfc822.pm blib/lib/Mail/Mailer/rfc822.pm ... ... ... Manifying blib/man3/Mail::Util.3pm Manifying blib/man3/Mail::Address.3pm [root@bigboy MailTools-1.74]# make test PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t t/extract.....ok ... ... ... All tests successful. Files=7, Tests=95, 2 wallclock secs ( 1.28 cusr + 0.29 csys = 1.57 CPU) [root@bigboy MailTools-1.74]# Your Perl module installation should now be complete. Automatic Installation of Perl Modules Modules can be installed automatically using the perl utility but you must first install the

Annamalaiar College Of Engineering

Open Source Laboratory

prerequisite ncftp and perl-CPAN package to download the packages from CPAN. [root@bigboy tmp]# yum -y install ncftp perl-CPAN After the package installed you can use the following perl command to enter the CPAN utility. perl -MCPAN -e shell B The first time it is run, Perl will prompt you for a number of configuration options. In most cases the defaults will be sufficient. After the initial setup is complete you will have a cpan> command prompt cpan> Installation of modules can then be done with the install command followed by the name of the module. In this example we install the Mail::Audit module using the CPAN utility. [root@bigboy tmp]# perl -MCPAN -e shell Terminal does not support AddHistory. cpan shell -- CPAN exploration and modules installation (v1.7602) ReadLine support available (try 'install Bundle::CPAN') cpan> install Mail::Audit CPAN: Storable loaded ok LWP not available CPAN: Net::FTP loaded ok Fetching with Net::FTP: ftp://archive.progeny.com/CPAN/authors/01mailrc.txt.gz ... ... ... Installing /usr/share/man/man3/Mail::Audit::MAPS.3pm Appending installation info to /usr/lib/perl5/5.8.8/i386-linux-threadmulti/perllocal.pod /usr/bin/make install -- OK cpan> exit Terminal does not support GetHistory. Lockfile removed. [root@bigboy tmp]# The exit command allows you to return to the Linux command prompt and your Perl module should be fully installed.

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

RESULT: Thus the repository data and repository configuration files for the downloaded packages are created successfully.

Annamalaiar College Of Engineering

Open Source Laboratory

Ex. No. 05 Date :

INSTALLATION OF SOFTWARE PACKAGES

Install samba and share files to windows Install Common UNIX Printing System (CUPS) Aim: To install various software packages in Open Source Operating System. Procedure: Background In the beginning systems administrators and users have to install new applications and utilities in Linux by compiling them from source. Compiling software and installing them from source has lot of draw backs. Some of them are listed below: 1. The user/administrator has to install necessary dependent libraries and other helper software before actually compiling and installing the application from source. 2. It is difficult to keep track the software installed on a system. 3. It is difficult to remove the software once installed from the source. 4. It is difficult to keep them updated. Enter packages and package management. The biggest advantage of package is, it knows the steps needed to install/uninstall itself on your system. What used to be a painful manual process is now a straightforward procedure. What used to be a mass of 20,000 files becomes a couple hundred packages. A package manager keep tracks of the packages installed. It also keep tracks of what is inside a package. For example the following command lists the files installed by a particular package (in our case the kernel) on your system, ------------------rpm -qil kernel ------------------Package is a prebuilt opensource component. Normally 'package maintainer' of an application creates the package. If you are curious about how to create a package have a look at http://fedoraproject.org/wiki/PackageMaintainers/CreatingPackageHowTo. Once the package is created, it is published to centralized location called 'repository'. Repositories hold collection of packages and their metadata (metadata holds data about the packages available). There are numerous package managers available for Linux systems. Several of the package managers offer graphical front-ends, contain search capabilities, allow updates to be installed from remote locations, and provide E-mail notifications when new packages are available. One package manager that provides all of these capabilities is YUM _(YellowDog Updater Modified)__. This manual will provide an introduction to package management with

Annamalaiar College Of Engineering

Open Source Laboratory

yum. Installing software using yum Before installing software using yum, 1. Make sure that your internet/network connection is working 2. If you are behind a proxy server, add __proxy=http://IPAddress:Port__ at the end of yum configuration file __/etc/yum.conf__ 3. Make sure that you have appropriate permission to install the package (ask your system administrator) Enough talk, lets install a package. Enter the following command, -------------------------------yum install sl -------------------------------Press 'y' when the command asks your confirmation, The output of the command should be ------------------------------[root@gnubox lab-manual]# yum install sl Loaded plugins: presto, refresh-packagekit Setting up Install Process Resolving Dependencies --> Running transaction check ---> Package sl.i686 0:3.03-9.fc12 set to be installed --> Finished Dependency Resolution Dependencies Resolved ================================================================== ==== Package Arch Version Repository ================================================================== ==== Installing: sl i686 3.03-9.fc12 fedora Transaction Summary ================================================================== ===== Install 1 Package(s) Total size: 11 k Installed size: 11 k Is this ok [y/N]: y Downloading Packages: Running rpm_check_debug Running Transaction Test Transaction Test Succeeded Running Transaction Installing : sl-3.03-9.fc12.i686 1/1 Installed:

Annamalaiar College Of Engineering

Open Source Laboratory

sl.i686 0:3.03-9.fc12 Complete! ---------------------------After installing the package, check whether the it is working my typing 'sl' == Uninstall a package Lets try removing the package, -------------------------yum -y remove sl ------------------------Note the '-y' option in the command, it instructs the 'yum' to assume 'yes'(y) to all the questions, You don't have to press the 'y' key. --------------------------------[root@gnubox package-installation]# yum remove sl Loaded plugins: presto, refresh-packagekit Setting up Remove Process Resolving Dependencies --> Running transaction check ---> Package sl.i686 0:3.03-9.fc12 set to be erased --> Finished Dependency Resolution Dependencies Resolved ================================================================== =====Package Arch Version Repository ================================================================== =====Removing: sl i686 3.03-9.fc12 @fedora Transaction Summary ================================================================== =====Remove 1 Package(s) Installed size: 11 k Is this ok [y/N]: y Downloading Packages: Running rpm_check_debug Running Transaction Test Transaction Test Succeeded Running Transaction Erasing : sl-3.03-9.fc12.i686 Removed: sl.i686 0:3.03-9.fc12 Complete! [root@gnubox package-installation]# ------------------------------------------------If you closely look at the above output, you can infer that the package 'sl' belongs to repository 'fedora'.

Annamalaiar College Of Engineering

Open Source Laboratory

== Searching for a package Lets try searching for some games in linux, --------------------yum search game --------------------------------------------------------------[root@gnubox package-installation]# yum search game Loaded plugins: presto, refresh-packagekit ================================================================== ========== Matched: game ==================================================== kdegames.i686 : KDE Games kdegames3.i686 : KDE 3 Games not ported to KDE 4 kdegames-minimal.i686 : Minimal set of KDE Games tecnoballz.i686 : A Brick Busting game atanks.i686 : Remake of a classic DOS game "Scorched Earth" clanbomber.i686 : Lay bombs and Blast the other players of the field game using ClanLib puzzles.i686 : A collection of one-player puzzle games slingshot.noarch : A Newtonian strategy game abe.i686 : Scrolling, platform-jumping, ancient pyramid exploring game alienarena.i686 : Multiplayer retro sci-fi deathmatch game bsd-games.i686 : Collection of text-based games extremetuxracer.i686 : 3D racing game featuring Tux freeciv.i686 : A multi-player strategy game freecol.noarch : Turn-based multi-player strategy game <output snipped for brevity> ------------------------------------== Updating your system Updates keeps your software free from bugs and crashes. Lets try updating the packages using package manager yum. ---------------yum -y update ---------------== Lab excercises === Task 1 ==== Objective Make your media players play mp3 files by installing necessary gstreamer plugins ==== Installing gstreamer plugins .Step 1: Make sure rpmfusion-free, rpmfusion-nonfree repositories are enabled --------------------yum repolist enabled ---------------------

Annamalaiar College Of Engineering

Open Source Laboratory

Above command list's the enabled repositories on your system. ----------------------------------[root@gnubox zer0c00l]# yum repolist Loaded plugins: presto, refresh-packagekit repo id repo name Dropbox Dropbox Repository adobe-linux-i386 Adobe Systems Incorporated fedora Fedora 14 - i386 fedora-firefox4 Firefox 4 Web Browser google-chrome google-chrome livna rpm.livna.org for 14 - i386 remi Les RPM de remi pour Fedora 14 - i386 rpmfusion-free RPM Fusion for Fedora 14 - Free rpmfusion-free-updates RPM Fusion for Fedora 14 - Free - Updates rpmfusion-nonfree RPM Fusion for Fedora 14 - Nonfree rpmfusion-nonfree-updates RPM Fusion for Fedora 14 - Nonfree - Updates updates Fedora 14 - i386 - Updates repolist: 25,829 ------------------------------------Step 2: Enable rpmfusion repositories if they are not enabled ----------rpm -ivh http://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-releasestable.noarch.rpm rpm -ivh http://download1.rpmfusion.org/free/fedora/rpmfusion-free-releasestable.noarch.rpm ----------Step 3: Install necessary packages ------------yum -y install gstreamer-plugins-bad gstreamer-plugins-ugly xine-lib-extras-nonfree yum -y install xmms,xmms-mp3 ------------Step 4: Open an audio file and test the installation.

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

RESULT: Thus the various software packages in open source operating system are installed successfully

Annamalaiar College Of Engineering

Open Source Laboratory

Ex.No.06 Date :

WRITING USERSPACE DRIVERS USING FUSE

With FUSE it is possible to implement a fully functional filesystem in a userspace AIM: To mount and unmount a file system in a new directory. program. Features include: Simple library API Simple installation (no need to patch or recompile the kernel) Secure implementation Userspace - kernel interface is very efficient Usable by non privileged users Runs on Linux kernels 2.4.X and 2.6.X Has proven very stable over time FUSE was originally developed to support AVFS but it has since became a separate project. Now quite a few other projects are using it. Implementing a filesystem is simple, a hello world filesystem is less than a 100 lines long. Here's a sample session: ~/fuse/example$ mkdir /tmp/fuse ~/fuse/example$ ./hello /tmp/fuse ~/fuse/example$ ls -l /tmp/fuse total 0 -r--r--r-1 root root 13 Jan 1 1970 hello ~/fuse/example$ cat /tmp/fuse/hello Hello World! ~/fuse/example$ fusermount -u /tmp/fuse ~/fuse/example$ Installation Some projects include the whole FUSE package (for simpler installation). In other cases, FUSE must be installed first. The installation is simple, after unpacking enter: > ./configure > make > make install If this produces an error, please read on. The configure script will try to guess the location of the kernel source. In case this fails, it may be specified using the --with-kernel parameter. Building the kernel module needs a configured kernel source tree matching the running kernel. If you build your own kernel this is no problem. On the other hand if a precompiled kernel is used, the kernel headers used by

Annamalaiar College Of Engineering

Open Source Laboratory

the FUSE build process must first be prepared. There are two possibilities: 1. A package containing the kernel headers for the kernel binary is available in the distribution (e.g. on Debian it's the kernelheadersX.Y.Z package for kernelimageX.Y.Z) 2. The kernel source must be prepared: o Extract the kernel source to some directory o Copy the running kernel's config (usually found in /boot/configX.Y.Z) to .config at the top of the source tree o Run make prepare After installation, you can try out the filesystems in the example directory. To see what is happening try adding the -d option. This is the output produced by running cat /tmp/fuse/hello in another shell: ~/fuse/example> ./hello /tmp/fuse -d unique: 2, opcode: LOOKUP (1), ino: 1, insize: 26 LOOKUP /hello INO: 2 unique: 2, error: 0 (Success), outsize: 72 unique: 3, opcode: OPEN (14), ino: 2, insize: 24 unique: 3, error: 0 (Success), outsize: 8 unique: 4, opcode: READ (15), ino: 2, insize: 32 READ 4096 bytes from 0 READ 4096 bytes unique: 4, error: 0 (Success), outsize: 4104 unique: 0, opcode: RELEASE (18), ino: 2, insize: 24 More operations can be tried out with the fusexmp example filesystem. This just mirrors the root directory similarly to mount --bind / /mountpoint. This is not very useful in itself, but can be used as template for creating a new filesystem. By default FUSE filesystems run multi-threaded. This can be verified by entering the mountpoint recursively in the fusexmp filesystem. Multi-threaded operation can be disabled by adding the -s option. Some options can be passed to the FUSE kernel module and the library. See the output of fusexmp -h for the list of these options. The following figure shows the path of a filesystem call (e.g. stat) in the above hello world Example: The FUSE kernel module and the FUSE library communicate via a special file descriptor which is obtained by opening /dev/fuse. This file can be opened multiple times, and the obtained file descriptor is passed to the mount syscall, to match up the descriptor with the mounted filesystem.

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

RESULT: Thus the file system in a new directory is mounted and unmounted successfully.

Annamalaiar College Of Engineering

Open Source Laboratory

Ex. No. 07 Date : Aim:

GUI PROGRAMMING

To implement GUI Programming using GTK or QT in Open Source Operating System. Gambas : Visual Basic for Linux Gambas is a free software development enviroment based from basic interpreter and works just like visual basic in windows. With gambas, we can design GUI or a program by using QT or GTK+, SQL, PostgreSQL, Firebird, ODBC, and SQLLite database also to translate any 3D OpenGL application and web application CGI. Well, it surely has a ton of features. Installation Procedure Here is the latest gambas installation manual(v. 2.5): 1. Add a new repositories: Open System > Administration> Software Sources > Third-Party Software. Click the add button to add a new repositories and paste this following code: deb http://azores.linex.org/gambas-other/ hardy main 2. And than type: sudo apt-get install gambas or for the easy way, just click this link to install gambas. It almost all of the programming languange available in here. And it really look almost the same like VB in windows. Pre-requisites: To ensure that all tools required are installed. [fosslab@fosslab ~]$ rpm -qa qt-devel qt-devel-4.7.0-3.fc14.i686 [fosslab@fosslab ~]$ rpm -qa qt-demos qt-demos-4.7.0-3.fc14.i686 [fosslab@fosslab ~]$ rpm -qa qt-examples qt-examples-4.7.0-3.fc14.i686 A GUI Hello World Create a new directory for the program. [fosslab@fosslab ~]$mkdir qthello Go to the newly created directory. [fosslab@fosslab ~]$cd qthello [fosslab@fosslab qthello]$ create the file in the qthello directory. [fosslab@fosslab qthello]$gedit qthello.cpp Type the following code, save and close gedit #include <QApplication> #include <QPushButton> int main(int argc, char *argv[]) {

Annamalaiar College Of Engineering

Open Source Laboratory

QApplication app(argc, argv); QPushButton helloButton("Hello World"); helloButton.resize(80, 20); helloButton.show(); return app.exec(); } Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Once the file has been saved, use the following commands to compile and execute the program. [fosslab@fosslab qthello]$ qmake-qt4 -project [fosslab@fosslab qthello]$ qmake-qt4 [fosslab@fosslab qthello]$ make [fosslab@fosslab qthello]$ ./qthello Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in The output will be a window like this: Window with a Button Create a new directory for the program. [fosslab@fosslab ~]$mkdir qtbutton Go to the newly created directory. [fosslab@fosslab ~]$cd qtbutton [fosslab@fosslab qthello]$ create the file in the qthello directory. [fosslab@fosslab qthello]$gedit qtbutton.cpp Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Type the following code, save and close gedit #include <QtGui> int main(int argv, char **args) { QApplication app(argv, args); QTextEdit *textEdit = new QTextEdit; QPushButton *quitButton = new QPushButton("&Quit"); QObject::connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit())); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(textEdit); layout->addWidget(quitButton); QWidget window; window.setLayout(layout); window.show(); return app.exec(); } Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in

Annamalaiar College Of Engineering

Open Source Laboratory

once the file has been saved, use the following commands to compile and execute the program. [fosslab@fosslab qthello]$ qmake-qt4 -project [fosslab@fosslab qthello]$ qmake-qt4 [fosslab@fosslab qthello]$ make [fosslab@fosslab qthello]$ ./qtbutton The output will be a window like this: Using Layouts. Create a new directory for the program. [fosslab@fosslab ~]$mkdir qtlayout Go to the newly created directory. [fosslab@fosslab ~]$cd qtlayout [fosslab@fosslab qtlayout]$ create the file in the qtlayout directory. [fosslab@fosslab qtlayout]$gedit qtlayout.cpp Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Type the following code, save and close gedit //qtlayout.cpp #include <QtGui> int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget window; //Create a label an a single line text box QLabel *label = new QLabel("Name:"); QLineEdit *lineEdit = new QLineEdit(); //Create a layout. Add the label and the lineedit to it. QHBoxLayout *layout = new QHBoxLayout(); layout->addWidget(label); layout->addWidget(lineEdit); //Apply the layout to the main window. //Since the widgets are part of the layout, //they are now children of the window. window.setLayout(layout); window.setWindowTitle("Window layout"); window.show(); return app.exec(); } once the file has been saved, use the following commands to compile and execute the program. [fosslab@fosslab qtlayout]$ qmake-qt4 -project [fosslab@fosslab qtlayout]$ qmake-qt4 [fosslab@fosslab qtlayout]$ make [fosslab@fosslab qtlayout]$ ./qtlayout

Annamalaiar College Of Engineering

Open Source Laboratory

Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in The output will be a window like this: Signals and Slots This program demonstrates the use of signals and slots to make two widgets interact with each other. The entire application is divided into 3 files: 1. communicate.h 2. communicate.cpp 3. main.cpp Create a new directory for the program. [fosslab@fosslab ~]$mkdir qtsignals Go to the newly created directory. [fosslab@fosslab ~]$cd qtsignals [fosslab@fosslab qtsignals]$ create the communicate.h file in the qtsignals directory. [fosslab@fosslab qtsignals]$gedit qommunicate.h Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Type the following code and save gedit //communicate.h #include <QWidget> #include <QApplication> #include <QPushButton> #include <QLabel> class Communicate : public QWidget { //The Q_OBJECT macro causes the moc tool to initialise //code for signals and slots, run time type information //and dynamic property system Q_OBJECT public: Communicate(QWidget *parent = 0); //add a lot which allows widget communications private slots: void add(); private: QLabel *label; }; Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in create the communicate.cpp file in the qtsignals directory. [fosslab@fosslab qtsignals]$gedit qommunicate.cpp Type the following code and save gedit

Annamalaiar College Of Engineering

Open Source Laboratory

//communicate.cpp #include "communicate.h" #include <QDesktopWidget> Communicate::Communicate(QWidget *parent) : QWidget(parent) { resize(180, 140); QPushButton *plus = new QPushButton("+", this); plus->setGeometry(50, 40, 50, 30); label = new QLabel("0", this); label->setGeometry(120, 40, 20, 30); //Connect the clicked event of the button to //the add method of the class connect(plus, SIGNAL(clicked()), this, SLOT(add())); } void Communicate::add() { //Change the text displayed in the label int val = label->text().toInt(); val++; label->setText(QString::number(val)); } Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in create the main.cpp file in the qtsignals directory. [fosslab@fosslab qtsignals]$gedit main.cpp Type the following code and save gedit //main.cpp #include "communicate.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); Communicate window; window.setWindowTitle("Communicate"); window.show(); return app.exec(); } Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in To compile and execute the program. [fosslab@fosslab qtsignals]$ qmake-qt4 -project [fosslab@fosslab qtsignals]$ qmake-qt4 [fosslab@fosslab qtsignals]$ make [fosslab@fosslab qtsignals]$ ./qtsignals

Annamalaiar College Of Engineering

Open Source Laboratory

The output will be a window like this: Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Menus and Toolbars. This program will display a menu which can be used to close the program . The entire application is divided into 3 files: 1. mymenu.h 2. mymenu.cpp 3. main.cpp Create a new directory for the program. [fosslab@fosslab ~]$mkdir qtmenu Go to the newly created directory. [fosslab@fosslab ~]$cd qtmenu [fosslab@fosslab qtmenu]$ create the mymenu.h file in the qtmenu directory. [fosslab@fosslab qtmenu]$gedit mymenu.h Type the following code and save gedit //mymenu.h #include <QMainWindow> class MyMenu : public QMainWindow { public: MyMenu(QWidget *parent = 0); }; Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in create the mymenu.cpp file in the qtmenu directory. [fosslab@fosslab qtmenu]$gedit mymenu.cpp Type the following code and save gedit //mymenu.cpp #include "mymenu.h" #include <QMenu> #include <QMenuBar> #include <QApplication> MyMenu::MyMenu(QWidget *parent) : QMainWindow(parent) { //create the quit action object QAction *quit = new QAction("&Quit", this); //create the file menu QMenu *file; file = menuBar()->addMenu("&File"); //add the quit action to the new menu file->addAction(quit);

Annamalaiar College Of Engineering

Open Source Laboratory

//connect the triggered signal from the quit action menu //to the global quit method which closes the application connect(quit, SIGNAL(triggered()), qApp, SLOT(quit())); } Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in create the main.cpp file in the qtmenu directory. [fosslab@fosslab qtmenu]$gedit main.cpp Type the following code and close gedit //main.cpp #include "mymenu.h" #include <QDesktopWidget> #include <QApplication> int main(int argc, char *argv[]) { QApplication app(argc, argv); MyMenu window; window.setWindowTitle("My menu"); window.show(); return app.exec(); } Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in To compile and execute the program. [[fosslab@fosslab qtmenu]$ qmake-qt4 -project [fosslab@fosslab qtmenu]$ qmake-qt4 [fosslab@fosslab qtmenu]$ make [fosslab@fosslab qtmenu]$ ./qtmenu The output will be a window like this:

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

RESULT: Thus the GUI programming using GTK in open source operating system is implemented successfully

Annamalaiar College Of Engineering

Open Source Laboratory

Ex.No. 08 Date Aim : :

VERSION CONTROL SYSTEM SETUP AND USAGE

To setup a version control system for managing files using svn. The system should be able to track changes to the files/folders and a period of time and revert if necessary Description : In this exercise, we would be setting up version control using svn. We would create a repository and then access that repository over http. Briefly, we would be doing the following Install/setup svn repository Configure apache for mod_svn access. We would also password-protect svn access Check in code/files using svn commands Check out codes to another location Modify/commit codes Revert to an older version of the code Pre-requisite To ensure that all tools required are installed. [fosslab@fosslab ~]$ rpm -qa subversion subversion-1.6.12-3.fc14.i686 [fosslab@fosslab ~]$ rpm -qa mod_dav_svn [fosslab@fosslab ~]$ su Password: [root@fosslab fosslab]# yum install mod_dav_svn Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Disable SelLinux [root@fosslab fosslab]# vi /etc/selinux/config Change the lines containing SELINUX=enforcing as SELINUX=disabled Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in After making the above changes reboot your system. Configuration of the repository The following commands create the necessary folder structure for the repository [root@fosslab fosslab]# mkdir /svn [root@fosslab fosslab]# mkdir /svn/repos [root@fosslab fosslab]# cd /svn/repos/ [root@fosslab repos]# chown -R apache.apache ../repos [root@fosslab repos]# Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Now we need to initialize the svn structure and create a repository [root@fosslab repos]# svnadmin create svn-test

Annamalaiar College Of Engineering

Open Source Laboratory

Creation of a local area for code The purpose of this step is to have a staging area for code from where you would be doing some development. This code can then be committed to the svn Create the local folder structure [root@fosslab repos]# mkdir /home/fosslab/svn-test [root@fosslab repos]# cd /home/fosslab/svn-test/ [root@fosslab svn-test]# Create local directories as per requirement - This can be customized to suit your needs [root@fosslab svn-test]# mkdir configurations options main Edit any file as required and save [root@fosslab svn-test]# vi configurations/test.cfg Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Import of the code area onto svn Import the initial structure onto svn [root@fosslab svn-test]# svn import /home/fosslab/svn-test/ file:///svn/repos/svn-test/ -m "Intial Import" This imports the files/folders onto the repo with a log message of Initial Import For fixing the permissions of the newly committed repo to be accessible by apache [root@fosslab svn-test]# chown -R apache.apache /svn/repos Configuring Apache Edit subversion.conf at /etc/httpd/conf.d/subversion.conf and add the following lines [root@fosslab svn-test]# vi /etc/httpd/conf.d/subversion.conf <Location /repos> DAV svn SVNParentPath /svn/repos AuthType Basic AuthName "Subversion repos" AuthUserFile /etc/svn-auth-conf Require valid-user </Location> Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in The above line allow for a repo on /svn/repos to be accessible with a password contained in /etc/svn-auth- conf Restart apache to apply the changes [root@fosslab svn-test]# service httpd restart Stopping httpd: [ OK ] Starting httpd: [ OK ] [root@fosslab svn-test]# Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in configure password for authentication [root@fosslab svn-test]# htpasswd -cm /etc/svn-auth-conf user01

Annamalaiar College Of Engineering

Open Source Laboratory

New password: Re-type new password: Adding password for user user01 [root@fosslab svn-test]# Checkout the repo We can check out the repo into a third party area by doing the following steps [root@fosslab tmp]# svn --username=user01 co http://localhost/repos/svn-test / Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Editing and Committing [root@fosslab tmp]# cd /tmp/svn-test/ [root@fosslab svn-test]# ls configurations main options [root@fosslab svn-test]# vi configurations/test.cfg Committing the changes [root@fosslab svn-test]#svn commit -m "Added a line to testconf1.cfg." Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Adding/Deleting Items root@fosslab svn-test]# ls configurations main options [root@fosslab svn-test]# cd configurations/ [root@fosslab configurations]# cp /etc/yum.conf . [root@fosslab configurations]# svn commit -m "Added yum conf" Listing out all revisions. This step will give you all the checkpoints [root@fosslab configurations]# svn log http://localhost/repos/svn-test/ Reverting/checkout to revision 1 [root@fosslab configurations]#svn co -r 1 http://localhost:80/repos/svn-test/

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

RESULT: Thus the version control system using RCS for managing files is done successfully.

Annamalaiar College Of Engineering

Open Source Laboratory

Ex. No. 09 Date : Aim :

TEXT PROCESSING WITH PERL

To do some common text processing task using perl Description : Perl program is a text file. You can use any text editor to create the program. Normally following line will be the first line #! /usr/bin/perl This tells Linux to use /usr/bin/perl executable to interpret rest of the lines in the program. This line may vary depending on the location of perl binary. Sometimes it may be /usr/local/bin/perl or some other place. Commonly .pl extension is used, however you can write without extension also. Pre-requisites : Normally Perl is installed by default Linux Installation. [fosslab@fosslab ~]$ rpm -qa perl perl-5.12.2-136.fc14.i686 [fosslab@fosslab ~]$ The following packages are required to connect Perl with Mysql [fosslab@fosslab ~]$ rpm -qa perl-DBI perl-DBI-1.613-1.fc14.i686 [fosslab@fosslab ~]$ rpm -qa perl-DBD-MySQL perl-DBD-MySQL-4.017-1.fc14.i686 Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Create a new directory for Perl programs [fosslab@fosslab ~]$ mkdir perlprog [fosslab@fosslab ~]$ cd perlprog/ [fosslab@fosslab perlprog]$ 1. Sample PERL Program Create a new file using the gedit text editor [fosslab@fosslab perlprog]$gedit first.pl Type the following code, save and close gedit #!usr/bin/perl # the above line is shebang directive $name=<STDIN>; chomp($name); print "$name\n"; Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Now run the program as follows [fosslab@fosslab perlprog]$ perl first.pl This is my first perl program This is my first perl program

Annamalaiar College Of Engineering

Open Source Laboratory

[fosslab@fosslab perlprog]$ 2. Scalar variables in PERL fosslab@fosslab perlprog]$gedit scalar.pl Type the following code, save and close gedit #!/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"; Now run the program as follows [fosslab@fosslab perlprog]$ perl scalar.pl Camel 42243 3. Array in PERL fosslab@fosslab perlprog]$gedit array.pl Type the following code, save and close gedit #!usr/bin/perl my @animal=("cow","Buffalo","Camel"); print "@animal\n"; # list all elements in array print "$#animal\n"; # list last element position print "$animal[0]\n"; #list 0th position element $count=@animal; print "$count"; # count no of elements in array Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Now run the program as follows [fosslab@fosslab perlprog]$ perl array.pl cow Buffalo Camel 2 cow 3 4. Hash in PERL fosslab@fosslab perlprog]$gedit hash.pl Type the following code, save and close gedit #!usr/bin/perl %color=('apple'=>"red",'banana'=>"yellow",'orange'=>"orange"); print "$color{'apple'}\n"; Now run the program as follows [fosslab@fosslab perlprog]$ perl hash.pl red 5. To display all values in hash fosslab@fosslab perlprog]$gedit hashvalues.pl Type the following code, save and close gedit

Annamalaiar College Of Engineering

Open Source Laboratory

#!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"; } Now run the program as follows [fosslab@fosslab perlprog]$ perl hashvalues.pl red yellow red orange Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in 6. If loop in perl fosslab@fosslab perlprog]$gedit ifloop.pl Type the following code, save and close gedit #!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"; Now run the program as follows [fosslab@fosslab perlprog]$ perl ifloop.pl 10 100 10 Sample programs If not loop (unless)in perl #!usr/bin/perl $a=5; unless($a>10) #is equal to if not { print "a less than 10"; } While loop (until) in perl

Annamalaiar College Of Engineering

Open Source Laboratory

#!usr/bin/perl $a=0; until($a>10) #is equal to while { print "$a\n"; $a++; } Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in 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"; } 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"; Function #!usr/bin/perl sub sayHello() { print "Hello\n"; } &sayHello(); 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); Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Find Maximum value using function

Annamalaiar College Of Engineering

Open Source Laboratory

#!usr/bin/perl sub max() { $max=shift @_; # shift function remove the first element in array and the remaining element will be stored in $max foreach $v (@_) # $v is the second values in the @_ { $max=$v if $max<$v; } return $max; } $d=&max(10,278,1050,76,800,246,76,345); print "The maximum value is $d\n"; 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"; program to check greater among 3 number #Greatest among 3 number print "Enter A value : "; $a=<>; print "Enter b value : "; $b=<>; print "Enter c value : "; Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in $c=<>; if(($a > $b)&&($a > $c)) { print "A is greater"; } elsif(($b > $c)&&($b > $a)) { print "B is greater"; } else

Annamalaiar College Of Engineering

Open Source Laboratory

{ print "C is greater"; } Create the table in perl that will be automatically updated in database using mysql First create the database as follows in mysql [fosslab@fosslab ~]$ mysql -u root -p Enter password: mysql> Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in To view existing databases mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | test | +--------------------+ 3 rows in set (0.01 sec) mysql> Create a new database mysql>create database student; Query OK, 1 row affected (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 through PERL program we use the following procedure Open a new terminal [fosslab@fosslab ~]$ cd perlprog/ [fosslab@fosslab perlprog]$ gedit connect.pl Type the following code, save and close gedit #!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:$!");

Annamalaiar College Of Engineering

Open Source Laboratory

} Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in $sth=$dbh->prepare("create table students(rollno int,sname varchar(50))"); $sth->execute(); $dbh->disconnect; Now run the program as follows [fosslab@fosslab perlprog]$ perl connect.pl [fosslab@fosslab perlprog]$ Now the table is created. To view the table go back to the other terminal (which is already opened for mysql) mysql> show tables; +-------------------+ | Tables_in_student | +-------------------+ | students | +-------------------+ 1 row in set (0.00 sec) Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Insert the values in perl that will be automatically updated in database using mysql as follows [fosslab@fosslab perlprog]$ gedit dbinsert.pl Type the following code, save and close gedit #!usr/bin/perl use DBI; #to use the build in package we use "Use", DBI is the build in package in perl my $dbh=DBI->connect("dbi:mysql:student","root",""); #connect to database if(!$dbh) { die("error:$!"); } $sth=$dbh->prepare("insert into students values(100,'thamarai')"); # create the table $sth->execute(); $dbh->disconnect; Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Now run the program as follows [fosslab@fosslab perlprog]$ perl dbinsert.pl [fosslab@fosslab perlprog]$ Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Now the record is inserted. To view the record go back to the other terminal (which is already opened for mysql)

Annamalaiar College Of Engineering

Open Source Laboratory

mysql> select * from students; +--------+----------+ | rollno | sname +--------+----------+ | 100 | thamarai | +--------+----------+ 1 row in set (0.00 sec)

Annamalaiar College Of Engineering

Open Source Laboratory

RESULT: Thus the login page is created and connected with SQL server for providing authentication.

Annamalaiar College Of Engineering

Open Source Laboratory

Ex. No. 10 Date : Aim :

SIMPLE APPLICATIONS USING PHP

To do some simple PHP Programs Pre-requisites: To ensure that all packages required are installed. ( requires a web server,php and mysql ) [fosslab@fosslab ~]$ rpm -qa php php-5.3.3-1.fc14.i686 [fosslab@fosslab ~]$ rpm -qa mysql mysql-5.1.51-2.fc14.i686 [fosslab@fosslab ~]$ rpm -qa mysql-server mysql-server-5.1.51-2.fc14.i686 [fosslab@fosslab ~]$ Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Check mysql status [fosslab@fosslab ~]$ service mysqld status mysqld (pid 1759) is running... [fosslab@fosslab ~]$ Create all your programs in /var/www/html/ and the output can be viewed in a web browser Assign read,write and executable permission for /var/www/html [fosslab@fosslab ~]$ su Password: [root@fosslab fosslab]# chmod 777 /var/www/html [root@fosslab fosslab]# exit exit [fosslab@fosslab ~]$ 1.Simple Hello World [fosslab@fosslab ~]$ cd /var/www/html [fosslab@fosslab html]$ gedit hello.php Type the following code, save and close gedit <?php Print "Hello, World!"; ?> Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Now run the program as follows Open a Browser and type a url as http://localhost/hello.php 2.Concatenation Operator There is only one string operator in PHP. The concatenation operator (.) is used to put two string values together. To concatenate two string variables together, use the concatenation operator:

Annamalaiar College Of Engineering

Open Source Laboratory

[fosslab@fosslab html]$ gedit concate.php Type the following code, save and close gedit <?php $txt1="Hello World!"; $txt2="What a nice day!"; echo $txt1 . " " . $txt2; ?> Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Now run the program as follows Open a Browser and type a url as http://localhost/concate.php Login Form using PHP and MySQL: In any website generally it is mandatory to have a login form to keep your data secure. In this regard we need to have a table which keeps the user-id and respective password. First of all we need to create a database and table which will store the username and password. Login in to mysql [fosslab@fosslab ~]$ mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 3 Server version: 5.1.51 Source distribution Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. This software comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to modify and redistribute it under the GPL v2 license Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> Create a databsae mysql> create database userlist; Query OK, 1 row affected (0.02 sec) mysql> use userlist; Database changed mysql> create table user(username varchar(20),password varchar(20)); Query OK, 0 rows affected (0.08 sec) mysql> Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in After that we will store few data into it: mysql> insert into user values('user01','hello'); Query OK, 1 row affected (0.05 sec) mysql> insert into user values('user02','hello2'); Query OK, 1 row affected (0.00 sec) mysql>

Annamalaiar College Of Engineering

Open Source Laboratory

Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Now create a user login page [fosslab@fosslab html]$gedit userlogin.html Type the following HTML code, save and close gedit <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body > <form method="post" action="userlogin.php" > <table border="1" > <tr> <td> <B>User-Id</B> </td> <td><input type="text" name="userid"> </tr> <tr> <td><B>Password</B></td> <td><input name="password" type="password"></input></td> </tr> <tr> <td><input type="submit" value="Submit"/> <td><input type="reset" value="Reset"/> </tr> </table> </form> </body> </html> Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Now create a php program for mysql connectivity [fosslab@fosslab html]$gedit userlogin.php Type the following HTML code, save and close gedit <?php $f_usr= $_POST["userid"]; $f_pswd= $_POST["password"]; $con=mysql_connect("localhost","root",""); if(! $con) { die('Connection Failed'.mysql_error()); }

Annamalaiar College Of Engineering

Open Source Laboratory

mysql_select_db("userlist",$con); $result=mysql_query("select * from user where username='$f_usr' and password='$f_pswd'"); if(mysql_num_rows($result)==1) { echo "Welcome"; } else { echo "Please check your username and password"; } ?> Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Now run the program as follows Open a Browser and type a url as http://localhost/userlogin.html If the username and password both are correct then output will be: Welcome If any one of the field or both are incorrect then the output will be: Please check your username and password

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

RESULT: Thus the simple application using PHP is created and executed successfully.

Annamalaiar College Of Engineering

Open Source Laboratory

Ex. No.11 Date : Aim:-

SIMPLE APPLICATION USING PYTHON

To create and run simple application using Python with database connectivity. Procedure: The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard. Python Database API supports a wide range of database servers: GadFly mSQL MySQL PostgreSQL Microsoft SQL Server 2000 Informix Interbase Oracle Sybase The DB - API provides a minimal standard for working with databases, using Python structures and syntax wherever possible. This API includes the following: Importing the API module. Acquiring a connection with the database. Issuing SQL statements and stored procedures. Closing the connection MySQLdb: MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2.0, and is built on top of the MySQL C API. Installation of MySQLdb Before proceeding you make sure you have MySQLdb installed on your machine. Just type the following in your Python script and execute it: #!/usr/bin/python import MySQLdb If it produces following result then it means MySQLdb module is not installed: Traceback (most recent call last): File "test.py", line 3, in <module> import MySQLdb ImportError: No module named MySQLdb To install MySQLdb module, $ gunzip MySQL-python-1.2.2.tar.gz $ tar -xvf MySQL-python-1.2.2.tar $ cd MySQL-python-1.2.2 $ python setup.py build

Annamalaiar College Of Engineering

Open Source Laboratory

$ python setup.py install Note: Make sure you have root privilege to install above module. Database Connection: Before connecting to a MySQL database make sure followings: You have created a database TESTDB. You have created a table EMPLOYEE in TESTDB. This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME. User ID "testuser" and password "test123" are set to access TESTDB Python module MySQLdb is installed properly on your machine. Example: Following is the example of connecting with MySQL database "TESTDB" #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() # execute SQL query using execute() method. cursor.execute("SELECT VERSION()") # Fetch a single row using fetchone() method. data = cursor.fetchone() print "Database version : %s " % data # disconnect from server db.close() While running this script, its producing following result at my Linux machine. Database version : 5.0.45 If a connection is established with the datasource then a Connection Object is returned and saved into db for further use otherwise db is set to None. Next db object is used to create a cursor object which in turn is used to execute SQL queries. Finally before coming out it ensures that database connection is closed and resources are released. Creating Database Table: Once a database connection is established, we are ready to create tables or records into the database tables using execute method of the created cursor. Example: First let's create Database table EMPLOYEE: #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() # Drop table if it already exist using execute() method.

Annamalaiar College Of Engineering

Open Source Laboratory

cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") # Create table as per requirement sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )""" cursor.execute(sql) # disconnect from server db.close() INSERT Operation: INSERT operation is required when you want to create your records into a database table. Example: Following is the example which executes SQL INSERT statement to create a record into EMPLOYEE table. #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() # Prepare SQL query to INSERT a record into the database. sql = """INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)""" try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() # disconnect from server db.close() Above example can be written as follows to create SQL queries dynamically: #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method

Annamalaiar College Of Engineering

Open Source Laboratory

cursor = db.cursor() # Prepare SQL query to INSERT a record into the database. sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \ LAST_NAME, AGE, SEX, INCOME) \ VALUES ('%s', '%s', '%d', '%c', '%d' )" % \ ('Mac', 'Mohan', 20, 'M', 2000) try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() # disconnect from server db.close() Example: Following code segment is another form of execute where you can pass parameters directly: .................................. user_id = "test123" password = "password" con.execute('insert into Login values("%s", "%s")' % \ (user_id, password)) .................................. READ Operation: READ Operation on any databasse means to fetch some useful information from the database. Once our database connection is established, we are ready to make a query into this database. We can use either fetchone() method to fetch single record or fetchall method to fetech multiple values from a database table. fetchone(): This method fetches the next row of a query result set. A result set is an object that is returned when a cursor object is used to query a table. fetchall(): This method fetches all the rows in a result set. If some rows have already been extracted from the result set, the fetchall() method retrieves the remaining rows from the result set. rowcount: This is a read-only attribute and returns the number of rows that were affected by an execute() method. Example: Following is the procedure to query all the records from EMPLOYEE table having salary more than 1000.

Annamalaiar College Of Engineering

Open Source Laboratory

#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() # Prepare SQL query to INSERT a record into the database. sql = "SELECT * FROM EMPLOYEE \ WHERE INCOME > '%d'" % (1000) try: # Execute the SQL command cursor.execute(sql) # Fetch all the rows in a list of lists. results = cursor.fetchall() for row in results: fname = row[0] lname = row[1] age = row[2] sex = row[3] income = row[4] # Now print fetched result print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \ (fname, lname, age, sex, income ) except: print "Error: unable to fecth data" # disconnect from server db.close() This will produce following result: fname=Mac, lname=Mohan, age=20, sex=M, income=2000 Update Operation: UPDATE Operation on any databasse means to update one or more records which are already available in the database. Following is the procedure to update all the records having SEX as 'M'. Here we will increase AGE of all the males by one year. Example: #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() # Prepare SQL query to UPDATE required records sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')

Annamalaiar College Of Engineering

Open Source Laboratory

try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() # disconnect from server db.close() DELETE Operation: DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20. Example: #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() # Prepare SQL query to DELETE required records sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20) try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() # disconnect from server db.close() Performing Transactions: Transactions are a mechanism that ensures data consistency. Transactions should have the following four properties: Atomicity: Either a transaction completes or nothing happens at all. Consistency: A transaction must start in a consistent state and leave the system is a consistent state. Isolation: Intermediate results of a transaction are not visible outside the current transaction. Durability: Once a transaction was committed, the effects are persistent, even after a system failure.

Annamalaiar College Of Engineering

Open Source Laboratory

The Python DB API 2.0 provides two methods to either commit or rollback a transaction. COMMIT Operation: Commit is the operation which gives a green signal to database to finalize the changes and after this operation no change can be reverted back. Here is a simple example to call commit method. db.commit() ROLLBACK Operation: If you are not satisfied with one or more of the changes and you want to revert back those changes completely then use rollback method. Here is a simple example to call rollback metho. db.rollback() Disconnecting Database: To disconnect Database connection, use close() method. db.close() If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB. However, instead of depending on any of DB lower level implementation details, your application would be better off calling commit or rollback explicitly. Handling Errors: There are many sources of errors. A few examples are a syntax error in an executed SQL statement, a connection failure, or calling the fetch method for an already canceled or finished statement handle. The DB API defines a number of errors that must exist in each database module. The following table lists these exceptions. Exception Description Warning Used for non-fatal issues. Must subclass StandardError. Error Base class for errors. Must subclass StandardError. InterfaceError Used for errors in the database module, not the database itself. Must subclass Error. DatabaseError Used for errors in the database. Must subclass Error. DataError Subclass of DatabaseError that refers to errors in the data. OperationalError Subclass of DatabaseError that refers to errors such as the loss of a connection to the database. These errors are generally outside of the control of the Python scripter. IntegrityError Subclass of DatabaseError for situations that would damage the relational integrity, such as uniqueness constraints or foreign keys. InternalError Subclass of DatabaseError that refers to errors internal to the database module, such as a cursor no longer being active.

Annamalaiar College Of Engineering

Open Source Laboratory

ProgrammingError Subclass of DatabaseError that refers to errors such as a bad table name and other things that can safely be blamed on you. NotSupportedError Subclass of DatabaseError that refers to trying to call unsupported functionality. Your Python scripts should handle these errors but before using any of the above exceptions, make sure your MySQLdb has support for that exception. You can get more information about them by reading the DB API 2.0 specification. PROGRAM CODE: import sys import MySQLdb #connect conn = MySQLdb.connect(host="localhost",user="root",passwd="home",db="address_book ") #create a cursor cursor = conn.cursor() #Add Records def Add(): var = True while var: ssn = raw_input("Enter SSN number:") name = raw_input("Enter a Name:") address = raw_input("Enter the Address:") city = raw_input("Enter the City:") state= raw_input("Enter the State:") postcode = raw_input("Enter the Postcode:")

country = raw_input("Enter the country:") cursor.execute(""" insert into addresses (ssn,name,address,city,state,postcode,country) values (%s,%s,%s,%s,%s,%s,%s)""",(ssn,name,address,city,state,postcode,country)) print "Add Another Record y/n" enter = raw_input("Enter the option:") if enter == 'y': var = True else: var = False #Modify Records def Modify(): ssn = raw_input("Enter the old ssn number to update:")

Annamalaiar College Of Engineering

Open Source Laboratory

newssn = raw_input("Enter the new ssn number:") cursor.execute(""" update addresses set ssn = %s where ssn = %s""",(newssn,ssn)) #Delete records def Delete(): ssn = raw_input("Enter the ssn record to be deleted:") cursor.execute(""" delete from addresses where ssn=%s""",ssn) #View Records def List(): print 'List the Records' cursor.execute("select * from addresses") result = cursor.fetchall() for record in result: print record[0],"-->",record[1],"-->",record[2],"->",record[3],"-->",record[4],"-->",record[5],"-->",record[6] def Exit(): sys.exit() def printToConsole(): while True: print '1.Add Record' print '2.Modify Record' print '3.Delete Record' print '4.List Record' print '5.Exit' option = int(raw_input('Enter the Option :')) if option == 1: Add() elif option == 2: Modify() elif option == 3: Delete() elif option == 4: List() elif option == 5: Exit() printToConsole()

Annamalaiar College Of Engineering

Open Source Laboratory

RESULT: Thus the simple application using python with database connectivity is created and executed successfully.

Annamalaiar College Of Engineering

Open Source Laboratory

Ex. No.12 Date : Aim :

SETTING UP THE NETWORK INTERFACE

To setup Network Interface using ifconfig command and the related system files Setting up Network Interfaces To see how your network is configured on your computer, use the ifconfig command. Note that this command is in the /sbin directory and this directory is not in normal users's path and only in root's path. So, as normal user, you will have to use "/sbin/ifconfig" command on the command prompt. As root just using "ifconfig" will do. Here is an example output if this command is used as a normal user: [fosslab@fosslab ~]$ /sbin/ifconfig Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in [fosslab@fosslab ~]$ su Password: [root@fosslab fosslab]# ifconfig Static IP addresses are manually assigned to a computer by an administrator. The exact procedure varies according to platform. This contrasts with dynamic IP addresses, which are assigned either by the computer interface or host software itself, as in Zeroconf, or assigned by a server using Dynamic Host Configuration Protocol (DHCP). Assigning IP Address,Netmask and gateway using ifconfig command IP address : 192.168.1.100 (An unused IP) netmask : 255.255.255.0 IP address of the default gateway : 192.168.1.1 [fosslab@fosslab ~]$ su Password: [root@fosslab fosslab]# mii-tool eth0: negotiated 100baseTx-FD flow-control, link ok To Assign IP address and netmask [root@fosslab fosslab]# ifconfig eth0 192.168.1.100 netmask 255.255.255.0 [root@fosslab fosslab]# Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in [root@fosslab fosslab]# ifconfig To Assign gateway [root@fosslab fosslab]# route add default gw 192.168.1.1 [root@fosslab fosslab]# route -n Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in

Annamalaiar College Of Engineering

Open Source Laboratory

These settings are not permanent. It's go away the next time you boot. For permanent setting use the following steps. [root@fosslab fosslab]# vi /etc/sysconfig/network-scripts/ifcfg-eth0 Change the values as shown below and save [root@fosslab fosslab]# service network restart Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in [root@fosslab fosslab]#ifconfig [root@fosslab fosslab]# route -n Leenux Technologies , 1st Floor, Almarkz Complex, 222 Arcot Road, Kodambakkam, Chennai 24. www.leenux.in Managing iptables [root@fosslab fosslab]#service iptables start [root@fosslab fosslab]#service iptables stop [root@fosslab fosslab]#service iptables restart

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

Annamalaiar College Of Engineering

Open Source Laboratory

RESULT: Thus the complete network interface using ifconfig command like gateway, DNS, IP tables, etc is done successfully.

Annamalaiar College Of Engineering