Você está na página 1de 62

NETW235

Consolidated Mini-Labs

Task 1:: VMware => Ubuntu installation


Select START programs from local Desktop/Laptop to start VMware workstation:: => Programs => Technology => VMware => VMware Workstation => New Workstation => Create on D: drive => Use max of 40GB => VM/Menu =>send CTRL+ALT+DEL H/w minimum requirements => Intel Pentium 4, 1 GHz, 512 MB, 5 GB Disk Installation Steps => Load disk on DVD drive => Select English => Select Install Ubuntu => .... => Welcome Page => Select English => Preparing to install Ubuntu => Un-Check " " " - Download updates while installing => Un-Check " - Third party software => Allocate drive space => Check - Default - Install on VMware => Create File system partitions => SWAP Partition SWAP 2000 MB => root / Partition EXT4 8000 MB => /home partition" EXT4 30000 MB

NETW235

NETW235

Consolidated Mini-Labs

Provide Credential info & config


=> Where are You? " => Select New York from Glob map => Select USA Keyboard => Enter Who are you info? => username (root/super user) " => passwd => Welcome " => Calculating file to skip copying " => Copying files .....

Verify Install completion.

NETW235

NETW235

Consolidated Mini-Labs

Task 2:: User management 1) Start VM Ubantu Server and Switch to a root login $ sudo -s <password>

User info

The id command prints information for a certain user $ id <username>

Create a user

$ useradd -c A test user <username> $ man useradd Batch user/NoLogin user creation:: $ useradd -c Batch user 1 -s /sbin/nologin <username> [ Check out options ]

Change the users password


$ passwd <username>

Create a new group


$ groupadd <group name>

Add a user to a group


$ usermod -a -G <group123> <username>

NETW235

NETW235

Consolidated Mini-Labs

Remove a user from a group

Removing a user from a group is a bit trickier. Unfortunately, there is no direct command, use exclusion!! First get group listing for the user and re-define groups with exclusion of group to be removed. $ id -nG <username> Result:: group1, group2, group3, group4 To remove <username> from group2, execute the following $ usermod <username> -G group1,group3,group4

Lock and Unlock user accounts


$ usermod -L <username> $ usermod -U <username>

Delete a user

$ userdel -r <username> The -r option is used then the users home directory and mail spool are also deleted.

Change a groups name Delete a group

$ groupmod -n <NEW grp name> <grp name>

$ groupdel <group name>

NETW235

NETW235

Consolidated Mini-Labs

Task 3:: Basic commands

cat
This is one of the most exible Unix commands. We can use to create, view and concatenate les. For our rst example we create a three-item English-Spanish dictionary in a le called "dict."
$ cat >dict red rojo green verde blue azul <control-D> $

<control-D> stands for "hold the control key down, then tap 'd'". The symbol > tells the computer that what is typed is to be put into the le dict. To view a le we use cat in a different way:
$ cat dict red rojo green verde blue azul $

If we wish to add text to an existing le we do this:


$ cat >>dict white blanco black negro <control-D> $

Now suppose that we have another le tmp that looks like this:
$ cat tmp cat gato dog perro $

NETW235

NETW235

Consolidated Mini-Labs

Then we can join dict and tmp like this:


$ cat dict tmp >dict2

We could check the number of lines in the new le like this:


$ wc -l dict2 8

The command wc counts things --- the number of characters, words, and line in a le.

chmod
This command is used to change the permissions of a le or directory. For example to make a le essay.001 readable by everyone, we do this:
$ chmod a+r essay.001

To make a le, e.g., a shell script mycommand executable, we do this


$ chmod +x mycommand Now we can run mycommand

as a command. To check the permissions of a le, use ls -l . For more information on chmod, use man chmod.

cd
Use cd to change directory. Use pwd to see what directory you are in.
$ $ $ $ cd english pwd /u/ma/jeremy/english ls novel poems

NETW235

NETW235
$ $ $ $

Consolidated Mini-Labs

cd novel pwd /u/ma/jeremy/english/novel ls ch1 ch2 ch3 journal scrapbook

$ cd .. $ pwd $ /u/ma/jeremy/english $ cd poems $ cd $ /u/ma/jeremy

Jeremy began in his home directory, then went to his english subdirectory. He listed this directory using ls , found that it contained two entries, both of which happen to be diretories. He cd'd to the diretory novel, and found that he had gotten only as far as chapter 3 in his writing. Then he used cd .. to jump back one level. If had wanted to jump back one level, then go to poems he could have said cd ../poems. Finally he used cd with no argument to jump back to his home directory.

cp
Use cp to copy les or directories.
$ cp foo foo.2

This makes a copy of the le foo.


$ cp ~/poems/jabber .

This copies the le jabber in the directory poems to the current directory. The symbol "." stands for the current directory. The symbol "~" stands for the home directory.

NETW235

NETW235

Consolidated Mini-Labs

date
Use this command to check the date and time.
$ date Fri Jan 6 08:52:42 MST 1995

echo
The echo command echoes its arguments. Here are some examples:
$ echo this this $ echo $EDITOR /usr/local/bin/emacs $ echo $PRINTER b129lab1 Things like PRINTER are so-called

environment variables. This one stores the name of the default printer --- the one that print jobs will go to unless you take some action to change things. The dollar sign before an environment variable is needed to get the value in the variable. Try the following to verify this:
$ echo PRINTER PRINTER

NETW235

NETW235

Consolidated Mini-Labs

grep
Use this command to search for information in a le or les. For example, suppose that we have a le dict whose contents are
red rojo green verde blue azul white blanco black negro

Then we can look up items in our le like this;


$ grep red dict red rojo $ grep blanco dict white blanco $ grep brown dict $

