You are on page 1of 294

Operating Systems

Week 1
Week 1

• Introduction

• Class resources and expectations

• Review syllabus

• Review outline

• Material Introduction
Who am I?
 Dr. Malek Alsmadi
 Malsmadi@confederationcollege.ca
 Get an answer within 24 hours
 – except weekends/holidays
 Office hours:
 TBA

 Location: TBA
 Appointment is best
Student Success

 Attendance is required!
 Hand in ALL Lab assignments
 Do all homework
Course Information

 Review the course outline contents


 Learning outcomes
 Detailed Content
 Method of Evaluation

5
Course Information

 Course Code: CP150


 Co-Requisites: N/A
 Pre-Requisites: N/A
 Course Hours: 42.00

6
Course Description

Operating Systems is a course designed to give the user


knowledge of the most popular and powerful operating
systems used today. In this course, the student will acquire
an understanding of both Linux and Windows operating
systems. The student will gain an understanding of the major
features of an operating system, learn how to control the
operating system, create shell script programs and install
and manage packages and operating system virtual
machines.

7
Course Learning Outcomes

1. Understand the computing environment


2. Install, manage and interact with various operating
systems
3. Install and effectively use a hypervisor client
4. Identify the differences, strengths and weaknesses of
various operating systems
5. Acquire and use relevant technical information from a
variety of sources
6. Interact with the operating system using commands and
batch files
7. Use language and terminology suited to the context 8
Course Evaluation
Hypervisor/Linux Operating System Labs - 35%
Linked to Course Learning Outcomes: 1, 2, 6, 7, 8, 10, 12, 15, 16, 17, 19
Linked to Essential Employability Skills: 6, 7, 10
Microsoft Windows Operating System Labs - 35%
Linked to Course Learning Outcomes: 3, 5, 9, 11, 13, 14, 16, 18, 19
Linked to Essential Employability Skills: 6, 10
Know My Computer Assignment- 10%
Linked to Course Learning Outcomes: 1, 4, 20
Linked to Essential Employability Skills: 6
Test(s) - 20%
Linked to Course Learning Outcomes: 1, 2, 6, 12, 14, 16, 20
Linked to Essential Employability Skills: 6, 7, 10

9
Resources

How

Oracle VirtualBox
https://www.virtualbox.org/wiki/Downloads

Linux – CentOS, RedHat, Ubuntu… ??


Class Etiquette

No chatting
 Neighbours
 Cellphones
 Facebook

No games, movies, videos, texting


What is an Operating System?

 A program that acts as an intermediary between a user of a


computer and the computer hardware

 Operating system goals:


 Execute user programs and make solving user problems easier
 Make the computer system convenient to use
 Use the computer hardware in an efficient manner
Computer System Structure
 Computer system can be divided into four components:
 Hardware – provides basic computing resources
 CPU, memory, I/O devices
 Operating system
 Controls and coordinates use of hardware among
various applications and users
 Application programs – define the ways in which the
system resources are used to solve the computing
problems of the users
 Word processors, compilers, web browsers,
database systems, video games
 Users
 People, machines, other computers
Four Components of a Computer System
Operating System Definition

 OS is a resource allocator
 Manages all resources
 Decides between conflicting requests for efficient and
fair resource use
 OS is a control program
 Controls execution of programs to prevent errors and
improper use of the computer
Operating System Definition (Cont.)

 No universally accepted definition


 “The one program running at all times on the
computer” is the kernel.
 Everything else is either
 a system program , or
 an application program.
OS features

Common features in an OS
• process management
• interrupts
• memory management
• file system
• device drivers
• networking
• security
• input/output
OS Containers

Smart phone
Tablet
PC
Cloud computing
Servers
Operating Systems

The major contenders

Windows

Linux

Mac

Different flavors and capabilities (32/64 bit)


What is meant by a 32 bit system?

• Processors generally have integer and addressing registers that


are 32 bits wide (general registers)
• In most processors these registers (address or integer) are the
only ones that are allowed to address data in memory
• Many computer instruction sets are designed so that a single
integer register can store the address to any location in the
computer's physical or virtual memory
• Therefore 32 bits hold a maximum value of 4,294,967,295
Who understands this?
Getting down to the bits

First, what is a bit?


• the smallest piece of information that can be stored
• on/off – positive/negative – 1/0

What is a nibble?
• 4 bits

What is a byte?
• 8 bits
Storage Definitions

A byte is 8 bits, and


- on most computers it is the smallest convenient chunk of storage.
A kilobyte, or KB, is 1,024 bytes
a megabyte, or MB, is 1,0242 bytes
a gigabyte, or GB, is 1,0243 bytes
a terabyte, or TB, is 1,0244 bytes
a petabyte, or PB, is 1,0245 bytes
Storage-Device Hierarchy
Summary

 OS definition
 Computer system structure
 OS features
 OS containers
 Storage Definitions and Hierarchy
Lab Work

Investigate Blackboard (does it work/exist?)


• direct: https://confederation.blackboard.com/
• through the portal: https://portal.confederationcollege.ca

Download Software
Hypervisor
https://www.virtualbox.org/wiki/Downloads
Operating Systems
Week 2
Week 2

 Process Management
 Memory Management
 File System Management
 Protection and Security
Process Management

 A process is a program in execution. It is a unit of work


within the system. Program is a passive entity,
process is an active entity.
 Process needs resources to accomplish its task
 CPU, memory, I/O, files
 Initialization data
 Process termination requires reclaim of any reusable
resources

Operating System Concepts, Ninth Edition


By: Avi Silberschatz, Peter Baer Galvin and Greg Gagne
John Wiley & Sons, Inc. ISBN 978-1-118-06333-0
Process Management Activities
The operating system is responsible for the following activities in
connection with process management:

 Creating and deleting both user and system processes


 Suspending and resuming processes
 Providing mechanisms for process synchronization
 Providing mechanisms for process communication
 Providing mechanisms for deadlock handling

Operating System Concepts, Ninth Edition


By: Avi Silberschatz, Peter Baer Galvin and Greg Gagne
John Wiley & Sons, Inc. ISBN 978-1-118-06333-0
Memory Management

 To execute a program all (or part) of the instructions must


be in memory
 All (or part) of the data that is needed by the program must
be in memory.
 Memory management determines what is in memory and
when
 Optimizing CPU utilization and computer response to
users

Operating System Concepts, Ninth Edition


By: Avi Silberschatz, Peter Baer Galvin and Greg Gagne
John Wiley & Sons, Inc. ISBN 978-1-118-06333-0
Memory Management Activities

 Memory management activities


 Keeping track of which parts of memory are
currently being used and by whom
 Deciding which processes (or parts thereof) and
data to move into and out of memory
 Allocating and deallocating memory space as
needed

Operating System Concepts, Ninth Edition


By: Avi Silberschatz, Peter Baer Galvin and Greg Gagne
John Wiley & Sons, Inc. ISBN 978-1-118-06333-0
File System Management
 File-System management
 Organizes files into directories
 Determines who can access what (Access control)
 OS activities include
 Creating and deleting files and directories
 Primitives to manipulate files and directories
 Mapping files onto secondary storage
 Backup files onto stable (non-volatile) storage media

Operating System Concepts, Ninth Edition


By: Avi Silberschatz, Peter Baer Galvin and Greg Gagne
John Wiley & Sons, Inc. ISBN 978-1-118-06333-0
Protection and Security
 Protection – any mechanism for controlling access of processes or
users to resources defined by the OS
 Security – defense of the system against internal and external
attacks
 Huge range, including denial-of-service, viruses, identity theft, theft of
service
 Systems generally first distinguish among users, to determine who
can do what
 User identities (user IDs, security IDs) include name and associated
number, one per user
 User ID then associated with all files, processes of that user to
determine access control
 Group identifier (group ID) allows set of users to be defined and controls
managed, then also associated with each process, file
 Privilege escalation allows user to change to effective ID with more
rights

Operating System Concepts, Ninth Edition


By: Avi Silberschatz, Peter Baer Galvin and Greg Gagne
John Wiley & Sons, Inc. ISBN 978-1-118-06333-0
Securing a file

Right click the file


Select properties

