Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

27
Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting

Transcript of Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Page 1: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Internet / Intranet

Spring 2000

Class 8Perl / CGI Scripting

Page 2: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 2

Class 8 Agenda

Homework Discussion : Milestone #3PresentationsCGI Scripting

PerlTelnet / UNIX

Lab WorkTelnet

Basic UNIX

Perl

Page 3: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 3

CGI / ScriptingScripts are Programs Run By the Server

CGI – Common Gateway InterfaceMethodology For Server/Script Communication

Can Be Written in Any Language Supported By the ServerUNIX Origins

PERL is Most CommonScript Output is Returned to the BrowserAlternative Methodologies Exist

CGI is the Most Portable

PERL – Practical Extraction and Reporting LanguageUNIX Based Scripting LanguagePorted to Multiple Platforms

How Does Browser Know to Execute a Program?Program is in a Script Directory

Typically cgi-bin (Apache)

Or By Extension (e.g. .pl, .cgi)Scripts Must Have Executable Permissions

Page 4: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 4

Scripting FeaturesScripts Can Have Input Parameters

Passed as Part of URL : ? Argument (Query String)Special Characters Passed as % Ascii Hex ValuesName/Value Pairs : Separated by &

Variable Passed in HTTP Header

Name/Value PairsMethod = Post HTML Forms

Passed in CookiesNetscape Origins, Now Widely AdoptedName/Value Pairs Associated With a URLStored on Client ComputerUsers May Turn off Cookies

Scripts Must Be Aware of How Parameters are Being Passed

Different Methodology to Access Each MethodParameters Also Used to Maintain State Information

Help Track a “Session”

Page 5: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 5

Scripting Issues

Security ConcernsNo Limits on What CGI Scripts May AccessPotential to Execute Any System CommandHacker Can Cause Serious and Unforeseen ProblemsPotential to Affect More Than Just Your Web SiteMany ISP’s Limit CGI Capabilities

Performance ConcernsCGI Scripts are Run as a Standalone Process

E.g. Interpreter is Loaded and Initialized Each Time

Alternative to Posting FormsMailto Option

Page 6: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 6

PerlWhy Should I Learn Perl?

S/W Engineers Need to Be Adept at Picking Up New Languages

Need a “Comfort Level” of ExpertiseAbility to Write Basic CodeAbility to View/Modify Existing CodeAbility to Learn More as Needed

Develop Reference “Library”Develop “Guru” Network

Large Public Archives of Perl ScriptsPerl Basics

InterpretedOriginally Used Primarily By UNIX Sys-Admins“Public Domain”The preferred language for CGI ScriptsPERL is Relatively Portable

Activestate ActivePerl (Windows / IIS) UNIX specific scripts dominate (Uses UNIX O/S Commands)

Page 7: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 7

Perl 101C-like

Lines end with ;Syntax of Print statement is very similarPointers and indirection

VB-like Untyped (except for arrays)Associative arrays

UNIX-like “Tricks”

e.g. $a = <> retrieves a line of input from stdinsupport for regular expressionsdoublequotes vs. singlequotesall examples must contain foo

Perl-LikeVariables begin with $Comments begin with #Subroutines Begin with &Associative Arrays Begin with %

Page 8: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 8

Perl 102

Powerful FeaturesCan run “command line” commands on O/S (system, `xxx`)Can create code on the fly (eval)Subroutine LibrariesPowerful Features Make it a Target of Hackers

Print is the Most Important CommandGenerate HTML Using Print Statementsprint “text to print \n”Don’t forget carriage returns: \n

First Line: #! /usr/local/bin/perlOutput has Mime content-type as first line, blank line

print “Content-type: text/html \n\n”;

Page 9: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 9

A Simple Perl Example#! /usr/local/bin/perl# First Perl$myname=“Evan”;print <<END;Content-type: text/html

<HTML><HEAD><TITLE></TITLE></HEAD><BODY>

ENDprint “<H1>This is $myname ’s Test Perl Script.</H1>\n”;print “<H2>Hello World</H2>\n”;print “</BODY>\n”;print “</HTML>\n”;

Page 10: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 10