Notice that no output was returned by grep brown. This is because "brown" is not in our dictionary le. Grep can also be combined with other commands. For example, if one had a le of phone numbers named "ph", one entry per line, then the following command would give an alphabetical list of all persons whose name contains the string "Fred".
$ grep Fred ph | sort Alpha, Fred: 333-6565 Beta, Freddie: 656-0099 Frederickson, Molly: 444-0981 Gamma, Fred-George: 111-7676 Zeta, Frederick: 431-0987

The symbol "|" is called "pipe." It pipes the output of the grep command into the input of the sort command. For more information on grep, consult
$ man grep
NETW235

NETW235

Consolidated Mini-Labs

head
Use this command to look at the head of a le. For example,
$ head essay.001

displays the rst 10 lines of the le essay.001 To see a specic number of lines, do this:
$ head -n 20 essay.001

This displays the rst 20 lines of the le.

ls
Use ls to see what les you have. Your les are kept in something called a directory.
$ ls foo foobar letter1 $ letter2 letter3 maple-assignment1

Note that you have six les. There are some useful variants of the ls command:
$ ls l* letter1 letter2 letter3 $

Note what happened: all the les whose name begins with "l" are listed. The asterisk (*) is the " wildcard" character. It matches any string.

NETW235

NETW235

Consolidated Mini-Labs

lpr
This is the standard Unix command for printing a le. It stands for the ancient "line printer." See
$ man lpr

for information on how it works. See print for information on our local intelligent print command.

mkdir
Use this command to create a directory.
$ mkdir essays

To get "into" this directory, do


$ cd essays

To see what les are in essays, do this:


$ ls

There shouldn't be any les there yet, since you just made it. To create les, see cat or emacs.

more
More is a command used to read text les. For example, we could do this:
$ more poems

The effect of this to let you read the le "poems ". It probably will not t in one screen, so you need to know how to "turn pages". Here are the basic commands: q --- quit more
NETW235

NETW235

Consolidated Mini-Labs

spacebar --- read next page return key --- read next line b --- go back one page For still more information, use the command man more.

mv
Use this command to change the name of le and directories.
$ mv foo foobar

The le that was named foo is now named foobar

print
This is a moderately intelligent print command.
$ print foo $ print notes.ps $ print manuscript.dvi In each case print does the right thing, regardless of whether the le is a text le (like foo ), a postcript le (like notes.ps, or a dvi le (like manuscript.dvi. In these examples the le is printed on

the default printer. To see what this is, do


$ print

and read the message displayed. To print on a specic printer, do this:


$ print foo jwb321 $ print notes.ps jwb321 $ print manuscript.dvi jwb321

To change the default printer, do this:


$ setenv PRINTER jwb321

NETW235

NETW235

Consolidated Mini-Labs

pwd
Use this command to nd out what directory you are working in.
$ pwd /u/ma/jeremy $ cd homework $ pwd /u/ma/jeremy/homework $ ls assign-1 assign-2 assign-3 $ cd $ pwd /u/ma/jeremy $

Jeremy began by working in his "home" directory. Then he cd 'd into his homework subdirectory. Cd means " change directory". He used pwd to check to make sure he was in the right place, then used ls to see if all his homework les were there. (They were). Then he cd'd back to his home directory.

rm
Use rm to remove les from your directory.
$ rm foo remove foo? y $ rm letter* remove letter1? y remove letter2? y remove letter3? n $

The rst command removed a single le. The second command was intended to remove all les beginning with the string "letter." However, our user (Jeremy?) decided not to remove letter3.

NETW235

NETW235

Consolidated Mini-Labs

rmdir
Use this command to remove a directory. For example, to remove a directory called "essays", do this:
$ rmdir essays

A directory must be empty before it can be removed. To empty a directory, use rm.

rsh
Use this command if you want to work on a computer different from the one you are currently working on. One reason to do this is that the remote machine might be faster. For example, the command
$ rsh solitude

connects you to the machine solitude. This is one of our public workstations and is fairly fast. See also: telnet

setenv
$ echo $PRINTER labprinter $ setenv PRINTER myprinter $ echo $PRINTER myprinter

NETW235

NETW235

Consolidated Mini-Labs

sort
Use this commmand to sort a le. For example, suppose we have a le dict with contents
red rojo green verde blue azul white blanco black negro

Then we can do this:


$ sort dict black negro blue azul green verde red rojo white blanco Here the output of sort

went to the screen. To store the output in

le we do this:
$ sort dict >dict.sorted

You can check the contents of the le dict.sorted using cat , more , or emacs .

tail
Use this command to look at the tail of a le. For example,
$ tail essay.001

displays the last 10 lines of the le essay.001 To see a specic number of lines, do this:
$ tail -n 20 essay.001

This displays the last 20 lines of the le.

NETW235

NETW235

Consolidated Mini-Labs

tar
Use create compressed archives of directories and les, and also to extract directories and les from an archive. Example:
$ tar -tvzf foo.tar.gz

displays the le names in the compressed archive foo.tar.gz while


$ tar -xvzf foo.tar.gz

extracts the les.

telnet
Use this command to log in to another machine from the machine you are currently working on. For example, to log in to the machine "solitude", do this:
$ telnet solitude

See also: rsh.

wc
Use this command to count the number of characters, words, and lines in a le. Suppose, for example, that we have a le dict with contents
red rojo green verde blue azul white blanco black negro

NETW235

NETW235

Consolidated Mini-Labs

Then we can do this


$ wc dict 5 10 This shows that dict 56 tmp

has 5 lines, 10 words, and 56 characters.

The word count command has several options, as illustrated below:


$ wc -l dict 5 tmp $ wc -w dict 10 tmp $ wc -c dict 56 tmp

NETW235

NETW235

Consolidated Mini-Labs

Task 4 :: Creating and Managing File systems


1) Create a New virtual disk on VM Workstation and re-boot

a) Open virtual machine settings b) Add new hardware c) Start hardware wizard / Select new hard disk d) Create the virtual disk => 10 Gig e) Disk Type should be SCSI / Set disk size and options f) Name the disk file / click next g) Ensure new disk exists / Click OK to close VM settings tab h) Re-boot VM Server i) Switch to a root login $ sudo -s <password>