Click the security tab

Can apply the different permission of security


Can change the ownership of the file (if given the permissions)
A good OS is invisible

• Mostly, the users have no idea (hidden and performed behind the scenes)
• Users just interact with the application (which interacts with the OS which
interacts with the hardware)
• A desktop OS needs only worry about one user and the applications that are
running
• What about a server OS or Cloud OS?
• Many users, many applications, finite resources
Multi Thinking

The OS must…
Execute and provide services for applications software
AND
Manage the computer's resources
• Multi-tasking
• allowing multiple software processes to run at the same time
• Multi-threading
• allowing different parts of a software program to run concurrently
OS varieties

Common:
Unix (and derivatives)
MacIntosh (Apple)
Windows (Microsoft)

How many OSes are there?


Types of OS

Single-user, single task


Older cell phones / PDA
- Palm : allowed, for example, note taking only, then email generation, then ...
Single-user, multi-tasking
Modern computers
- word processing, downloading file, playing music
Multi-user
Servers
- Unix, main frame OS
Windows Server

Multi-user and/or multi-tasking?

• Many people can access different files on the system


• Many people can print through the server
• The server can be used as a web-server
• So:
• does it have multi-tasking?
• is it multi-user?
Operating Systems
Week#3
OS varieties

Uncommon ( special purpose )


specializations for mainframes
robotics
manufacturing
real-time control systems
etc.

https://en.wikipedia.org/wiki/List_of_operating_systems
Types of OS

Single-user, single task


Older cell phones / PDA
- Palm : allowed, for example, note taking only, then email generation, then ...

Single-user, multi-tasking
Modern computers
- word processing, downloading file, playing music

Multi-user
Servers
- Unix, main frame OS
In the beginning...

In April 1991, Linus Torvalds, at the time a 21-year-old student at the University of Helsinki, Finland, started
working on some simple ideas for an operating system.

He started with a task switcher in Intel 80386 assembly language and a terminal driver.

On 25 August 1991, Torvalds posted the following to comp.os.minix, a newsgroup on Usenet:

“I'm doing a (free) operating system (just a hobby, won't be big and professional like gnu)
for 386(486) AT clones. This has been brewing since April, and is starting to get ready.
I'd like any feedback on things people like/dislike in minix, as my OS resembles it
somewhat (same physical layout of the file-system (due to practical reasons) among
other things)...”
GNU/Linux
What is linux?

• An operating system

• Initially was text based

• Gained a GUI with time

• X Windows in 1992

• Feb. 1992 adopted GNU General Public License (GPL) over Linus’ previous self-drafted license,
which had not permitted commercial redistribution

• the kernel on an Android device


Licensing

Initially, Torvalds released Linux under a license which forbade any commercial use.
This was changed in version 0.12 to the GNU General Public License (GPL).
This license allows distribution and sale of possibly modified and unmodified versions of Linux but
requires that all those copies be released under the same license and be accompanied by the
complete corresponding source code.

Torvalds has described licensing Linux under the GPL as the "best thing I ever did."
Linux

and you say that... how?

https://www.youtube.com/watch?v=5IfHm6R5le0
Linux & the VM
Welcome to linux

Our starting point


- Enter your username followed by enter
- Enter your password, followed by enter (remember: you will not see anything being typed out –
security reasons)

Press this x to make the grey window go away for now


Press this bubble to make this windows go away for ever
Linux in VirtualBox

Mouse pointer integration

When you click in the window, the Linux operating system (the guest) will gain full control of the
mouse
To exit the guest window (the Linux operating system in this case) you will need to press the host
button (displayed in the bottom right of the screen)
What if you have no Right Ctrl???

Well, you are now stuck!


• Press Ctrl-Alt-Del
• Press Cancel
Now you are unstuck
Linux in VirtualBox

Mouse pointer integration

Now you are unstuck


• Press File on the VirtualBox window
• Select Preferences
• Select the Input option
• Choose the Virtual Machine tab
• Click the shortcut for the Host Key
Combination
• Press the key on your keyboard you want
to use as the new host key (I chose F12 in
this case)
• Press OK
Creating a New User

To create a new user, type in useradd followed by a space and the username for the new account
you are creating
• E.g. useradd mcgee

Do not forget to set the user’s password using passwd username


• E.g. passwd mcgee

Note: To set your own password, just type in passwd and enter

Why?
Creating a New User
Clear Command

 The clear command clears the screen and wipes the board
clean.
 It will take the user back to the start prompt of whatever
directory you are currently operating in.
 To use the clear command simply type clear

http://www.informit.com/blogs/blog.aspx?uk=The-10-Most-Important-Linux-Com
mands
mkdir Command

 creates new directories in our file system


 Syntax
 mkdir dirname

https://www.computerhope.com/unix/umkdir.htm
rmdir Command

 removes empty directories from our filesystem


 Syntax
 rmdir dirname

https://www.computerhope.com/unix/umkdir.htm
cd Command

 stands for "change directory", changes the shell's current working


directory.
 It is a builtin command, (executed directly by the shell)
 changes your working directory, to move around within
the hierarchy of your file system.
 Syntax
 cd directory

https://www.computerhope.com/unix/ucd.htm
pwd Command, whoami Command

 Pwd: prints the full pathname of the current working directory


 whoami: displays the username of the current user

https://www.computerhope.com/unix/upwd.htm
The root directory

 the first directory in your files system hierarchy.


 All other directories are subdirectories of the root
directory.
 represented by a single slash ("/").
 To change into the root directory, making it your working
directory, use the command: cd /

https://www.computerhope.com/unix/ucd.htm
The parent directory

 The parent directory of the current directory,


 the one above the current directory,
 is represented by two dots ("..").
 To change to the parent directory, making it your working
directory, use the command: cd ..

https://www.computerhope.com/unix/ucd.htm
The home directory

 the default directory when we open a new terminal session


 It holds all our settings, default documents and downloads
folder, and other personal items
 It has a special representation: a tilde ("~")
 To change to the home directory, making it your working
directory, use the command: cd ~

https://www.computerhope.com/unix/ucd.htm
Basic Commands

The folder I am in
What is in this folder? //Go back one level
This folder has nothing in it
What’s here? (one folder) //Go back one level

What’s here? (many folders)


Where am I?
The root
How do I use this function?

How do I use this function?


If you need more information on a known function, you can use three different approaches
Two are accessible from the command line
• man
• will open the manual for whatever command you are looking for
• Usage: man whoami
• enter will drop one line
• space will drop one page
• q will exit

• --help
• will ask the command to show the possible flags to use
• Usage: whoami --help
How do I use this function?

The third approach is accessible outside of the command line: the internet

e.g.
You want to know how to add a user to a wheel group, you would type
Red hat add user to wheel group
or
linux add user to wheel group

Note: Provide the language or the environment you are interested in. In this case we specify RED
HAT or linux, otherwise you will be presented with information on how to do it in other systems
Listing Files/Directories - ls Command

 lists the contents of, and optional information about


directories and files.
 With no options, ls lists the files contained in
the current directory, sorting them alphabetically
 Syntax
ls

https://www.computerhope.com/unix/uls.htm
Listing Files/Directories - ls Command

 Directories are denoted in blue color.


 Files are denoted in white
 To view all the files in directories as well as subdirectories
 Syntax
 ls -R

https://www.computerhope.com/unix/uls.htm
Listing Files/Directories - ls Command

 To view detailed information of the files in directories


 Syntax
 ls -al

https://www.computerhope.com/unix/uls.htm
Listing Files/Directories - ls Command

 Hidden files/directories in Linux begin with . “period”


 Any file/dir will not be displayed by default
 To view hidden files/directories
 Syntax
 ls -a

https://www.computerhope.com/unix/uls.htm
Creating & Viewing Files –
cat Command
 The 'cat' command is used to display text files
 Also used for copying, combining and creating new text files
 To create a new file, use the command
 cat > filename
 Add content
 Press 'ctrl + d' to save and return to command prompt

https://www.guru99.com/must-know-linux-commands.html#1
Creating & Viewing Files –
cat Command
 To view an existing file contents, use the command
 cat filename
 To concatenate/combine text of two files into
