Title: TDC597 Linuxbased Network Management Lecture Three Perl
1TDC597Linux-based Network ManagementLecture
Three - Perl
- James T. Yu, Ph.D.
- jyu_at_cs.depaul.edu
- School of CTI
- DePaul University
2What is PERL
- Practical Extraction and Report Language
- Similar to shell script but a lot more powerful
- Is it more powerful than Aw?
- Easily available
- Lots of documentation and examples on the web
3Basic Concepts
- Perl files extension .pl
- Convention (not a requirement)
- Create self executing scripts
- Use system (Linux) commands
- Comment entry
- Print information on the screen
4First Perl Program
5Perl Basics
- Perl is a script language
- No compiler, no object file
- All perl commands end in "" .
- Perl can call Linux commands
- system(linux command")
- The pound sign "" is the symbol for comment.
Same as Shell and Awk. - The "print command" is used to write outputs on
the screen. - Note put \n at the end
- If you want to use formats for printing you can
use printf which is similar to C.
6Scalar Variables ()
- Scalar variables are always preceded with the
symbol. - No variable declaration is needed before its use.
- It is a good practice to declare it my
variable - No data types, such as character or numeric.
- Scalar variable means that it can store only one
value. - A scalar variable can store a character, a
string, or a number. - Example, name "betty"
- The value betty is stored in the scalar variable
name. - Use single quote for literal string. price
99.99 - Question what is wrong with price 99.99
- Default values for all variables is undef which
is equivalent to null.
7List Variables (_at_)
- List variables are like arrays. It can be
considered as a group of scalar variables. - They are always preceded by the _at_ symbol.
- Example, _at_names ("betty","veronica","tom")
- Like in C the index starts at 0.
- To reference the second item, use names1
- Note the symbol here because each element is a
scalar variable.
8List Variable
9Operations on list variablesstack operation
- Operators push, pop, shift, unshift, reverse
- Push and pop treat the list variable as a stack
and operate on it. They act on the top (last)
item of the stack. - Example push(_at_names,"lily") will yield
- _at_names with content of ("betty","veronica","tom",
"lily"). - Example pop(_at_names) returns "lily" which is the
last value. And _at_names will contain
("betty","veronica","tom").
10Operations on list variables (cont.)queue
operation
- shift and unshift act on the bottom (first) of
the stack - Example, unshift(_at_names,"lily"), and _at_names
contains ("lily","betty","veronica","tom"). - Example, shift(_at_names) returns "lily" and _at_names
contains ("betty","veronica","tom"). - reverse reverses the list.
11Operations on List Variables
12Hash Variables ()
- Hash variables are like arrays but instead of
having numbers as their index they can have any
scalars as index. - The same associate array in Awk.
- Hashes are preceded by the symbol.
- Example, hashArray ("A", 1, "B", 2, "C", 3)
- To get the hashArray, reference hashArrayA".
This will return the value of hashArray of A. - A is the key and 1 is its value.
- keys() returns a list of all the keys of the
given hash. - values() returns the list of all the values in a
given hash.
13Hash Variables
14Hash Variable (sorting)
15Read / Write to Files
- To read from and write to files, we need to
create handles which refer to the files. This is
the same as the file descriptor in C. - Return true if the file is opened successfully
otherwise, return false. - To create the handles we use the open command.
- Example open(FILEREAD, lt filename") create
the handle called FILEREAD for the file
"filename". - This handle will be used for reading.
- The lt" symbol before the filename is to indicate
the file is opened for reading. - Example open(FILEWRITE, "gtfilename") create the
handle called FILEWRITE for the file "filename". - This handle will be used for writing.
- The "gt" symbol before the filename is to indicate
the file is opened for writing.
16Read / Write to Files
- Once the file handles are created. the reading
and writing to files is pretty simple. - Example, linevalue ltFILEREADgt
- This will result in a line being read from the
file pointed by FILEREAD and the that line is
stored in the scalar variable linevalue. - When the end of file is reached the ltFILEREADgt
returns an undef. - Example, print FILEWRITE "linevalue \n
- This will result in a line with the value as in
linevalue being written to the file pointed by
the FILEWRITE . - To close a file for reading/writing, use
- close FILEHANDLE
17File Read/Write
18Control Structures
- If / unless statements
- while / until statements
- for statements
- foreach statements
- last , next , redo statements
- And as control structures
19if / unless
- The if command is similar to the if in C.
- unless the reverse of if
- Example of unless.
- unless(condition) .
- In an if command, in the case that you want to
leave the then part empty and have just an else
part, use unless.
20Numerical Comparison
Note same as C
21if unless
22while / until / for
- The while command is similar to the while of C.
- The for command is also similar to C
implementation - until.
- until( ltexpressiongt ) ltstatementsgt .
- The statements are executed till the condition is
met.
23Loop while, for, until
24foreach statement
- This statement takes a list of values and assigns
them one at a time to a scalar variable,
executing a block of code with each successive
assignment. - Example foreach var (list) .
25foreach
26last / next / redo
- The last command is similar to the break
statement of C. - When you want to quit from a loop, use last.
- Do not use break (syntactically correct, but )
- To skip the current loop use the next statement.
- It immediately jumps to the next iteration of the
loop. - This is similar to the continue statement in C.
- Do not use continue
- The redo statement repeats the same iteration
again.
27last, next, redo
28Functions
- Function declaration
- Calling a function
- Local variables
- Returning values
29Function Declaration
- The keyword sub describes the function.
- So the function should start with the keyword
sub. - Example, sub addnum . .
- It should be preferably either in the end or in
the beginning of the main program to improve
readability and also ease in debugging. - Always have a prolog at the beginning of the
function (a requirement for TDC597)
30Function Calls - Invocation
- name getname( )
- The symbol should precede the function name
in any function call.
31Parameters of Functions
- Parameter are passed to the function as a list.
- The parameter is denoted by _at__ inside the
function. - So if you pass only one parameter, the size of _at__
list will be one. If you pass two parameters then
the _at__ size will be two. These two parameters are
accessed by _0 and _1.
32More About Functions
- The variables declared in the main program are by
default global so they are available for
reference in the function. - Local variables are declared by putting 'my'
while declaring the variable. - my x x is a local variable in the function
33More About Functions
- The result of the last operation is usually the
value that is returned unless there is an
explicit return statement returning a particular
value. - Recommendation always use return to return a
value. - Clarity is more important than saving one line of
code. - There are no pointers in Perl but we can
manipulate and even create complicated data
structures.
34Function (sub)
35String Operation
- split and join
- String Comparison
- Using different delimiter
- matching replacing
- Index and substring
- Others
36The split function
- split is used to form a list from a scalar data
depending on the delimiter. - The default delimiter is the space.
- It is usually used to get the independent fields
from a record. Â - Example
- linevalue "R101 tom 89"
- _ linevalue.
- _at_data split()
- data0 is R101, data1 is tom , data2 is
89. - split by default acts on the _ variable.
- If split has to perform on some other scalar
variable, than the syntax is. - split (/ /, linevalue)
- To use other delimiter for split, the syntax is
- split(/ltdelimitergt/, linevalue)
- Example _at_arr split(/ /, linebuf)
- one or more space characters
37The join function
- join does the exact opposite job as that of the
split. - It takes a list and joins up all its values into
a single scalar variable using the delimiter
provided. - Example, newlinevalue join(_at_data)
38split and join
39String Operations
40String Operations
41Matching and Replacing
- Suppose you need to look for a pattern and
replace it with another one you can do the same
thing as what you do in Linux. The command in
perl is - s/ltpatterngt/ltnew patterngt/
- This by default acts on the _ variable. If it
has to act on a different variable (eg newval)
then use. - Example, _at_newvals/ltpatterngt/ltnew patterngt /.
42Pattern Match and Substitution
43index and substr
- index(s, c, i)
- Return the position of c in s, start searching
from i - substr(s, n1, n2)
- Create a subsring from s, starting at n1 with
lengthn2
s ..12345.. my idx1
index(s, "", 0) my idx2 index(s, "",
(idx11)) my pid substr(s, (idx11),
(idx2-idx1-1))
44many, many more Perl features
45Hw03 (due 08/02)
- Objective analyze the Linux message file
- The message file is located in /var/log/messages
(readable by root only) - A sample copy of message file is saved on
- /home/tdc597/log/messages (hard code in your
program) - It has a lot of system log information
- User login and logout time
- Failed login attempt
- More
- Hw03 show a summary report of account usage
- Extra credit analysis of potential system
intrusion - Template /home/jyu/tdc597/lec03/hw03template.pl
- Your program HOME/hw03/hw03script.pl
- Your directory and files must be protected from
other students.
46Input Data
47Extra Credit intrusion analysis
Failed login attempt to root (uid0) from an
unknown remote host
Report number of intrusion attempt from each
rhost