2. Create a record of the current partition table to make cleanup




$ sfdisk -d /dev/sdb > /root/part.table

NETW235

NETW235

Consolidated Mini-Labs

3. Use fdisk to create new partition for an ext3 system. $ fdisk /dev/sdb ... Command (m for help): p Command (m for help): n Command action (e extended p Partition number (1-4): 1 First Cylinder (x-y, default x) : enter Last Cylinder or +sizeM or +sizeK (x-y, default x) : enter Command (m for help): p Command (m for help): w $ shutdown -r now (print current table details) (partition table saved) (to make changes) 4) Verify that two partitions are seen on the disk. Identify extact name and type of partition sdb1. (print current table details) p primary (1-4) $ fdisk -l /dev/sdb $ cat /proc/partitions $ ls /dev/sdb*

NETW235

NETW235

Consolidated Mini-Labs

5) Being careful to specify the current block device file, create filesystems on the two partitions: $ mkfs -t ext3 /dev/sdb1 (make sure sdb1 is right one) 6) Add entries for both file systems => using vi /etc/fstab


/dev/sdb1 /mnt/ext ext3 defaults 1 2 7) Make the corresponding directories, mount the file systems, and confirm that theyre mounted


$ mkdir /mnt/ext $ mount -a $df -hT | grep /mnt $ mount | grep /mnt

NETW235

NETW235

Consolidated Mini-Labs

Task 5 :: Creating/Adding Hot SWAP 1) Save/record the current memory usage $ (echo BEFORE; free) > /tmp/mem 2) Allocate a 100MB block of contiguous disk space using dd $ dd if=/dev/zero of =/tmp/swaptest bs=1M count=100
(if => input file, of => output file, bs => block size)

$ ls -lh /tmp/swaptest 3) Write SWAP signature to the file and so that kernel will know $ mkswap /tmp/swaptest


4) Activate the new SWAP space and record new memory totals $ swapon /tmp/swaptest $ (echo AFTER; free) >> /tmp/mem 5) Compare BEFORE and AFTER totals for the memory usage $ cat /tmp/mem 6) Deactivate the temporary SWAP space and remove the file $ swapoff /tmp/swaptest $ rm -f /tmp/swaptest
NETW235

NETW235

Consolidated Mini-Labs

TASK 6 :: Setting User Quota 1) Modify /etc/fstab to include the user and group quota options using vi /etc/fstab /dev/sdb1 /mnt/ext ext3 default usrquota,grpquota 1 2 2) Re-mount the filesystem and verify that the new options


# mount -o remount /mnt/ext # mount | grep /mnt

3) Build the initial quota database # quotacheck -cugm /tmp/ # ls -l /tmp/aquota* 4) Activate the quotas for, and generate a report # quotaon /tmp/

# repquota /tmp/ 5) Change the block quota to set a hard limit (4th column) to 2048 blocks/2MB for a user # setquota testuser 0 2048 0 0 /tmp/

NETW235

NETW235

Consolidated Mini-Labs

6) Test <testuser?>s disk quota by trying to create a 4MB file




# su - testuser # cd /tmp/ # dd if=/dev/zero of=/tmp/bigfile bs=1024 count=4096

7) As the <testuser?> , use the quota command to view usage # quota -v 8) Try copying another file to /tmp to see error message # cp /etc/fstab /tmp/ 9) Delete bigfile and verify the usage report


# rm /tmp/bigfile # quota -v

NETW235

NETW235
Task 7 :: Network Discovery 1) Switch to a root login $ sudo -s <password>

Consolidated Mini-Labs

2) Check speed and duplex settings for eth0: $ ethtool eth0 | grep (Speed|Duplex) 3) Check MAC address $ ifconfig eth0 | grep HWaddr 4) Find IP address and subnet mask for eth0. $ ifconfig eth0 | grep addr $ ip addr list eth0 | grep inet 5) Default gateway: $ route | grep ^def $ ip route list match 0.0.0.0 7) Checkout DNS name server IPs $ grep ^name /etc/resolve.conf 8) Use DHCP to check client is running $ cat /var/run/dhclient-eth0.pid 9) Checkout DHCP lease files $ cat 10) Hostname commands $ hostname $ uname -n

NETW235

NETW235

Consolidated Mini-Labs

Task 8 :: Discover, manage DHCP Network commands 1) Check DHCP configuration NIC and verify client is running? $ more /etc/network/interfaces $ more /etc/dhcp3/dhclient.conf 2) Make a backup copy of config file and start dhclient $ cp /etc/dhcp3/dhclient.conf /etc/dhcp3/dhclient.conf.backup $ dhclient 3) Examine the current IP address configured on NIC and identify the last Octet number $ ip addr show eth0 4) Add a second IP address to the eth0 $ ip addr add 192.168.41.XX/24 dev eth0 5) Test/ping new alias IP $ ping -c 1 192.168.41.XX 6) Re-add the additional address with a LABLEL, so the ifconfig or IP command can assossiate new virtual interface with the address $ ip addr del 192.168.41.XX/24 dev eth0 $ ip addr add 192.168.41.XX/24 label eth0:0 dev eth0 7) View the interface with both commands $ ip addr list dev eth0 $ ifconfig -a

NETW235

NETW235

Consolidated Mini-Labs