another file
 cat file1 file2 >newfile
 Only text files can be displayed and combined using
this command

https://www.guru99.com/must-know-linux-commands.html#1
Copying and Appending Files –
cat Command
 To copy the content of one file to another file use the
greater than ‘>’ symbol with the cat command as shown,
 cat file1 > file2
 To append the contents of one file to another, use the
double greater than ‘>>’ symbol with the cat command.
 cat file1 >> file2

https://www.guru99.com/must-know-linux-commands.html#1
Removing Files –
rm Command
 The rm command - removes files from your Linux OS
 the rm command will delete created files without
confirmation
 Syntax:
 rm testfile.txt

Note: the rmdir command will only delete an empty
directory, the rm command will remove both files and
directories with files in it.

http://www.informit.com/blogs/blog.aspx?uk=The-10-Most-Important-Linux-Com
mands
Moving/Renaming Files – mv Command

 The mv command - moves files from one location to


another
 Syntax:
 mv testfile.txt /home/malek/Documents
 mv command needs super user permission. Currently, we are executing the
command as a standard user

https://www.guru99.com/must-know-linux-commands.html#1
sudo Program

 Sudo program allows regular users to run programs with


the security privileges of the superuser or root
 sudo command_to_run
 sudo mv testfile.txt /home/malek/Documents

 sudo command will ask for password authentication


 After authentication, you can use mv command as usual
Moving/Renaming Files – mv Command

 The mv command – is also used to rename files


 Syntax:
 mv testfile.txt newtestfile.txt

https://www.guru99.com/must-know-linux-commands.html#1
Operating Systems

Week 4
Questions

What is meant by …

1. Hypervisor
2. Guest system
3. Host system
Answers

1. Hypervisor
• The application that is being used to run the virtual machines
• VirtualBox

2. Host system
• The computer system that is running the virtual machines
• Windows or iOS

3. Guest system
• The virtual machine that is being run
• RedHat, CentOS, ……………….
System registration
System registration

Un-registering a system

# subscription-manager remove --all


# subscription-manager unregister
# subscription-manager clean

Reference: https://access.redhat.com/solutions/253273
System registration

Registering a system

Use the following command to register the system, then automatically associate any available subscription
matching that system:
# subscription-manager register --username <username> --auto-attach

Reference: https://access.redhat.com/solutions/253273
Installing Software
How to install software

use an install application: yum

what we want yum


options (aka flags) to interact with

yum [options] [command] [package ...]


the command that we
the program we want to run want yum to execute
Installing vim

vim is an improved version of vi (the basic basic text editor)

Is vi and Vim same?


Vi is the universal text editor of Linux. If you know how to use the Vi text editor, you can edit any text file
on any mode and version of Linux. Vim is simply an improved version of Vi, but unlike Vi, Vim is not
universal. Depending on your Linux distro, it may be or may not be installed by default.
Installing vim

It is not installed by default (minimal RedHat installation)

Therefore, to install vim, we will use the yum program to install this text editor

• yum install vim


Installing vim

If the system not registered then the result will beThe Result
Installing vim

The Result

What is this?
• We can see “This system is not registered to Red Hat Subscription Management” in what the
program report to us
• We need to also remember the License agreement specified “you may install this software on up to 16
nodes”
• If we search the reported issue (first bullet) we can see that we need to register this installation of Red Hat
Enterprise Linux with Red Hat
• The feedback from the program also show us how to fix this issue
• Therefore, combining a quick internet search with the feed back will get us to type in:
subscription-manager register --username <username> --auto-attach
• I do not use the --password flag (as shown on the Red Hat website) because I do not like to ever type a
password in plain text
Yum solves the dependencies issues
Networking
Networking

MAC address

• all computers have a mac address


• mac address (physical address) is the unique address of your network card so it can be
mac address length is 48 bits. It is written usually using the Hexadecimal format
• This is equivalent to the roll number of the piece of property that you are living on
(e.g. 2401010040023240000)
• Devices on one LAN (local area networks depends on the mac address to
communicates)
Networking

Hexadecimal
Networking
Networking

IP address
• On the internet (or to communicate between LANs) we use a logical address (Internet
protocol address or IP address)
• IPv4 has 32 bits. IPv6 has 128 bits.
• This is like specifying your street address (2280 Baronwood Dr., Oakville, Ontario,
Canada). This street address is an easier way to find the property with the roll number
2401010040023240000
• But, this is still hard to remember (what is the IP address to Google’s Canadian web
server?)
• So we use names (e.g. www.google.ca)
• This is like saying John’s house (to refer to 2280 Baronwood Dr. …)
Troubleshooting

Installing the net-tools


Troubleshooting

Installing the net-tools


Where is the break?

Is it the local switch? Router? Modem?


Is it your computer?
is it the network card?
is it your network cable?
Is it the ISP?
Is it some big part of the internet backbone?
Troubleshooting

Can you send anything out to the internet using ping <ip address or named address>?
ping 74.125.21.103
ping www.google.com
Should see something like

Windows Linux
Find the break
Vi editor
Vi Editor

 The most popular and classic text editor in Linux family


 Supported by almost all Linux Distributions
 User-friendly
 Advanced versions of the vi editor is VIM which
is Vi Improved
 Vi editor has two operation modes

https://www.guru99.com/the-vi-editor.html
Vi Editor – Command Mode

 The editor opens in command mode, and understands


commands such as
 move the cursor and cut, copy, paste the text
 Saves the changes made to the file
 Commands are case sensitive

https://www.guru99.com/the-vi-editor.html
Launching the Vi editor

 To start the Vi Editor -Open the Terminal (CLI) and:


 To open a new file, at $ prompt type $vi filename.txt
 To open an existing file, use the same command i.e. type
$vi filename.txt
 The Editor will open in the command mode
 Press ‘i’ to enter the insert mode
 Add the text
 Press Esc to enter the command mode
 Type :wq to save the file
Vi Editor – Insert Mode

 This mode is used to insert text in the file


 To switch to the Insert mode from the command mode
 press 'i' on the keyboard
 In the Insert mode, any key acts as an input for the file
 To return to the command mode and save the changes
press the Esc key [and type ‘:’ key]

https://www.guru99.com/the-vi-editor.html
Vi Editor – Moving within a file
 Be in the command mode to move within a file
 Although the arrow keys can be used, the default keys
are given in the table

Keystroke Use
k Move cursor up
j Move cursor down
h Move cursor left
l Move cursor right

https://www.guru99.com/the-vi-editor.html
VI Editor – Saving and closing a file

 Be in the command mode to exit the editor and save


changes to the file.

Keystroke Use
:q! Forced quit without
saving
:w Save the file but
keep it open
:q Quit without saving
:wq Save the file and
quit
https://www.guru99.com/the-vi-editor.html
Keystrokes Action
i Insert at cursor (goes into insert mode)
a Write after cursor (goes into insert mode)
A Write at the end of line (goes into insert mode)
ESC Terminate insert mode
u Undo last change
U Undo all changes to the entire line
o Open a new line (goes into insert mode)
dd Delete line
3dd Delete 3 lines.
D Delete contents of line after the cursor
C Delete contents of a line after the cursor and insert new text. Press ESC key to
end insertion.
dw Delete word
4dw Delete 4 words
cw Change word
x Delete character at the cursor
r Replace character
R Overwrite characters from cursor onward
s Substitute one character under cursor continue to insert
S Substitute entire line and begin to insert at the beginning of the line
~ https://www.guru99.com/the-vi-editor.html
Change case of individual character
Operating Systems
Week#5
Week#5

• Shell Scripting
• What is a Shell?
• What is Shell Scripting?

https://searchdatacenter.techtarget.com/definition/shell
Types of Shell

 1. The Bourne Shell: Its prompt is $ and its derivatives


are :
 POSIX shell
 Korn Shell
 Bourne Again SHell also knew as bash
 2. The C shell: Its prompt is %, and its derivatives are:
C shell also is known as csh
 Tops C shell also is known as tcsh
What is Shell Scripting?

 A series of command for the shell to execute


 Can combine lengthy and repetitive commands into a
single script
 Can be stored and executed as needed
 Reduces the effort of the user