Class Exercise: First Perl

Save This Locally as perl1.plOpen a Command Prompt:

perl.exe perl1.pl

Once You Are Satisfied With the HTML ProducedUpload This via FTP to public_html/cgi-bin in your ShoreNet AccountRemember to Transfer this In ASCII Mode!

Give the Script Execute Permissions For AllRight Button Click / chmod in WS_FTP

http://shell3.shore.net/~brinetxx/cgi-bin/perl1.pl

Page 11: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 11

Advanced Exercise

Create a Script Like the One in Stein p.481Typo: for each should be foreachPut it On Your Web Site

Remember to Give the Script the Appropriate Permissions

OPTIONAL Homework: Install a Perl Interpreter On Your Local MachineRead Stein Chapter 9. Skim Chapter 8.

Page 12: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 12

Telnet

Telnet is a Remote Login ProtocolTerminal EmulationAll Processing Occurs on HostCommand Line InterfacePort 23

Used Extensively for UNIX Machines / Multiuser SystemsWhy Do We Care?

Remote Administration of Web SiteConfiguring Web Servers, Setting Permissions

Page 13: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 13

Sample Telnet Session

telnet world.std.com

Trying 192.74.137.5...

Connected to world.std.com.

Escape character is '^]'.

 

UNIX System V.4 (world)

 

login: evan

Password: xxxxx

Last login: Sun Jan 23 16:03:36 from fxtc2-c.std.com

Welcome to The World! A 24 x 250MHZ CPU 2.5GB SGI Challenge XL

world%

DNS Resolves the Name to an IP Address

Found the Telnet Server at This IP Address

Host Information

Login Successful

UNIX Command Prompt

Page 14: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 14

UNIX - Background

UNIX Developed at AT&T Bell Labs – 1969Multi-User / Multi-Tasking

Many Other Proprietary Operating Systems ExistedSchools Adopted UNIX as “Teaching” EnvironmentSchools Made Significant Additions and Changes

Standardization EffortsCulture of Sharing / Helping / Working Together

Free Software Foundation, etc.Put Source-Code in Public DomainMany Other “Free” Add-Ons / Extensions

LINUX

UNIX Expects Technical Competence

Page 15: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 15

UNIX File StructureForward Slashes (/) to Separate Filenames, DirectoriesCase Sensitive File Names

Windows is NotNo Limit on Filename Size / Extensions

Extensions are by ConventionRoot is “/”User Home Directory is: “~/”Symbolic Links / Aliases

Directories Can Be Spread Over Multiple DrivesCan Create Non-Hierarchical Structure

File PermissionsRead, Write, ExecuteSeparate Permissions for Owner, Group, All

Directories are Special Cases of FilesExecute Permissions = Able to Browse Directory

Page 16: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 16

Common Basic UNIX Commandspwd : List the current working directoryMore filename : List the Contents of a Filels : Lists the files in a directory

ls –l Permissions: drwxrwxrwx

d – If this is a directoryr,w,x – Read, Write, ExecuteOwner, Group, Public

Owner, Filesize, Timestamp, Filenamecd – change directorycd ~/

Change to Your Root Directorychmod

Changes PermissionsDon’t Use This Command Until You’re Sure About It

Can Open Up Serious Security Holes

Page 17: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 17

More Unix Commandsman command

UNIX helpe.g. man ls

cat filenameList a file

command | moreAll Output can be “piped” to Display one Screen at a Time

e.g. cat filename | more Carriage return – next pageq – quit

cp path1 path2Copy a File

mv path1 path2Move a File. Useful for Renaming a file

Page 18: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 18

The UNIX chmod Command

“UNIX” Modechmod abc filename

Where a,b,c are digits from 0 to 7 (Bit Mask)4 – Read, 2 – Write, 1 – Executea – owner, b – group, c- others

e.g. chmod 711 myscript.cgiSets permissions on file myscript.cgi so that:

It is readable, writable, and executable by ownerIt is executable by all others.

An “Easier” Waychmod u=rwx,g=x,o=xu – owner (user), g – group, o – other (Not Owner!)r – read, w –write, x – execute

Page 19: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 19