8) Make a backup copy of config files, config new static IP and re-start network. Desired new sample settings: => Host IP address 192.168.1.100 => Netmask: 255.255.255.0 => Network ID: 192.168.1.0 => Broadcast IP: 192.168.1.255 => Gateway/Router IP: 192.168.1.254 => DNS Server: 192.168.1.254 $ cp /etc/network/interfaces $ ifconfig eth0 /etc/network/interfaces.backup

( To check existing network in eth0 )

$ vi /etc/network/interfaces <=Append new network settings iface eth0 inet static address 192.168.1.100 netmask 255.255.255.0 network 192.168.1.0 broadcast 192.168.1.255 gateway 192.168.1.254 ESC :x Save and close the vi file. Restart the network: $ /etc/init.d/networking restart 4) Define new DNS servers, backup config file and $ cp /etc/resolv.conf /etc/resolv.conf.backup $ vi /etc/resolv.conf domain search ESC :x <= Append new Name server ubuntu_test ubuntu_test Save and close the vi file.

nameserver 192.168.1.254

5) Test new DNS server $ host ubuntu_test

NETW235

NETW235

Consolidated Mini-Labs

Task 9 :: Verify Apache is running and check with Browser. 1) Start VM Ubantu Server a) Switch to a root login $ sudo -s <password>

2) Run apache2ctl status to check Apache is running # cd /usr/sbin # ls # apache2ctl status 3) Stop , cleanup error and access logs # cd /usr/sbin # ls # apache2ctl stop # cd /var/log/apache2/ # ls # rm -i error.log # rm -i access.log 4) Start from Apache install path, and check logs # cd /usr/sbin # apache2ctl start # cd /var/log/apache2/ # ls # more error.log # more access.log

NETW235

NETW235

Consolidated Mini-Labs

5) Use browser and check Welcome screen a) Make Network enable with DHCP on / use Network Editor

b) User Browser and enter Ubuntu server IP Address

c)

NETW235

NETW235

Consolidated Mini-Labs

Task 10 :: Change Apache default config files 1) Change directory to Apache default config files location # cd /etc/apache2/sites-available/ # cp default default.bak

2) Verify that the disks/file systems /mnt/webapp & /mnt/weblog are available and the following command may display similar bitmap as show below. # df -hT | grep /mnt/web

3) Use vi Editor to change ServerAdmin, DocumentRoot, and Log files location. # vi default Search ServerAdmin and replace administrator e-mail to ServerAdmin webmaster@mywebhost.com

Search DocumentRoot and replace HTML, CGI scripts path to DocumentRoot /mnt/webapp

Search ErrorLog & CustomLog and replace path to ErrorLog CustomLog /mnt/weblog/error.log /mnt/weblog/access.log combind

NETW235

NETW235

Consolidated Mini-Labs

4) Restart Apache from /usr/sbin and check with browser for any changes? # cd /usr/sbin # apache2ctl restart a) User Browser and enter Ubuntu server IP Address to verify changes. NOTE:: You may see a Page not found/Forbidden error WHY? (There are scripts/HTML files on new DocumentRoot ) 5) Clear page not found error/Forbidden path error by copying default Welcome page Script/HTML? # cp /var/www/*.* # cd /mnt/webap Use vi Editor and change content of the default Welcome page a) User Browser and enter Ubuntu server IP Address to verify changes. 6) Change more content details or add a new and verify with Browser results # cd /mnt/webap Use vi Editor and change content of the default Welcome page b) User Browser and enter Ubuntu server IP Address to verify changes.
NETW235

/mnt/webapp/

NETW235

Consolidated Mini-Labs

Task 11 :: Change status.conf to see server-status page 1) Change status.conf file to allow your own server IP (192.168.117.131/24) to display server-status page on browser. # cd /etc/apache2/mods-available/ # cp status.conf status.conf.bak Display and identify Server IP # ip addr show eth0 Use vi editor to change permission within status.conf file. # vi status.conf Change / un-comment by removing # sign Make following line to change as highlighted # Allow from to Allow from 192.168.117.131/24 2) Check browser for http://192.168.117.131/server-status It may not display server-status!! WHY? Restart Apache Web server and check again; # apache2ctl restart Check again for http://192.168.117.131/server-status You must see detailed Apache Server status!!!
NETW235

.example.com

NETW235
Task 12:: PERL/CGI.

Consolidated Mini-Labs

1) Start VM Ubantu Serve and Switch to a root login $ sudo -s <password>

2) Install PERL/CGI module to Apache2 server # apt-get install libapache2-mod-perl2 3) Fix ServerName for Website/Host name # vi /etc/apache2/conf.d/fqdn

and add

# ServerName localhost
4) Fix the DocumentRoot for static pages and PERL/CGI module
# cp/etc/apache2/sites-available/default "" /etc/apache2/sites-available/mysite

# vi /etc/apache2/sites-available/mysite
Change the DocumentRoot Directory directive, replace <Directory /var/www/> to <Directory /mnt/webapp/pages/> Change the /cgi-bin/ Alias directive, replace Alias /cgi-bin/ /mnt/webapp/cgi-bin/ PerlModule ModPerl::Registry <Location /cgi-bin/> SetHandler perl-script PerlHandler ModPerl::Registry #PerlHandler ModPerl::PerlRun Options +ExecCGI #PerlSendHeader On </Location>

NETW235

NETW235

Consolidated Mini-Labs

5) Add directories and enable mysite # mkdir -p /mnt/webapp/pages # cp /var/www/*.* /mnt/webapp/pages # mkdir -p /mnt/webapp/cgi-bin

# a2dissite default # a2ensite mysite

NETW235

NETW235

Consolidated Mini-Labs