Creating a Shell Script

 Create a file using a vi editor


 Name script file with extension .sh [optional]
 Start the first line of the script with #! /bin/sh
 "#!" is an operator called shebang which directs the script to
the interpreter location
 Hence by using "#! /bin/sh" the script gets directed to the
bourne-shell
 Write some code and save the file
 Execute the script by typing bash filename.sh
Creating and Running a Shell Script
Creating a Shell Script – contd..

 Multiple commands can be added in a file and executed in one go


 One file can be executed from another file
Creating and Running a Shell Script

Note the difference in execute


permissions of first.sh before and
after its execution
Printing to the console
 Traditionally the first program created in a
new language is Hello World.
 The command which prints to the display is
echo.
 Let's name our script hello.sh.
 So we'll type vi hello.sh
 The echo command prints to the display.
 Let's add our hello message echo
Hello, World
 Lets save the file, and go to the command
mode
 To execute our script type bash hello.sh
 Bash is a shell, and command language. It
opens our script, and invokes the commands
in it
Ref: Lynda.com
Printing to the console – contd…

Let’s add another


line to our script

So we'll type vi
hello.sh

Let's add our hello


message echo Mars
is blue

Lets save the


file, and go to the
command mode

To execute our script


type bash hello.sh

Now both the lines


are displayed

Ref: Lynda.com
Why to use bash command?
 We use bash command to execute our script because
files by default don't have the execute permission
 Let's try ./hello.sh.
 We get an error message ‘Permission denied’
 To make a file executable, we type chmod u+x
hello.sh. This gives user the permission to execute
the script
 Okay, let's try it again. ./hello.sh. Okay, that worked
 Why to type ./before the name of the script?
 hello.sh. command not found.
 Linux systems look for commands on the path, not in
the current directory. And if the command is not in
the path, they report that it is not found.
 When we put the ./ we tell the system don't bother
with the path, here's the location of the command.
Comments
 A comment begins with the #
sign, and ends at the end of the
line.
 Let's add a comment to our script
 Save and run it again
 There’s no change in the display
 Comments are a programmer
thing not something for the user
 Not displayed like echo
The shebang
 The #! syntax used in scripts to indicate an interpreter for
execution under Linux OS
 Since our script code is written specifically for the Bash shell, we
need to make sure that our script only runs on Bash
 Go to the top of the page, insert a new line i.e. interpreter
line known as the shebang
 This line tells the system which command processor should
handle this script
 For Bash, it is
 #!/usr/bin/env bash
 Or
 #!/bin/bash
Variables

 Must begin with a letter or an underscore


 Consists of letter and numbers and underscores
 Any letter except the first can be a number
 Case sensitive
 Usually Upper case but not mandatory
Variables – contd..

 A variable is created by putting an equal sign between a


name on the left side and a value on the right side e.g.
 First_name=Ken

 Favorite_color=blue

 To display the contents of a variable proceed it with a $


 Type
 echo Hi $First_name, your favorite color
is $Favorite_color
 The value can be anything but if it has spaces it should be
wrapped in quotes
 Spaces are not allowed on either side of the equal sign
Variables – contd..
Variables – contd..

Why did we get an error?


Variables – contd..

What is wrong now?


Variables – contd..

How it has been fixed?


Variables – contd..

 Variables cannot have white space in them


 If we need them to have a space between the words
 wrap them in either single or double quotes
Passing Parameters
 Input from users can be read through parameters
 The script always receives parameters, even if it doesn't
use them
 Bash passes them through special symbols
 The first parameter, $0 is special as it is the path and
name of the executing script
 Generally, we use parameters from $1 to $9
 Parameters make it possible to be interactive with the
user.
Parameters – contd..
• The parameter $1 has
been assigned to the
variable username
• When user executes the
code and type the value,
it is assigned to the
parameter $1
Parameters – contd..
• The parameter $1 has
been assigned to the
variable username
• When user executes the
code and type the value,
it is assigned to the
parameter $1
• We can display the date
using echo, however it has
to be enclosed in ()
Getting input from users – read command

 read command is used to get input from the user


 read -p “ prompt_text”
 dash p keeps the user's input on the same line as the
prompt
 the next part is the prompt message the user will see
Getting input from users – read command
Reference

 Lynda.com
Operating Systems
Week#7
week#7

• Shell Scripting
• Branching and Loops

https://searchdatacenter.techtarget.com/definition/shell
The if statement
 The if statement lets us make decisions
 The basic form of the if statement is
 if-then-fi

 If an expression is true, then the commands between the


then and the fi are executed
 Fi sounds funny but has no deep meaning. It is simply if
backwards and denotes the end of the if statement
The if statement – Example

 If we enter Blue as the value of $1,


then it displays Color is Blue
 If we enter Red, displays nothing.
 If we don’t enter any value, we
get an error message
Boolean compares numeric values

 If equal –eq
 If not equal –ne
 If less than –lt
 If less than or equal to –le
 If greater than –gt
 If greater than or equal to –ge
Boolean compares - Example
 According to the if conditions, depending
upon the values of the parameter $1,
appropriate messages will be displayed
The if – then – else statement
 The if statement let us make decisions
 The basic form of the if-else statement is
 if-then-else-fi

 If an expression is true, then the commands following the


then are executed
 If the expression is false, then the commands following
the else up to the fi are executed
The if –then–else statement- Example

 Three outputs are


displayed
The if –then–elif-then-else statement
 The basic form of the statement is
 if-then-elif-then-else-fi

 If the first expression is true, then the


commands following the then are executed
 If the expression is false, then the expression following
elif is evaluated, if that condition is true, then the
commands following the second then are executed, and
so on
 Otherwise commands following the else up to the fi are
executed
 else has to be the last option
The if –then–elif-then-else statement- Example

 Three outputs are displayed


 However, there are two echo statements
following the first if
The while loop

 Loops give us the ability to execute our code repetitively


 We have two loops – while and for
 The while loop is structured similar to the if statement
 It begins with a test which is evaluated at the top of each
loop. If true, the commands between the do and the
done statements are executed
 Syntax:
 while [ condition ]
 do

 Statements

 done
The while loop- Example

 The loop is executed 11 times. Why?


The for loop

 The for loop also gives us the ability to execute our code
repetitively
 For each of the items in a given list, for loop performs the
given set of commands
 Syntax:
 for var in <list>
do
<commands>
done
The for loop – contd…

 The parameters can be read individually using $1, $2 and


so on but there is another special symbol, $@
 We can say NAMES=$@
 $@ holds all of the parameters the user typed in one
array.
 They can be used with the loop to iterate over each
parameter one at a time
The for loop- Example
 Here’s our code
 The loop is not executed. Why?

 The loop is executed three times


Break and Continue Statements

 Both loops import two special instructions, break and


continue
 Break causes the current loop to terminate and it begins
executing the instructions after the done statement
 Syntax:
 break
The break statement - Example
 Here’s our code
 Output with no names entered

 Output with three names entered

 The loop is stopped due to break


statement.
 Notice that the loop is stopped, not
the script
Continue Statement

 The continue statement goes immediately to the top of


the loop
 Let's replace the break with continue and see what
happens
 Syntax:
 continue
The continue statement - Example
 Here’s our code

 Output with no names entered

 Output with three names entered

 When it reads Bravo, it just goes to


the top of the loop and then continues
with the execution
References

 Lynda.com
Week 8: CPU Scheduling

Operating System Concepts – 9th Edition Silberschatz, Galvin and Gagne ©2013
Objectives

To introduce CPU scheduling, which is the basis for


multiprogrammed operating systems
To describe various CPU-scheduling algorithms

Operating System Concepts – 9th Edition 6.2 Silberschatz, Galvin and Gagne ©2013
Basic Concepts

Maximum CPU utilization


obtained with multiprogramming
CPU–I/O Burst Cycle – Process
execution consists of a cycle of
CPU execution and I/O wait
CPU burst followed by I/O burst
CPU burst distribution is of main
concern

Operating System Concepts – 9th Edition 6.3 Silberschatz, Galvin and Gagne ©2013
Process Concept (Cont.)
Program is passive entity stored on disk (executable file),
process is active
Program becomes process when executable file loaded into
memory
Execution of program started via GUI mouse clicks, command
line entry of its name, etc
One program can be several processes
Consider multiple users executing the same program