A Caveat

UNIX Culture – Developer OrientedRead Access Often Given For Non-Confidential Files User Responsibility to Not Abuse ItBe Respectful When Not in Your User Directory

Page 20: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 20

Lab Work: TelnetFrom a command prompt type: telnetConnect/Remote SystemHost Name: users.shore.netLogin: brinetxx [Your Shorenet Login]Password: [Your Shorenet password]ls –lcd public_htmlls –lcd binchmod perl1.pl 600

Try to access the Script Nowchmod perl1.pl 755ls -lcd ~/ls –llogout

Page 21: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 21

Reference MaterialCGI / PERL

Stein Chapter 9http://www.activestate.com/ActivePerl

Freeware ActivePerl Interpreter For Microsoft Platforms

http://www.shore.net/techtalk/referenceold/cgi.htmlShoreNet’s CGI Reference Page

http://www.webdeveloper.com/cgi-perlCGI/Perl Portal

http://agora.leeds.ac.uk/Perl/start.htmlA Perl tutorial

http://worldwidemart.com/scripts/Free CGI Scripts (Matt’s Script Archive)

Page 22: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 22

Processing Forms – The Server Side

Target of Forms is Usually a CGI ScriptScript Requirements

1. Parse the Data2. Process the Data3. Return Data to the User

Raw HTML or Another Form

Data Flow OptionsEach Script Handles a Specific Form

Form in Plain HTMLScript in Perl

One Script Handles Multiple FormsSelects Action Based on Data Passed InAll in Perl

Page 23: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 23

Scripting – Parsing Data

GET vs. PUTEach Requires Different LogicParsing is Not Trivial

All Parameters Passed in On One LineEach Name/Value Pair Separated by &Name Separated From Value by =Special Character Encoding Complicates It

E.g. Value May Contain &,=Error Handling

Typically Use a Library to Parse DataPublic Domain

Cgi.pm – Perl5 Object OrientedUsed by Stein

Cgi-lib.pl – Basic PerlUsed by Schapiro

Others

Page 24: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 24

CGI-LIB http://cgi-lib.berkeley.edu/Using This Library in Perl

Download Library From WebsiteVersion 2.18 – Latest Version

More RobustSupports Saving File Uploads as Files

Version 1.14 – Easier to UnderstandUse This Version to Understand cgi-lib Code

Install it in cgi-bin DirectoryPerl Code:

require (“cgi-lib.pl”);&ReadParse();

More Perl Inforequire – Includes Another File%varname – Associative Arrays

Use Braces {} to Index, $ prefixe.g. $varname { ‘keyname’ }

Page 25: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 25

ReadParse Subroutine in cgi-lib

ReadParse SubroutineReads in Both Get and Put Data

Converts Encoding to Plain TextPuts Key/Value Pairs in %in

%in is an Associative ArrayTo Access a Value:

$in { ‘keyname’ }

To Access Each Key/Value Pairforeach $keyname (sort keys (%in))

print “$keyname $in {$keyname };}

Example

Page 26: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 26

In Class Exercise

Modify Last Weeks Script to Accept User Name via a Form

Step 1: Install cgi-lib in Your bin DirectoryMake Sure to Set Permissions Correctly

Step 2: Make a Copy of perl1.pl Name it perl2.pl

Step 3: Edit perl2.plAdd these lines:

require (“cgi-lib.pl”);&ReadParse();

Replace $myname=‘xxx’; with $myname = $in { ‘username’ };

Copy it to Your Shorenet cgi-bin directory

Page 27: Internet / Intranet Spring 2000 Class 8 Perl / CGI Scripting.

Brandeis University Internet/Intranet Spring 2000 27

In Class Exercise (2)

Step 4: Create a Simple Form To Accept User Name

<html><head></head><body><form method=“post” action=

http://users.shore.net/~brinetxx/cgi-bin/perl2.pl>Enter name: <input type=“text” name=“username”

value=“default”><br><input type=“submit” Value=“submit”></form></body></html>

Copy it to Your Shorenet Public_html Directory

Step 5: Try It!When You Are Done

Review Sample Scripts / Demos