Task 13:: PERL File operations and HTML Script generation. 1) Create and run PERL program to display environment details # cd /mnt/webapp/cgi-bin # vi test_serverInfo.cgi
#!/usr/bin/perl use CGI; my $query= new CGI; $|=1;# Flush output immediately. print $query->header; $count = ($#ARGV + 1); print "Argument Count: $count"; foreach $word (@ARGV) { print "\n $word"; } print "\n"; print "SERVER_SOFTWARE = $ENV{'SERVER_SOFTWARE'}\n"; print "SERVER_NAME = $ENV{'SERVER_NAME'}\n"; print "SERVER_PROTOCOL = $ENV{'SERVER_PROTOCOL'}\n"; print "SERVER_PORT = $ENV{'SERVER_PORT'}\n"; print "SERVER_ROOT = $ENV{'SERVER_ROOT'}\n"; print "REQUEST_METHOD = $ENV{'REQUEST_METHOD'}\n"; print "HTTP_AccEPT = $ENV{'HTTP_AccEPT'}\n"; print "PATH_INFO = $ENV{'PATH_INFO'}\n"; print "PATH = $ENV{'PATH'}\n"; print "PATH_TRANSLATED = $ENV{'PATH_TRANSLATED'}\n"; print "SCRIPT_NAME = $ENV{'SCRIPT_NAME'}\n"; print "QUERY_STRING = $ENV{'QUERY_STRING'}\n"; print "QUERY_STRING_UNESCAPED = $ENV{'QUERY_STRING_UNESCAPED'}\n"; print "REMOTE_HOST = $ENV{'REMOTE_HOST'}\n"; print "REMOTE_IDENT = $ENV{'REMOTE_IDENT'}\n"; print "REMOTE_ADDR = $ENV{'REMOTE_ADDR'}\n"; print "REMOTE_USER = $ENV{'REMOTE_USER'}\n"; print "AUTH_TYPE = $ENV{'AUTH_TYPE'}\n"; print "CONTENT_TYPE = $ENV{'CONTENT_TYPE'}\n"; print "CONTENT_LENGTH = $ENV{'CONTENT_LENGTH'}\n"; print "DOCUMENT_ROOT = $ENV{'DOCUMENT_ROOT'}\n"; print "DOCUMENT_URI = $ENV{'DOCUMENT_URI'}\n"; print "DOCUMENT_NAME = $ENV{'DOCUMENT_NAME'}\n"; print "DATE_LOCAL = $ENV{'DATE_LOCAL'}\n"; print "DATE_GMT = $ENV{'DATE_GMT'}\n"; print "LAST_MODIFIED = $ENV{'LAST_MODIFIED'}\n"; # End of PERL Script (Your

/cgi-bin/ Alias of Apache Server)

Save vi file ESC :x and add execute permissions. # chmod 755 test_serverInfo.cgi Startup Browser and try run your first CGI program:: http://192.168.xxx.yyy/cgi-bin/test_serverInfo.cgi
NETW235

NETW235

Consolidated Mini-Labs

2) Create HTML Form template Script for calculator # cd /mnt/webapp/cgi-bin # vi input_form.dat


<html> <head> <title>Simple Perl Calculator</title> </head> <body> <h1>Simple Perl Calculator</h1> <form action="cgi-bin/calculator.cgi" method="get"> <table border="0"> <tr> <td> <input type="text" name="num1" size="3"> </td> <td> <select name="operation"> <option value="a">+</option> <option value="s">-</option> <option value="m">*</option> <option value="d">/<option> </select> </td> <td> <input type="text" name="num2" size="3"> </td> <td> <input type="submit" value="Calculate"> </td> </tr> </table> </form> <p>$OUTPUT</p> </body> </html>

NETW235

NETW235

Consolidated Mini-Labs

3) Next, create a file "calculator.cgi" in /cgi-bin/ Alias path of your Apache2 mysite.
$ cd /mnt/webapp/cgi-bin/ $ vi calculator.cgi #!/usr/bin/perl -w use strict; use CGI qw/:standard/; # Declare and initialize variables. my $num1 = 0; my $num2 = 0; my $result = 0; my $operation = ""; my $output = ""; my @input_form = (); my $output_html = ""; # Get input from "param" via CGI.pm. $num1 = param("num1"); $num2 = param("num2"); $operation = param("operation"); # Act on supplied input. if ($operation eq "a") { $result = $num1 + $num2; } if ($operation eq "s") { $result = $num1 - $num2; } if ($operation eq "m") { $result = $num1 * $num2; } if ($operation eq "d") { if ($num2 == 0) { $result = "Cannot divide by zero."; } else { $result = $num1 / $num2; } } # Read in the HTML template file. open (HTMLFILE, "<input_form.dat"); @input_form = <HTMLFILE>; close HTMLFILE; foreach (@input_form) { $output_html .= $_; } # Insert result in HTML template. $output_html =~ s/\$RESULT/$result/g; # Send HTML to the browser. print "Content-type:text/html\n\n"; print $output_html;

Run browser and see the output http://192.168.xxx.yyy/cgi-bin/calculator.cgi


NETW235

NETW235

Consolidated Mini-Labs

Task 14:: Install MySQL and configure PHP & Perl admin pages How to install MySQL on Ubantu Server 1) Update apt-get Databse of your Ubuntu Server:: Open a terminal and type the following commands to upgrade package database: $ sudo apt-get update $ sudo apt-get upgrade 2) Install MySQL server software :: You will be prompted to setup mysql root user password. $ sudo apt-get install mysql-server mysql-common mysql-client 3) Install GUI/Interface modules:: PHP GUI:: $ sudo apt-get install php5-mysql Perl5 GUI:: $ sudo apt-get install libdbd-mysql-perl 4) Re-Start Apache Server:: $ sudo /etc/init.d/apache2 restart 5) How Do I Access MySQL Server? Type the following command: $ mysql -u root -p You need to supply root user account password: Enter password:

NETW235

NETW235

Consolidated Mini-Labs

Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 107 Server version: 5.1.41-3ubuntu12.3 (Ubuntu) Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> 6) List Your Databases Type the following sql command at mysql> prompt: mysql> show databases; Sample outputs: +-----------------------+ | Database | +-----------------------+ | information_schema | | mysql | wiki | wikidb | wpmu 5 rows in set (0.02 sec) | | | |

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

7) Add A New Database To add a new database called myapps, enter: mysql> create database myapps;

NETW235

NETW235

Consolidated Mini-Labs

8) Add A New User called testUser to myapps Database and grant access from localhost: mysql> GRANT ALL ON myapps.* TO testUser@localhost IDENTIFIED BY 'Add-Your-Password-Here'; 9) Add A New User For myapps Database (Network Access) Make sure user testUser can access myapps database from Apache web server installed at 192.168.x.y mysql> GRANT ALL ON myapps.* TO testUser@192.168.x.y IDENTIFIED BY 'Your-Password-Here'; 10) How Do I View Log Files? The log is stored at /var/log/mysql/error.log, enter: $ tail -f /var/log/mysql/error.log $ grep 'something' /var/log/mysql/error.log

Configure MySQL Server


The default configuration file is located at /etc/mysql/my.cnf, enter: $ sudo vi /etc/mysql/my.cnf Change network binding to 192.168.x.y so that web server located at 192.168.x.y can access database: bind-address = 192.168.x.y Save and close the file.

NETW235

NETW235

Consolidated Mini-Labs

11) How Do I Start / Stop / Restart Server? $ sudo service mysql restart $ sudo service mysql stop $ sudo service mysql start Sample outputs: mysql start/running, process 4930 12) How to Reset a MYSQL root password? - MySQL has it's own user accounts, which are not related to the user accounts on your Linux machine. - By default, the root account of the MySQL Server is empty You need to set it. Please replace 'mypasswd' # mysqladmin -u root -h localhost password 'mypasswd' # mysqladmin -u root -h myhostname password 'mypasswd' 13) If you have problem with MySQL root password or lost it, the following step can be used to re-establish root!! password. Stop the mysql demon process using this command : # sudo /etc/init.d/mysql stop

Start the mysqld demon process using the --skip-grant-tables option with this command, run as background job. # sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &

Start the mysql client process using this command, please note we are using -p or say no password! # mysql -u root

NETW235

NETW235

Consolidated Mini-Labs

From the mysql prompt execute this command to be able to change any password mysql> FLUSH PRIVILEGES; mysql> GRANT CREATE, DROP ON *.* TO root@localhost IDENTIFIED BY 'newpass' WITH GRANT OPTION; GRANT ALL PRIVILEGES ON *.* TO root@localhost IDENTIFIED BY 'newpass' WITH GRANT OPTION; commit; exit Stop & start the mysql demon process using this command : # service mysql restart Verify the password is working::: # mysql -u root -p You need to supply root user account password: Enter password: mysql> show databases;

NETW235

NETW235

Consolidated Mini-Labs

Task 15:: PHP Admin pages Application and MySQL database maintenance.
1) Start VM Ubantu Serve and Switch to a root login $ sudo -s <password>

2) Install phpMyAdmin module for MySQL Admin pages # apt-get install phpmyadmin 3) Configure phpMyAdmin module with Apache2 # vi /etc/apache2/apache2.conf

Add the following Include directive... Include /etc/phpmyadmin/apache.conf


4) Use browser and access MySQL Admin pages http://192.168.x.y/phpmyadmin

NETW235

NETW235

Consolidated Mini-Labs

Task 16 :: PHP Web pages with MySQL database tables.


1) Create a MySQL database table to store user logins -- MySQL table webpage_logins with columns id, username, and passcode. # mysql -u root -p mysql> use myapps ; CREATE TABLE webpage_logins ( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(30) UNIQUE, passcode VARCHAR(30) );

2) Add a New User called appuser to myapps Database and grant access on localhost: mysql> GRANT ALL ON myapps.* TO appuser@localhost IDENTIFIED BY 'apppass123'; 3 ) Add a new User For myapps Database (Network Access). Make sure user testUser can access myapps database from Apache web server installed at 192.168.x.y. mysql> GRANT ALL ON myapps.* TO appuser@192.168.x.y
IDENTIFIED BY 'apppass123';

NETW235

NETW235

Consolidated Mini-Labs

4) Create PHP scripts for WebPage:: # cd /mnt/webapp/pages vi welcome.php -- welcome.php -<?php include('lock.php'); ?> <body> <h1>Welcome <?php echo $login_session; ?></h1> </body> ESC :wq (to save and quit file welcome.php) vi config.php -- config.php -- MySQL Connection info -<?php $mysql_hostname = "192.168.x.y"; $mysql_user = "appuser"; $mysql_password = "apppass123"; $mysql_database = "myapps"; $bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong"); mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong"); ?> ESC :wq (to save and quit file config.php)

NETW235

NETW235

Consolidated Mini-Labs