Operating System Concepts – 9th Edition 6.4 Silberschatz, Galvin and Gagne ©2013
Process State

As a process executes, it changes state


new: The process is being created
running: Instructions are being executed
waiting: The process is waiting for some event to occur
ready: The process is waiting to be assigned to a processor
terminated: The process has finished execution

Operating System Concepts – 9th Edition 6.5 Silberschatz, Galvin and Gagne ©2013
Diagram of Process State

Operating System Concepts – 9th Edition 6.6 Silberschatz, Galvin and Gagne ©2013
CPU Scheduler
Short-term scheduler selects from among the
processes in ready queue, and allocates the CPU to
one of them
Queue may be ordered in various ways
CPU scheduling decisions may take place when a
process:
1. Switches from running to waiting state
2. Switches from running to ready state
3. Switches from waiting to ready
4. Terminates
Scheduling under 1 and 4 is nonpreemptive
All other scheduling is preemptive
Consider access to shared data
Consider interrupts occurring during crucial OS
activities

Operating System Concepts – 9th Edition 6.7 Silberschatz, Galvin and Gagne ©2013
Dispatcher

Dispatcher module gives control of the CPU to the process


selected by the short-term scheduler; this involves:
switching context
switching to user mode
jumping to the proper location in the user program to
restart that program
Dispatch latency – time it takes for the dispatcher to stop
one process and start another running

Operating System Concepts – 9th Edition 6.8 Silberschatz, Galvin and Gagne ©2013
Scheduling Criteria

CPU utilization – keep the CPU as busy as possible


Throughput – # of processes that complete their execution per
time unit
Turnaround time – amount of time to execute a particular
process
Waiting time – amount of time a process has been waiting in the
ready queue

Operating System Concepts – 9th Edition 6.9 Silberschatz, Galvin and Gagne ©2013
Scheduling Algorithm Optimization Criteria

Max CPU utilization


Max throughput
Min turnaround time
Min waiting time

Operating System Concepts – 9th Edition 6.10 Silberschatz, Galvin and Gagne ©2013
First- Come, First-Served (FCFS) Scheduling

Process Burst Time


P1 24
P2 3
P3 3
Suppose that the processes arrive in the order: P1 , P2 , P3
The Gantt Chart for the schedule is:

P1 P2 P3
0 24 27 30

Waiting time for P1 = 0; P2 = 24; P3 = 27


Average waiting time: (0 + 24 + 27)/3 = 17

Operating System Concepts – 9th Edition 6.11 Silberschatz, Galvin and Gagne ©2013
FCFS Scheduling (Cont.)
Suppose that the processes arrive in the order:
P2 , P3 , P1
The Gantt chart for the schedule is:

P2 P3 P1
0 3 6 30

Waiting time for P1 = 6; P2 = 0; P3 = 3


Average waiting time: (6 + 0 + 3)/3 = 3
Much better than previous case
Convoy effect - short process behind long process
Consider one CPU-bound and many I/O-bound processes

Operating System Concepts – 9th Edition 6.12 Silberschatz, Galvin and Gagne ©2013
Shortest-Job-First (SJF) Scheduling

Associate with each process the length of its next CPU burst
Use these lengths to schedule the process with the shortest
time
SJF is optimal – gives minimum average waiting time for a given
set of processes

Operating System Concepts – 9th Edition 6.13 Silberschatz, Galvin and Gagne ©2013
Example of SJF

ProcessArrival Time Burst Time


P1 0.0 6
P2 2.0 8
P3 4.0 7
P4 5.0 3

SJF scheduling chart

P4 P1 P3 P2
0 3 9 16 24

Average waiting time = (3 + 16 + 9 + 0) / 4 = 7

Operating System Concepts – 9th Edition 6.14 Silberschatz, Galvin and Gagne ©2013
Priority Scheduling

A priority number (integer) is associated with each process

The CPU is allocated to the process with the highest priority


(smallest integer  highest priority)
Preemptive
Nonpreemptive

SJF is priority scheduling where priority is the inverse of predicted


next CPU burst time

Problem  Starvation – low priority processes may never execute

Solution  Aging – as time progresses increase the priority of the


process

Operating System Concepts – 9th Edition 6.15 Silberschatz, Galvin and Gagne ©2013
Example of Priority Scheduling

ProcessA arri Burst TimeT Priority


P1 10 3
P2 1 1
P3 2 4
P4 1 5
P5 5 2

Priority scheduling Gantt Chart

P2 P5 P1 P3 P4
0 1 6 16 18 19

Average waiting time = 8.2 msec

Operating System Concepts – 9th Edition 6.16 Silberschatz, Galvin and Gagne ©2013
Round Robin (RR)

Each process gets a small unit of CPU time (time quantum q),
usually 10-100 milliseconds. After this time has elapsed, the
process is preempted and added to the end of the ready queue.
If there are n processes in the ready queue and the time
quantum is q, then each process gets 1/n of the CPU time in
chunks of at most q time units at once. No process waits more
than (n-1)q time units.
Timer interrupts every quantum to schedule next process
Performance
q large  FIFO
q small  q must be large with respect to context switch,
otherwise overhead is too high

Operating System Concepts – 9th Edition 6.17 Silberschatz, Galvin and Gagne ©2013
Example of RR with Time Quantum = 4
Process Burst Time
P1 24
P2 3
P3 3
The Gantt chart is:

P1 P2 P3 P1 P1 P1 P1 P1
0 4 7 10 14 18 22 26 30

Average waiting time = ((10-4)+4+7)/3 = 5.66 msec


Typically, higher average turnaround than SJF, but better
response
q should be large compared to context switch time
q usually 10ms to 100ms, context switch < 10 usec

Operating System Concepts – 9th Edition 6.18 Silberschatz, Galvin and Gagne ©2013
Operating Systems
Week#9 - Windows Command Prompt
Solution - Lab#8
RR Algorithm
P1=2, P2=1, P3=8, P4=4 and P5=5 ms

Round Robin:-
Time quantum = 2 ms

P1 P2 P3 P4 P5 P3 P4 P5 P3 P5 P3

0 2 3 5 7 9 11 13 15 17 18 20

Waiting time for P1=0, P2=2, P3=(18-6)=12, P4=(11-2)=9, P5=(17-4)=13


Average waiting time = (0+2+12+9+13)/5
= 7.2 ms
This Week

• What is a Command Prompt?


• Working with Files and Directories
• Command Prompt Basics
The Command Prompt
 A traditional operating system environment unlike icon based Windows
environment.
 We use our keyboard, not mouse.
 Command Prompt works at a lower level than Windows, means that we
have more control over the machine.
 To launch Command prompt, select Start -> Run/Search and type cmd in the
box.
 The Command Prompt shows up as a terminal window, should look
something like:

C:\>

https://www.cs.princeton.edu/courses/archive/spr05/cos126/cmd-prompt.html
Command Prompt Basics

cls – clear the screen and start from the top


dir – view current directory contents
dir <characters>* - view directory contents that start with <characters>
• e.g. dir d* will display all contents (directories and files) that start with d
dir <characters>
- view the file named <characters>
- view the contents of a directory named <characters>
cmd /? – get help on the command cmd
Note: Windows is NOT case sensitive
Command Prompt Basics

cd <characters> - move into the directory named <characters>


cd \ or cd / - move to the root directory (usually c: )
cd c:\users – move into the users directory at root c

Windows now manages both forward (/) and backward (\) slashes as the same for dir and cd
Command Line Basics

mkdir <characters> - create a directory named <characters>


e.g. mkdir mydir

echo list of character – will send list of characters to the monitor


c:\Users\malsmadi> echo "hello world"
"hello world"
Command Line Basics

move sourceFilename foldername\destinationFilname – moves sourceFilename to


destinationFilename in foldername
- moves testing.bat from current directory to the root of c
move testing.bat c:\
- move theFile from directory1 to directory2 and changes the filename to
myfile
move c:\directory1\theFile c:\directory2\myfile
rename filename newFilename – will change the name of filename to newFilenaame
ren filename newFilename – is the same as rename filename newFilename
Command Line Basics

copy filename.one filename.two – will create a copy of filename.one and call it


filename.two
copy filename.one directoryname – will create a copy of filename.one in directory
directoryname
copy filename.one dir\filename.two – will create a copy of filename in directory dir with the
new filename filename.two
copy dir1\* dir2 – copy all the contents of dir1 to dir2
copy dir1 dir2 – copy all the contents of dir1 to dir2
Command Line Basics

del filename.one – will delete the file named filename.one


del directoryName – will delete the contents of directoryName
del <chars>* - will delete all files that start with <chars> in the current directory
rmdir directoryName – will delete the directory directoryName
Command Line Basics

Redirection
cmd > filename - redirect the effects of cmd to a filename, overwriting the file if it exists
cmd >> filename - redirect the effects of cmd to a filename, appending to the file if it exists
Command Line Basics

type filename –View file contents of filename without editing the file

more filename – View file contents of filename without editing the file, will stop at each new page
- space will move forward one page
- enter will move forward one line
- q will stop the viewing
Command Line Basics

whoami – if you are on a system that you need to log in to, it will display your domain and your
username
c:\Users\malsmadi\Documents\temp>whoami
confederation\malsamdi
my domain (the network) where I am logged into is confederation
my username is malsmadi
Network issues – ping command

• The ping command is usually used as a simple way to verify that


a computer can communicate over the network with another
computer or network device.
• The ping command operates by sending Internet Control
Message Protocol (ICMP) Echo Request messages
to the destination computer and waiting for a response.

https://www.lifewire.com/ping-command-2618099
Network issues

The command prompt allows for easy tracking of network issues


ping
<webaddress>
Network issues

ping comments

ping will resolve the web address to the ip address


• e.g. the ip address of the server hosting www.google.ca is 172.217.0.99
ping will let you know how poorly the connection to the server is
• I sent 4 packets and received 4 packets (no loss == good connection)
ping lets you know the connection speed between you and the server
• slowest was 9ms
• fastest was 8ms
• average was 8ms
Network issues – Ping Results

North Korean webserver is unreachable


Network issues – ipconfig Results

ipconfig displays all current TCP/IP


network configuration values and
refreshes Dynamic Host Configuration
Protocol (DHCP) and Domain Name
System (DNS) settings.
Used without parameters,
ipconfig displays the IP address, subnet
mask, and default gateway for all
adapters.

https://www.webopedia.com/TERM/I/ipconfig.html
Reference

 Lynda.com
Operating Systems
Week#10 – Batch Files in Windows
This Week

 Batch Files in Windows


 Batch Scripting
Batch Files in Windows

Batch Files

• The batch file is a group of command line functions that can be run
as a “program” or a script
• The extension is .bat or .cmd
• Files of this type are recognized and executed through an interface
(sometimes called a shell) provided by a system file called the
command interpreter.
• On Windows systems, this interpreter is known as cmd.exe.
Batch Files in Windows

Batch Files

To create a batch file, open up notepad


Enter your commands
Save the file as <yourfilename>.bat
Make sure you have File Type set to *.*
Press save
Batch Scripting
Batch Scripting is integrated to automate command
sequences which are repetitive in nature.
Some of the features of Batch Script are −
 To read inputs from users
 To use control structures such as for, if, while, switch
 To support Functions and Arrays
 To support regular expressions.
 To set up servers for different purposes
Creating Batch Files
 Batch files are normally created in notepad.
 open notepad and enter the commands required for
the script.
 For example, open notepad and enter the following
statements
 @ECHO OFF

Saving Batch Files
 Batch files have the extension of either .bat or .cmd.
 Do not use spaces while naming batch files, it might
creates issues when they are executed
 Do not use common/system batch files names such
as ping.cmd
 Remember to put the .bat or .cmd at the end of the
file name.
 Choose the “Save as type” option as “All Files”.
Executing Batch Files
1. Open the command prompt
2. Go to the location where the .bat or .cmd file is
stored.
3. Write the name of the file and press the Enter button
to execute the batch file.
Modifying Batch Files

1. Open windows explorer.


2. Go to the location where the .bat or .cmd file is
stored.
3. Right-click the file and choose the “Edit” option
from the context menu. The file will open in
Notepad for further editing.
Echo command
 Generally, the first line in a batch file has the following
command.
 @echo off
 By default, a batch file shows its command as it is
executed.
 The “@echo off” turns off this display.
 If the command is used as "echo off," it will turn off the
display for the rest of the commands, except for itself.
 The "at" sign "@" makes the command apply to itself too.
First Batch Script
 Let’s create our first batch script. Open notepad and enter
the following lines of code.
 @echo off
 Rem This is for listing down all the files in the directory
Program files
 dir "C:\Program Files" > C:\lists.txt
 echo "The program has completed"
 Save the file as “List.cmd”.
 When the script is executed, the names of the files in
C:\Program Files will be sent to the file C:\Lists.txt and in
the command prompt the message “The program has
completed” will be displayed.
First Batch Script - Output
Batch Script – Variables

 Batch Script – Variables


 Command Line Arguments: Parameters are
passed when the batch file is executed
 SetCommand: Variables are initialized via the ‘set’
command
Command Line Arguments
 Parameters are passed when the batch file is
executed
 The arguments are called from the batch files
through the variables %1, %2, %3, and so on.
 Let’s enter the following lines of code, and
 save as test.bat.
 @echo off
 echo %1
 echo %2
 echo %3
Set Command – Example -1
 Let’s enter the following lines of code, and
 save as msg.cmd
 @echo off
 set message=Hi there
 echo %message%

 However, for the following code, the output is


different:
 @echo off
 set message=Hi there
 echo message

 To display the value of the variable, the variable


needs to be enclosed in the % sign
Set Command
 Syntax:
 set /A variable-name=value
where,
 variable-name is the name of the variable you want to
set.
 value is the value which needs to be assigned to the
variable.
 /A– This switch is used if the value needs to be
numeric in nature.
Set Command – Example -2
 In order to define a variable to hold a numeric value, /A switch is used

 Let’s save the following code as sum.bat and run it:


 @echo off
 SET /A a=15
 SET /A b=10
 SET /A c=%a% + %b%
 echo %c%
Set Command – Example -3
 Let’s save the following code as math.bat and run it:
 @echo off
 SET /A a=15
 SET /A b=10
 SET /A c=%a% + %b%
 echo % % %c%
 SET /A c=%a% - %b%
 echo % % %c%
 SET /A c=%a% / %b%
 echo % % %c%
 SET /A c=%b% / %a%
 echo % % %c%
 SET /A c=%b% * %a%
 echo % % %c%
Global and Local Variables

 By definition, global variables can be accessed anywhere from a


program whereas local variables have a defined boundary in which
they can be accessed.
 In windows/DOS variables are global to the entire command
prompt session by default.
 SETLOCAL command is used to define the scope of local
variables.
 After calling SETLOCAL, any variable assignments revert upon
calling ENDLOCAL, calling EXIT, or when execution reaches the
end of file (EOF) in the script.
Global and Local Variables– Example
 Let’s save the following code as globalvar.cmd and run it:
 @echo off
 set globalvar=10
 SETLOCAL
 set var=100
 echo var = %var%
 set /A var=%var% + 5
 echo var = %var%
 echo globalvar = %globalvar%
 ENDLOCAL
 echo var = %var%
 echo globalvar = %globalvar%
Reading Input

 The Set command can also be used to read input from a


user
 The switch "/p" is used for this purpose.
 For example:
 set /p var1=
 A batch script will wait for the user to enter a value and will
assign the value to the variable var1
Reading Input – Example
 Let’s save the following code as math-io.cmd and run it:
 @echo off
 SET /p a=Enter first number
 SET /p b=Enter second number
 SET /A a=%a%
 SET /A b=%b%
 SET /A c=%a% + %b%
 echo % % %c%
 SET /A c=%a% - %b%
 echo % % %c%
 SET /A c=%a% / %b%
 echo % % %c%
 SET /A c=%b% / %a%
 echo % % %c%
 SET /A c=%b% * %a%
 echo % % %c%