vi lock.php -- lock.php -- Session verification. If no session value page redirect to login.php <?php include('config.php'); session_start(); $user_check=$_SESSION['login_user']; $ses_sql=mysql_query("select username from webpage_logins where username='$user_check' "); $row=mysql_fetch_array($ses_sql); $login_session=$row['username']; if(!isset($login_session)) { header("Location: login.php"); } ?> ESC :wq (to save and quit file lock.php) vi login.php -- login.php -- Contains PHP and HTML code. <?php include("config.php"); session_start(); if($_SERVER["REQUEST_METHOD"] == "POST") { // username and password sent from Form $myusername=addslashes($_POST['username']); $mypassword=addslashes($_POST['password']); $sql="SELECT id FROM webpage_logins WHERE username='$myusername' and passcode='$mypassword'"; $result=mysql_query($sql); $row=mysql_fetch_array($result); $active=$row['active']; $count=mysql_num_rows($result);
NETW235

NETW235

Consolidated Mini-Labs

// If result matched $myusername and $mypassword, // table row must be 1 row if($count==1) { session_register("myusername"); $_SESSION['login_user']=$myusername; header("location: welcome.php"); } else { $error="Your Login Name or Password is invalid"; } } ?> <form action="" method="post"> <label>UserName :</label> <input type="text" name="username"/><br/> <label>Password :</label> <input type="password" name="password"/><br/> <input type="submit" value=" Submit "/><br/> </form> ESC :wq (to save and quit file login.php) vi logout.php -- logout.php -- SignOut Destroy the session value. <?php session_start(); if(session_destroy()) { header("Location: login.php"); } ?> ESC :wq (to save and quit file logout.php)

NETW235

NETW235

Consolidated Mini-Labs

6) Use Browser & see PHP / MySQL Web site login screen http://192.168.x.y/login.php The login page may repeated with out access!!! WHY? 7) Add an application/Web site user details to webpages_login table and try again; # mysql -u root -p mysql> use myapps ; insert into webpage_logins ( id, username passcode ) values (1, johndoe,john123) ; insert into webpage_logins ( id, username passcode ) values (1, marydoe,mary123) ; commit; 8) Use Browser & test PHP / MySQL Web site login screen agian http://192.168.x.y/login.php 9) What is the difference between appuser in the database and users in table webpage_logins table?

NETW235

NETW235

Consolidated Mini-Labs

Task 17 :: Setup Rysync, test local backup and a remote backup. 1) Start VM Ubantu Serve and Switch to a root login $ sudo -s <password> 2) Create user user Oracle and group dba # groupadd dba # useradd -c Oracle User for software install oracle # usermod -a -G dba oracle 3) Install Rsync , Enabling it and start the rsync daemon sudo apt-get install rsync vi /etc/default/rsync Change RSYNC_ENABLE from false to true sudo /etc/init.d/rsync start 3) Configure rsync and restart # vi /etc/rsyncd.conf motd file = /etc/rsyncd.motd [backup] path = /home/oracle/backup comment = This is the path to my on the server) uid = oracle gid = oracle read only = false auth users = oracle secrets file = /etc/rsyncd.scrt

NETW235

NETW235

Consolidated Mini-Labs

Add details to message file and setup password file # vi /etc/rsyncd.motd Oracle backup space # vi /etc/rsyncd.scrt oracle:oracle123 Retart/reload Rsync daemon # /etc/init.d/rsync reload 4) Test rsync commands # sudo -s oracle # rsync -azvv /home/oralce/backup/ /home/oracle/test1 # rsync -vr /home/oralce/backup/ oracle@localhost 192.168.117.130::backup/test2 5) Setup ssh auto password between two nodes / hosts # sudo -s oracle Generate keys on both nodes (node1 and node2) # ssh-keygen -t dsa - Accept default file location - Leave the passphrase empty (press Enter) - Generates 2 files id_dsa,id_dsa.pub ~/.ssh directory - Copy/sftp id_dsa.pub from node1 put into a file called /home/username/.ssh/authorized_keys on node2 - Copy/sftp id_dsa.pub from node2 put into a file called /home/username/.ssh/authorized_keys on node1 - Test SSH no-password connections. $ ssh node2 date

NETW235

NETW235

Consolidated Mini-Labs

Task 18 :: Setup Apache2 multiple sites 1) Start VM Ubantu Serve a root login $ sudo -s <password> and Switch to

2) Create a completely separate document root, cgi-bin directory, and logfile directory for each host "
" # mkdir -p /mnt/webapp " # mkdir -p /mnt/webapp/www.example.com # mkdir -p /mnt/webapp/www.example.com/htdocs " mkdir -p /mnt/webapp/www.example.com/cgi-bin # " " " " " " " " " # mkdir -p /mnt/weblogs/www.example.com/logs # mkdir -p /mnt/webapp/www.example.net # mkdir -p /mnt/webapp/www.example.net/htdocs # mkdir -p /mnt/weblogs/www.example.net/logs # mkdir -p /mnt/webapp/www.example.net/cgi-bin # mkdir -p /mnt/webapp/www.example.org # mkdir -p /mnt/webapp/www.example.org/htdocs # mkdir -p /mnt/weblogs/www.example.org/logs # mkdir -p /mnt/webapp/www.example.org/cgi-bin

NETW235

NETW235

Consolidated Mini-Labs

3) Open Apache configuration vi /etc/apache2/conf.d/ports.conf " Find the line: Listen 80 and Type new three lines as Listen 8081 ! " Listen 8082 Listen 8083

4) Setup a new document root, cgi-bin directory, and logfile directory on config files
# vi /etc/apache2/conf.d/virtual.conf " " " # # NameVirtualHost * *:80 *:8081 *:8082 *:8083 We're running multiple virtual hosts.

NETW235

NETW235

Consolidated Mini-Labs

When Apache starts up it reads the contents of all files included in /etc/apache2/conf.d and files you create here won't get trashed on package upgrades. # cd /etc/apache2/sites-available # cp default www.example.com # cp default www.example.net # cp default www.example.org

NETW235

NETW235

Consolidated Mini-Labs

Edit files in /etc/apache2/sitesavailable/www.example.com with the following contents:


# # # <VirtualHost *> ServerAdmin webmaster@example.com #ServerName ServerName www.example.com 192.168.xxx.yyy:8081 Example.com (/etc/apache2/sites-available/www.example.com)