Arithmetic Operators

Operator Description Example

+ Addition of two operands 1 + 2 will give 3

− Subtracts second operand 2 − 1 will give 1


from the first

* Multiplication of both 2 * 2 will give 4


operands

/ Division of the numerator 3 / 2 will give 1


by the denominator

% Modulus operator and 3 % 2 will give 1


remainder of after an
integer division
Relational Operators
Operator Description Example
EQU Tests the equality between 2 EQU 2 will give true
two objects
NEQ Tests the difference between 3 NEQ 2 will give true
two objects
LSS Checks to see if the left 2 LSS 3 will give true
object is less than the right
operand
LEQ Checks to see if the left 2 LEQ 3 will give true
object is less than or equal
to the right operand

GTR Checks to see if the left 3 GTR 2 will give true


object is greater than the
right operand
GEQ Checks to see if the left 3 GEQ 2 will give true
object is greater than or
equal to the right operand
If Statement
 General form is:
 if(condition) do_something
 Let’s save the following code as if-st.bat and run it:

 @echo off
 SET /p a=Enter first number
 SET /p b=Enter second number
 SET /A a=%a%
 SET /A b=%b%
 if %a% equ %b% echo "Both values are equal"
 if %a% lss %b% echo "%a% is less than %b%"
 if %a% gtr %b% echo "%a% is greater than %b%"
Nested If Statement

 General form is:


 if(condition1) if(condition2) do_something
 only if condition1 and condition2 are met, then the code in the
“do_something” block be executed.
Nested If Statement - Example
 @echo off
 SET /p a=Enter first number
 SET /p b=Enter second number
 SET /A a=%a%
 SET /A b=%b%
 if %a% equ %b% echo "Both values are equal"
 if %a% lss %b% echo "%a% is less than %b%"
 if %a% gtr %b% echo "%a% is greater than %b%"
 if %a% equ %b% if %a% gtr 0 echo "Both values are equal and positive"
Reference

 https://www.tutorialspoint.com/batch_script/batch_script_variables.htm
Operating
Systems
Power shell
PowerShell Command Prompt

PowerShell was introduced in the year 2006. cmd was introduced in the year 1981.

It can be opened from run by typing PowerShell. It can be opened from run by typing cmd.

It can operate with both batch commands and PowerShell


It can work only with Batch commands.
cmdlets.

It provides the ability to create aliases for cmdlets or scripts.


This can help the user to navigate between the functions It doesn’t support the creation of aliases of commands.
easily.

Output from a command can’t be passed on to other


Output from a cmdlet can be passed to other cmdlets.
commands.
Output is in the form of an object Output from a command is just text.
In cmd, a command must be finished before the next
Can execute a sequence of cmdlets put together in a script.
command is run.
Help command is available to get information regarding any No such help option is available for information regarding
cmdlets. commands.
It has access to programming libraries as it is built on .net
No such access to libraries.
framework.
It doesn’t have the ability to connect with MS online
I can connect with Microsoft cloud products.
products.
Supports Linux Systems. It doesn’t support Linux systems.
What is a PS1 file?
A PS1 file is a script, or "cmdlet," used by Windows PowerShell, a Wind
ows shell program built on Microsoft's .NET Framework. It contains a se
ries of commands written in the PowerShell scripting language. PS1 file
s are similar to .BAT and .CMD files, except that they are executed in Wi
ndows PowerShell instead of the Windows CMD.EXE and COMMAND.C
OM programs.
Scripting in Windows
A tool or a combination of tools to automate a task or series of tasks

We have already looked at using batch files


Now let’s look at a stronger scripting language to use:

PowerShell

Start PowerShell by opening a run window and typing in


powershell
The Program
PowerShell
Note: Be careful, be very careful
Yes, this is a tool worthy of the name.
PowerShell can easily cause massive configuration changes, positive or negative — so protect
yourself and establish a test environment for your learning experiences.
Also consider using the "-confirm" parameter to test configurations before execution for certain
commands.
10 Useful Command
1: Get-Help

Use this command to get help with any other command.


For example, if you want to know how the Get-Process command works, you can type:
Get-Help -Name Get-Process
and Windows will display the full command syntax

You can also use Get-Help with individual nouns and verbs. For example, to find out all the
commands you can use with the Get verb, type:
Get-Help -Name Get-*
10 Useful Command
2: Set-ExecutionPolicy

Although you can create and execute PowerShell scripts, Microsoft has disabled scripting by default
in an effort to prevent malicious code from executing in a PowerShell environment.
You can use the Set-ExecutionPolicy command to control the level of security surrounding PowerShell
scripts.

You can set an execution policy by entering the Set-ExecutionPolicy command followed by the name
of the policy. For example, if you wanted to allow scripts to run in an unrestricted manner you could
type:

Set-ExecutionPolicy Unrestricted
10 Useful Command
2: Set-ExecutionPolicy

Four levels of security are available to you:


• Restricted
• Restricted is the default execution policy and locks PowerShell down so that commands
can be entered only interactively. PowerShell scripts are not allowed to run.
• All Signed
• If the execution policy is set to All Signed then scripts will be allowed to run, but only if
they are signed by a trusted publisher.
• Remote Signed
• If the execution policy is set to Remote Signed, any PowerShell scripts that have been
locally created will be allowed to run. Scripts created remotely are allowed to run only if
they are signed by a trusted publisher.
• Unrestricted
• As the name implies, Unrestricted removes all restrictions from the execution policy.
10 Useful Command
3: Get-ExecutionPolicy

If you're working on an unfamiliar server, you'll need to know what execution policy is in use before
you attempt to run a script.
You can find out by using the Get-ExecutionPolicy command.
10 Useful Command
4: Get-Service

The Get-Service command provides a list of all of the services that are installed on the system
If you are interested in a specific service you can append the -Name switch and the name of the
service (wildcards are permitted)
When you do, Windows will show you the service's state.
10 Useful Command
5: ConvertTo-HTML

PowerShell can provide a wealth of information about the system, but sometimes you need to do
more than just view the information onscreen. Sometimes, it's helpful to create a report you can send
to someone. One way of accomplishing this is by using the ConvertTo-HTML command.

To use this command, simply pipe the output from another command into the ConvertTo-HTML
command.

You will have to use the -Property switch to control which output properties are included in the
HTML file and you will have to provide a filename.
10 Useful Command
5: ConvertTo-HTML

To see how this command might be used, think back to the previous section, where we typed Get-
Service to create a list of every service that's installed on the system.
Now imagine that you want to create an HTML report that lists the name of each service along with its
status (regardless of whether the service is running).
To do so, you could use the following command:
Get-Service | ConvertTo-HTML -Property Name, Status > C:\service1s.html
ConvertTo-HTML
get-service | convertto-html > c:\services_1.html

get-service | convertto-html -Property name, status > c:\services_2.html


10 Useful Command
6: Export-CSV

Just as you can create an HTML report based on PowerShell data, you can also export data from
PowerShell into a CSV file that you can open using Microsoft Excel.
The syntax is similar to that of converting a command's output to HTML.
At a minimum, you must provide an output filename.
For example, to export the list of system services to a CSV file, you could use the following command:

Get-Service | Export-CSV c:\service.csv


10 Useful Command
7: Select-Object

If you tried using the previous command, you know that there were numerous properties (fields)
included in the CSV file.
It's often helpful to narrow things down by including only the properties you are really interested in.
This is where the Select-Object command comes into play.
The Select-Object command allows you to specify specific properties for inclusion.
For example, to create a CSV file containing the name of each system service and its status, you
could use the following command:
Get-Service | Select-Object Name, Status | Export-CSV c:\service.csv
Get-Service | ConvertTo-HTML -Property Name, Status > C:\service1s.html
10 Useful Command
8: Get-EventLog

You can actually use PowerShell to parse your computer's event logs.
There are several parameters available, but you can try out the command by simply providing the
-Log switch followed by the name of the log file.

For example, to see the Application log, you could use the following command:
Get-EventLog -Log "Application“

Of course, you would rarely use this command in the real world.
You're more likely to use other commands to filter the output and dump it to a CSV or an HTML file.
10 Useful Command
9: Get-Process

Just as you can use the Get-Service command to display a list of all of the system services, you can
use the Get-Process command to display a list of all of the processes that are currently running on the
system.

Note:
- you will have many processes
- to have the screen pause between full screen fills, pipe the command through the more command
get-process | more
You can limit the process by typing in the process name after the command:
get-process chrome
gps c*
10 Useful Command
10: Stop-Process

Sometimes, a process will freeze up.


When this happens, you can use the Get-Process command to get the name or the process ID for the
process that has stopped responding.
You can then terminate the process by using the Stop-Process command.
You can terminate a process based on its name or on its process ID.
For example, you could terminate Notepad by using one of the following commands:
Stop-Process -Name notepad
or
Stop-Process -ID 2668
The cmdlets of PowerShell
Command alias Cmdlet name Description of command
% ForEach-Object Performs an operation against each item in a collection of input obje
cts.
? Where-Object Selects objects from a collection based on their property values.
ac Add-Content Appends content, such as words or data, to a file.
... ... ...

Too many for making slides, click this instead 


Playing around

The only way to learn is to play (carefully) and Google

For example, how do you find all processes that have a process id > 6000?
get-process | where-object {$_.id -gt 6000}
Playing around
To properly understand

Sometimes what we see is not the way it really is


For example, I want all the aliases that reference a command that has obj in it

But there are aliases with obj in them:


Playing around
To properly understand

So let’s see what get-alias REALLY returns

Aha!!!
Not name, but DisplayName
Playing around
Correct the property name
More than one way...

For example, how do you find all processes that have a process id > 6000?
get-process | where-object {$_.id -gt 6000}
get-process | where-object id -gt 6000
get-process | ? {$_.id -gt 6000}
get-process | ? id -gt 6000

How do you get all the process with the name chrome in it?
get-process chrome
get-process –name chrome
get-process | where-object {$_.processname -eq "chrome"}
PowerShell

Copy and Paste

Simply left click and drag to highlight


One right click will copy the information and then unselect the text
With no selection, right click will paste
Lab Work
Operating
Systems
Week 11
Error Management
Is it broken?

There are always times when your system starts acting up


- running slow
- shutting down programs for no apparent reason
- not running correctly

The question becomes, why?


So that leads to the next question: how?
How do I know?
Where can we find the answers?
The choice

Do I just restart the computer and hope that it all goes away
(it very well may)?

or

Do I jump down the rabbit hole and try to track it out?


Follow the trail
We are computer programmers

Innate desire to know:


why
- why does it crash
where
- where is the issue
what
- what is the issue
how
- how can I duplicate it
- how can I prevent it
Event Viewer
Windows 7/8/10
Event Viewer
Windows 7/8/10
Tin Foil Hat Area?

The biggest problem with Event Viewer: it can be really confusing


• there are a lot of warnings
• there are a lot errors
• there are a lot informational messages

Without knowing what it all means, you can assume (incorrectly) that your
computer is broken or infected when there’s nothing really wrong
The Layout
Left-hand pane
- folder view
- you can find all of the different event logs, as well as the views that can be
customized with events from many logs at once
- E.g. Administrative Events view in recent versions of Windows displays all of
the Error, Warning, and Critical events whether they originated from the
Application log or the System log.
The Layout
Middle pane
- list of events
- clicking on an event will display the details in the preview pane – or you can
double-click on any of them to pull it up in a separate window, which can be
handy when you are looking through a big set of events and want to find all
the important things before beginning an internet search

Right-hand pane
- Quick access to actions such as
- creating custom views
- filtering
- creating a scheduled task based on a particular event
The events
• These are what we are here for
• They can run a range from specific and obvious things we can fix to vague
information that makes no sense and cannot be found through searches on
the internets
• They may show issues that are occurring with your system
• They may show details of specific events that are occurring with a program

Important Note: There are always going to be errors and warnings in the event
log, and you can’t solve all of them.
The most important thing is to use Event Viewer to troubleshoot problems you
are already having, rather than trying to find problems that you don’t know about
yet
Event Details
The Event Log Fields
Log Name – while in older versions of Windows everything got dumped into the
Application or System log, in the more modern editions there are dozens or
hundreds of different logs to choose from. Each Windows component will most
likely have its own log.
Source – this is the name of the software that generates the log event. The name
usually doesn’t directly match with a filename, of course, but it is a
representation of which component did it.
Event ID – the all-important Event ID can actually be a little confusing. If you were
to Google for “event ID 122” that you see in the next screenshot, you wouldn’t end
up with very useful information unless you also include the Source, or application
name. This is because every application can define their own unique Event IDs.
The Event Log Fields
Level – This tells you how severe the event is – Information just tells you that
something has changed or a component has started, or something has been
completed. Warning tells you that something might be going wrong, but it isn’t all
that important yet. The error tells you that something happened that shouldn’t
have happened, but isn’t always the end of the world. Critical, on the other hand,
means something is broken somewhere, and the component that triggered this
event has probably crashed.
User – this field tells you whether it was a system component or your user
account that was running the process that caused the error. This can be helpful
when looking through things.
OpCode – this field theoretically tells you what activity the application or
component was doing when the event was triggered. In practice, however, it will
almost always say “Info” and is pretty useless.
The Event Log Fields
Computer – on your home desktop, this will usually just be your PC’s name, but
in the IT world, you can actually forward events from one computer or server to
another computer. You can also connect Event Viewer to another PC or server.
Task Category – this field is not always used, but it ends up basically being an
informational field that tells you a bit more information about the event.
Keywords – this field is not usually used, and generally contains useless
information.
Going to Search
As a rule of thumb, you should try searching by the general description, the
Event ID and the Source, or a combination of those values.
Just remember that the Event ID is unique… for each application.
There is a lot of overlap and you can’t just search for “Event ID 122” because you
will get a lot of nonsense.
Search Results
Beware Internet Sites with “Solutions” for Event ID “Problems”
There are many web sites out there that automatically generate pages for every
single event ID, and then populate them with nonsense.
Some sites have valid responses.
However, many have useless results.
Worse than useless, some offer to solve the problem if you just download some
piece of software for your free analysis. Almost always, these sites are ads, and
the software “solution” is a fraud.

There is NO software package that can solve all of your event log problems
Good result. Useful
information? Need to
open and read

Questionable
I don’t think so
Event Viewer
Left hand pane.
Looking at the sections more closely:

What is this for? Basic explanation of this application


Event Viewer
A summary of the different events that have been recently logged
Diagnostics Performance
Windows Diagnostics Performance Log

There are a lot of interesting logs to look at when you are troubleshooting
One of the most interesting is found by browsing through the folders to the
following location:

Microsoft \ Windows \ Diagnostics-Performance

• An event log that shows all of the things that Windows logs internally for
performance checking
• If your computer boots up slower than normal, Windows will usually have a log
entry for it, and will often list out the component that caused Windows to boot
more slowly
Task Manager
Task Manager
This is one of the most used programs in managing programs on your system
It shows
- running applications
- running process
- running services
- memory consumption
- hard drive time utilization
- network usage
Task Manager
Right click on an empty space on your taskbar
Select Start Task Manager
or
Press Alt-Ctrl-Del
Select Start Task Manager
Windows 7
Windows 8 / 10
Understanding the Task Manager

Hide When Minimized


- When minimized it will
disappear into the task
tray

Show process from all


users
- Will show all the
processes that are
running on the
computer
Process Tab
Performance Tab
This tab will show
- how the different resources are currently being consumed
- how the resources have been consumed over the past little while
Performance Tab
Resource Monitor
And for more information

To get more information, you can use the Resource Monitor on the Performance
tab
Resource Monitor

It provides greater detail on how the resources are being managed


- how many threads a given program is running
- how much memory it is using (dedicated, shared, etc)
- how much memory is available
- how much memory is being used up
Resource Monitor
Resource Monitor
Windows PowerShell ISE
The Windows PowerShell Integrated Scripting Environment (ISE) is a host
application for Windows PowerShell. In the ISE, you can run commands and
write, test, and debug scripts in a single Windows-based graphic user
interface.
Windows PowerShell ISE

You might also like