ServerAlias example.com

# Indexes + Directory Root. DirectoryIndex index.html DocumentRoot /mnt/webapp/www.example.com/htdocs/

# CGI Directory ScriptAlias /cgi-bin/ /mnt/webapp/www.example.com/cgi-bin/ <Location /cgi-bin> Options +ExecCGI </Location> # Logfiles ErrorLog /mnt/webapp/www.example.com/logs/error.log

CustomLog /mnt/webapp/www.example.com/logs/access.log combined </VirtualHost>

NETW235

NETW235

Consolidated Mini-Labs

Next edit file the file www.example.net


# # # <VirtualHost *> ServerAdmin webmaster@example.net #ServerName ServerName www.example.net 192.168.xxx.yyy:8082 Example.net (/etc/apache2/sites-available/www.example.net)

ServerAlias example.net

# Indexes + Directory Root. DirectoryIndex index.html DocumentRoot /mnt/webapp/www.example.net/htdocs/

# CGI Directory ScriptAlias /cgi-bin/ /mnt/webapp/www.example.net/cgi-bin/ <Location /cgi-bin> Options +ExecCGI </Location>

# Logfiles ErrorLog /mnt/webapp/www.example.net/logs/error.log

CustomLog /mnt/webapp/www.example.net/logs/access.log combined </VirtualHost>

NETW235

NETW235

Consolidated Mini-Labs

Finally edit the file www.example.org:


# # # <VirtualHost *> ServerAdmin webmaster@example.org ServerName ServerName www.example.org 192.168.xxx.yyy:8083 Example.org (/etc/apache2/sites-available/www.example.org)

ServerAlias example.org

# Indexes + Directory Root. DirectoryIndex index.html DocumentRoot /mnt/webapp/www.example.org/htdocs/

# CGI Directory ScriptAlias /cgi-bin/ /mnt/webapp/www.example.org/cgi-bin/ <Location /cgi-bin> Options +ExecCGI </Location>

# Logfiles ErrorLog /mnt/webapp/www.example.org/logs/error.log

CustomLog /mnt/webapp/www.example.org/logs/access.log combined </VirtualHost>

NETW235

NETW235

Consolidated Mini-Labs

3) To enable the sites simply run: " # a2ensite www.example.com " # a2ensite www.example.net " # a2ensite www.example.org

"

Sites are installed; restart Apache.

# /etc/init.d/apache2 reload

This will now create the symbolic links so that /etc/apache2/sites-enabled/ www.example.org, etc, now exist and will be read by Apache server.

NETW235

NETW235

Consolidated Mini-Labs

Appendix - I

Linux editor vi commands

Modes in vi
Command mode This is the default when you enter vi. In command mode, most letters, or short sequences of letters, that you type will be interpreted as commands, without explicitly pressing Enter . If you press Esc when you're in command mode, your terminal will beep at you. Insert mode In insert mode, whatever you type is inserted in the le at the cursor position. Type a (lowercase letter a, for append) to enter insert mode from command mode; press Esc to end insert mode, and return to command mode. Line mode Use line mode to enter line oriented commands. To enter line mode from command mode, type a colon ( : ). Your cursor moves to the bottom of the screen, by a colon prompt.

NETW235

NETW235

Consolidated Mini-Labs

Starting vi and Saving Files


Starting vi: vi lenam e start editing lename, create it if necessary

Saving the le you're working on and/or leaving vi: :wq :q! :w! newle :n,m w! newle write the le to disk and quit quit without saving any changes write all lines from the entire current le into the le 'newle', overwriting any existing newle write the lines from n to m, inclusive, into the le newle, overwriting any existing newle

Moving the Cursor


Type: h j k l $ ^ To Move To: one space to the left (also try left arrow) one line down (also try down arrow) one line up (also try up arrow) one space to the right (also try right arrow) end of current line beginning of current line
NETW235

NETW235

Consolidated Mini-Labs beginning rst word on the next line end of le line n; use :0 to move the beginning of the le beginning of next word; 5w moves to the beginning of the 5th word to the right end of next word beginning of previous word one page up one page down the matching (, ), [, ], {, or } (Press % with your cursor on one of these characters to move your cursor its mate.)

Enter G :n w e b Ctrl-b Ctrl-f %

Searching for Text


/string ? string n search down for string search up for string repeat last search from present position

NETW235

NETW235

Consolidated Mini-Labs

Inserting Text
a A i I o O :r newle append starting right of cursor append at the end of the current line insert starting left of cursor insert at beginning of the current line open line below cursor, then enter insert mode open line above cursor, then enter insert mode add the contents of the le newle starting below the current line

Deleting Text
Type: x dw dd cw cc s D To: delete single character; 5x deletes 5 characters delete word; 5dw deletes 5 words delete line; 5dd deletes ... well you get the idea! delete word, leaves you in insert mode (i.e. change word) change line -- delete line and start insert mode change character -- delete character and start insert mode delete from cursor to end of line
NETW235

NETW235

Consolidated Mini-Labs

C u U J

change from cursor to end of line -- delete and start insert mode undo last change undo all changes to current line join current line with line that follows (press Enter in insert mode to split line)

Cutting and Pasting


Type: xp yy "ayy P "aP p "ap To: transpose two characters (two commands, x followed by p) yank (i.e. copy) one line into a general buffer (5yy to yank 5 lines) yank into the buffer named a put the general buffer back before the current line put from buffer a before current line put the general buffer back after the current line put from buffer a after the current line

NETW235

NETW235

Consolidated Mini-Labs

Miscellaneous Commands
Type: Ctrl-g Ctrl-l :!sh . To: show line number of current line redraw the entire display fork a shell; type Ctrl-d to get back to vi repeat last text change command at current cursor position

NETW235

Você também pode gostar