gl120 linux fundamentals - itcourseware · 2013-02-15 · linux fundamentals rhel6 sles11 u12.04...

90
GL120 LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts to audience members, are copyright ©2013 Guru Labs L.C. No part of this publication may be stored in a retrieval system, transmitted or reproduced in any way, including, but not limited to, photocopy, photograph, magnetic, electronic or other record, without the prior written permission of Guru Labs. This curriculum contains proprietary information which is for the exclusive use of customers of Guru Labs L.C., and is not to be shared with personnel other than those in attendance at this course. This instructional program, including all material provided herein, is supplied without any guarantees from Guru Labs L.C. Guru Labs L.C. assumes no liability for damages or legal action arising from the use or misuse of contents or details contained herein. Photocopying any part of this manual without prior written consent of Guru Labs L.C. is a violation of federal law. This manual should not appear to be a photocopy. If you believe that Guru Labs training materials are being photocopied without permission, please email [email protected] or call 1-801-298-5227. Guru Labs L.C. accepts no liability for any claims, demands, losses, damages, costs or expenses suffered or incurred howsoever arising from or in connection with the use of this courseware. All trademarks are the property of their respective owners. Version: GL120S-R6S11U1204-I00 EVALUTION COPY Unauthorized reproduction or distribution is prohibited.

Upload: others

Post on 19-Jun-2020

18 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

GL120LINUXFUNDAMENTALSRHEL6 SLES11 U12.04

The contents of this course and all its modules and related materials, including handouts toaudience members, are copyright ©2013 Guru Labs L.C.

No part of this publication may be stored in a retrieval system, transmitted or reproduced in anyway, including, but not limited to, photocopy, photograph, magnetic, electronic or other record,without the prior written permission of Guru Labs.

This curriculum contains proprietary information which is for the exclusive use of customers of GuruLabs L.C., and is not to be shared with personnel other than those in attendance at this course.

This instructional program, including all material provided herein, is supplied without any guaranteesfrom Guru Labs L.C. Guru Labs L.C. assumes no liability for damages or legal action arising fromthe use or misuse of contents or details contained herein.

Photocopying any part of this manual without prior written consent of Guru Labs L.C. is a violationof federal law. This manual should not appear to be a photocopy. If you believe that Guru Labstraining materials are being photocopied without permission, please email [email protected] orcall 1-801-298-5227.

Guru Labs L.C. accepts no liability for any claims, demands, losses, damages, costs or expensessuffered or incurred howsoever arising from or in connection with the use of this courseware. Alltrademarks are the property of their respective owners.

Version: GL120S-R6S11U1204-I00

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 2: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

ii

Table of ContentsChapter 1WHAT IS LINUX? 1

Unix and its Design Principles 2FSF and GNU 4GPL – General Public License 5The Linux Kernel 6Linux Kernel and Versioning 7Components of a Distribution 9Slackware 10SUSE Linux Products 11Debian 12Ubuntu 13Red Hat Linux Products 14Oracle Linux 16Mandriva 17

Chapter 2LOGIN AND EXPLORATION 1

Logging In 2Running Programs 3Interacting with Command Line 4The X Window System 6Starting X 7Gathering Login Session Info 9Gathering System Info 10got root? 11Switching User Contexts 12sudo 13Help from Commands and Documentation 15Getting Help with man & info 16

Lab Tasks 191. Login and Discovery 202. Help with Commands 253. Switching Users With su 29

Chapter 3THE LINUX FILESYSTEM 1

Filesystem Support 2Unix/Linux Filesystem Features 3Filesystem Hierarchy Standard 4Navigating the Filesystem 6

Displaying Directory Contents 7Filesystem Structures 8Determining Disk Usage With df and du 9Determining Disk Usage With baobab 10Disk Usage with Quotas 12File Ownership 13Default Group Ownership 14File and Directory Permissions 15File Creation Permissions with umask 17Changing File Permissions 19SUID and SGID on files 21SGID and Sticky Bit on Directories 22User Private Group Scheme 23

Lab Tasks 251. Navigating Directories and Listing Files 262. Disk and Filesystem Usage 283. File and Directory Ownership and Permissions 30

Chapter 4MANIPULATING FILES 1

Directory Manipulation 2File Manipulation 3Deleting and Creating Files 4Physical Unix File Structure 5Filesystem Links 6File Extensions and Content 7Displaying Files 8Previewing Files 9Displaying Binary Files 10Searching the Filesystem 11Alternate Search Method 12Producing File Statistics 13

Lab Tasks 141. Manipulating Files and Directories 152. File Examination & Search Commands 20

Chapter 5SHELL BASICS 1

Role of Command Shell 2Communication Channels 3File Redirection 4

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 3: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

iii

Piping Commands Together 5Filename Matching 6File Globbing and Wildcard Patterns 7Brace Expansion 8Shell and Environment Variables 9Key Environment Variables 10General Quoting Rules 11Nesting Commands 12Multiple and Multi-line Commands 13

Lab Tasks 141. Connecting Commands 152. Wildcard File Matching 203. Shell Variables 224. Shell Meta-Characters 245. Command Substitution 27

Chapter 6ARCHIVING AND COMPRESSION 1

Archives with tar 2Archives with cpio 3The gzip Compression Utility 4The bzip2 Compression Utility 5The XZ Compression Utility 6The PKZIP Archiving/Compression format 7

Lab Tasks 81. Archiving and Compression 9

Chapter 7TEXT PROCESSING 1

Searching Inside Files 2The Streaming Editor 3Text Processing with awk 4Replacing Text Characters 5Text Sorting 6Duplicate Removal Utility 7Extracting Columns of Text 8Combining Files and Merging Text 9Comparing File Changes 10

Lab Tasks 121. Text Processing 13

Chapter 8REGULAR EXPRESSIONS 1

Regular Expression Overview 2Regular Expressions 3RE Character Classes 4RE Quantifiers 5RE Parenthesis 6Lab Tasks 7

1. Pattern Matching with Regular Expressions 82. Extended Regular Expressions 103. Using Regular Expressions With sed 13

Chapter 9TEXT EDITING 1

Text Editing 2Pico/GNU Nano 3Pico/Nano Interface 4Pico/Nano Shortcuts 5vi and Vim 6Learning vi 7Basic vi 8Intermediate vi 9

Lab Tasks 121. Text Editing with Nano 132. Text Editing with Vim 16

Chapter 10COMMAND SHELLS 1

Shells 2Identifying the Shell 4Changing the Shell 5Bourne sh: Configuration Files 6Script Execution 7Bourne sh: Prompts 8bash: Bourne-Again Shell 9bash: Configuration Files 10bash: Command Line History 11bash: Command Editing 12bash: Command Completion 14bash: "shortcuts" 15bash: prompt 16Setting Resource Limits via ulimit 17

Lab Tasks 181. Linux Shells 192. Bash History 23

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 4: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

iv

3. Aliases 264. Bash Login Scripts 285. The Z Shell 30

Chapter 11INTRODUCTION TO SHELL SCRIPTING 1

Shell Script Strengths and Weaknesses 2Example Shell Script 3Positional Parameters 4Input & Output 5Doing Math 7Comparisons with test 8Exit Status 9Conditional Statements 10Flow Control: case 11The for Loop 13The while and until Loops 14

Lab Tasks 151. Writing a Shell Script 16

Chapter 12PROCESS MANAGEMENT AND JOB CONTROL 1

What is a Process? 2Process Lifecycle 3Process States 4Viewing Processes 5Signals 6Tools to Send Signals 7Job Control Overview 8Job Control Commands 9Persistent Shell Sessions with Screen 10Using screen 11Advanced Screen 13

Lab Tasks 141. Job Control Basics 152. Process Management and Job Control Basics 213. Screen Basics 254. Using Screen Regions 28

Chapter 13PROCESS ADMINISTRATION 1

Automating Tasks 2at/batch 3

cron 5The crontab Command 6crontab Format 7/etc/cron.*/ Directories 8Anacron 10Managing Processes 12Tuning Process Scheduling 13

Lab Tasks 151. Creating and Managing User Cron Jobs 162. Adding System cron Jobs 19

Chapter 14MANAGING SOFTWARE 1

Downloading with FTP 2FTP 3lftp 5Command Line Internet – Non-interactive 6Command Line Internet – Interactive 8Managing Software Dependencies 9Using the YUM command 11YUM package groups 14Configuring YUM 15Popular Yum Repositories 16Using the Zypper command 18Zypper Services and Catalogs 20The dselect & APT Frontends to dpkg 21Aptitude 22Configuring APT 23Lab Tasks 25

1. Command Line File Transfers 262. Using YUM [R6] 303. Using Zypper [S11] 364. Managing YUM Repositories [R6] 415. Managing Zypper Repositories [S11] 44

Chapter 15MESSAGING 1

System Messaging Commands 2Controlling System Messaging 4Internet Relay Chat 5Instant Messenger Clients 6Electronic Mail 7Sending Email with sendmail 8

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 5: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

v

Sending and Receiving Email with mailx 9Sending and Receiving Email with mutt 11Sending Email with Pine 12Evolution 13Lab Tasks 14

1. Command Line Messaging 152. Command Line Email 19

Chapter 16PRINTING 1

Linux Printer Sub-systems 2Legacy Print Systems 3Common UNIX Printing System 4Defining a Printer 5Standard Print Commands 7Format Conversion Utilities 8Ghostscript 9enscript and mpage 10

Lab Tasks 111. Printing 12

Chapter 17THE SECURE SHELL (SSH) 1

Secure Shell 2ssh and sshd Configuration 3Accessing Remote Shells 4Transferring Files 5Alternative sftp Clients 6SSH Key Management 7ssh-agent 8Lab Tasks 9

1. Introduction to ssh and scp 102. SSH Key-based User Authentication 123. Using ssh-agent 15

Chapter 18MOUNTING FILESYSTEMS & MANAGING REMOVABLE MEDIA 1

Filesystems Concept Review 2Mounting Filesystems 3NFS 4SMB 5Filesystem Table (/etc/fstab) 6AutoFS 7

Removable Media 8Lab Tasks 10

1. Accessing NFS Shares 112. On-demand filesystem mounting with AutoFS 13

Appendix ATHE X WINDOW SYSTEM 1

The X Window System 2X Modularity 3X.Org Drivers 4Configuring X Manually 5Automatic X Configuration 6Automatic X Configuration – SLES 7Xorg and Fonts 8Installing Fonts for Modern Applications 10Installing Fonts for Legacy Applications 12The X11 Protocol and Display Names 13Display Managers and Graphical Login 14Starting X Apps Automatically 16X Access Control 18Remote X Access (historical/insecure approach) 20Remote X Access (modern/secure approach) 22XDMCP 24Remote Graphical Access With VNC and RDP 26Specialized X Servers 28

Lab Tasks 291. Remote X with XDMCP [R6 S11] 302. Configure X Security [R6 S11] 373. Configure a VNC Server [R6] 434. Configure a VNC Server [S11] 485. Launching X Apps Automatically [R6 S11] 536. Secure X [R6 S11] 58

Appendix BEMACS 1

Emacs 2The Emacs Interface 3Basic Emacs 4More Emacs Commands 6Lab Tasks 7

1. Text Editing with Emacs 8

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 6: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

vi

Typographic Conventions

The fonts, layout, and typographic conventions of this book have beencarefully chosen to increase readability. Please take a moment tofamiliarize yourself with them.

A Warning and Solution

A common problem with computer training and reference materials isthe confusion of the numbers "zero" and "one" with the letters "oh" and"ell". To avoid this confusion, this book uses a fixed-width font that makeseach letter and number distinct.

Typefaces Used and Their Meanings

The following typeface conventions have been followed in this book:

fixed-width normal ⇒ Used to denote file names and directories. Forexample, the /etc/passwd file or /etc/sysconfig/directory. Alsoused for computer text, particularily command line output.

fixed-width italic ⇒ Indicates that a substitution is required. Forexample, the string stationX is commonly used to indicate that thestudent is expected to replace X with his or her own station number,such as station3.

fixed-width bold ⇒ Used to set apart commands. For example, thesed command. Also used to indicate input a user might type on thecommand line. For example, ssh -X station3.

fixed-width bold italic ⇒ Used when a substitution is requiredwithin a command or user input. For example, ssh -X stationX.

fixed-width underlined ⇒ Used to denote URLs. For example,http://www.gurulabs.com/.

variable-width bold ⇒ Used within labs to indicate a required studentaction that is not typed on the command line.

Occasional variations from these conventions occur to increase clarity.This is most apparent in the labs where bold text is only used to indicatecommands the student must enter or actions the student must perform.

0 OThe number

"zero".The letter

"oh".

1 lThe number

"one".The letter

"ell".

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 7: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

vii

Typographic Conventions

Terms and Definitions

The following format is used to introduce and define a series of terms:

deprecate ⇒ To indicate that something is considered obsolete, withthe intent of future removal.

frob ⇒ To manipulate or adjust, typically for fun, as opposed to tweak.grok ⇒ To understand. Connotes intimate and exhaustive knowledge.hork ⇒ To break, generally beyond hope of repair.hosed ⇒ A metaphor referring to a Cray that crashed after the

disconnection of coolant hoses. Upon correction, users were assuredthe system was rehosed.

mung (or munge) ⇒ Mash Until No Good: to modify a file, oftenirreversibly.

troll ⇒ To bait, or provoke, an argument, often targeted towards thenewbie. Also used to refer to a person that regularly trolls.

twiddle ⇒ To make small, often aimless, changes. Similar to frob.

When discussing a command, this same format is also used to show anddescribe a list of common or important command options. For example,the following ssh options:

-X ⇒ Enables X11 forwarding. In older versions of OpenSSH that donot include -Y, this enables trusted X11 forwarding. In newer versionsof OpenSSH, this enables a more secure, limited type of forwarding.

-Y ⇒ Enables trusted X11 forwarding. Although less secure, trustedforwarding may be required for compatibility with certain programs.

Representing Keyboard Keystrokes

When it is necessary to press a series of keys, the series of keystrokeswill be represented without a space between each key. For example, thefollowing means to press the "j" key three times: jjj

When it is necessary to press keys at the same time, the combination willbe represented with a plus between each key. For example, the followingmeans to press the "ctrl," "alt," and "backspace" keys at the same time:Ó¿Ô¿×. Uppercase letters are treated the same: Ò¿A

Line Wrapping

Occasionally content that should be on a single line, such as commandline input or URLs, must be broken across multiple lines in order to fiton the page. When this is the case, a special symbol is used to indicateto the reader what has happened. When copying the content, the linebreaks should not be included. For example, the following hypotheticalPAM configuration should only take two actual lines:

password required /lib/security/pam_cracklib.so retry=3a type= minlen=12 dcredit=2 ucredit=2 lcredit=0 ocredit=2

password required /lib/security/pam_unix.so use_authtok

Representing File Edits

File edits are represented using a consistent layout similar to the unifieddiff format. When a line should be added, it is shown in bold with aplus sign to the left. When a line should be deleted, it is shown struckout with a minus sign to the left. When a line should be modified, itis shown twice. The old version of the line is shown struck out with aminus sign to the left. The new version of the line is shown below theold version, bold and with a plus sign to the left. Unmodified lines areoften included to provide context for the edit. For example, the followingdescribes modification of an existing line and addition of a new line tothe OpenSSH server configuration file:

File: /etc/ssh/sshd_config #LoginGraceTime 2m- #PermitRootLogin yes+ PermitRootLogin no+ AllowUsers sjansen #StrictModes yes

Note that the standard file edit representation may not be used when itis important that the edit be performed using a specific editor or method.In these rare cases, the editor specific actions will be given instead.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 8: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

viii

Lab Conventions

Lab Task Headers

Every lab task begins with three standard informational headers:"Objectives," "Requirements," and "Relevance". Some tasks also include a"Notices" section. Each section has a distinct purpose.

Objectives ⇒ An outline of what will be accomplished in the lab task.Requirements ⇒ A list of requirements for the task. For example,

whether it must be performed in the graphical environment, orwhether multiple computers are needed for the lab task.

Relevance ⇒ A brief example of how concepts presented in the labtask might be applied in the real world.

Notices ⇒ Special information or warnings needed to successfullycomplete the lab task. For example, unusual prerequisites or commonsources of difficulty.

Command Prompts

Though different shells, and distributions, have different promptcharacters, examples will use a $ prompt for commands to be run asa normal user (like guru or visitor), and commands with a # promptshould be run as the root user. For example:

$ whoamiguru$ su -Password: password# whoamiroot

Occasionally the prompt will contain additional information. For example,when portions of a lab task should be performed on two different stations(always of the same distribution), the prompt will be expanded to:

stationX$ whoamigurustationX$ ssh root@stationYroot@stationY’s password: passwordstationY# whoamiroot

Variable Data Substitutions

In some lab tasks, students are required to replace portions of commandswith variable data. Variable substitution are represented using italic fonts.For example, X and Y.

Substitutions are used most often in lab tasks requiring more than onecomputer. For example, if a student on station4 were working with astudent on station2, the lab task would refer to stationX and stationY

stationX$ ssh root@stationY

and each would be responsible for interpreting the X and Y as 4 and 2.

station4$ ssh root@station2

Truncated Command Examples

Command output is occasionally omitted or truncated in examples. Thereare two type of omissions: complete or partial.

Sometimes the existence of a command’s output, and not its content, isall that matters. Other times, a command’s output is too variable toreliably represent. In both cases, when a command should produceoutput, but an example of that output is not provided, the followingformat is used:

$ cat /etc/passwd. . . output omitted . . .

In general, at least a partial output example is included after commands.When example output has been trimmed to include only certain lines,the following format is used:

$ cat /etc/passwdroot:x:0:0:root:/root:/bin/bash. . . snip . . .clints:x:500:500:Clint Savage:/home/clints:/bin/zsh. . . snip . . .

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 9: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

ix

Lab Conventions

Distribution Specific Information

This courseware is designed to support multiple Linux distributions.When there are differences between supported distributions, eachversion is labeled with the appropriate base strings:

R ⇒ Red Hat Enterprise Linux (RHEL)S ⇒ SUSE Linux Enterprise Server (SLES)U ⇒ Ubuntu

The specific supported version is appended to the base distributionstrings, so for Red Hat Enterprise Linux version 6 the complete stringis: R6.

Certain lab tasks are designed to be completed on only a sub-set ofthe supported Linux distributions. If the distribution you are using is notshown in the list of supported distributions for the lab task, then youshould skip that task.

Certain lab steps are only to be performed on a sub-set of the supportedLinux distributions. In this case, the step will start with a standardizedstring that indicates which distributions the step should be performed on.When completing lab tasks, skip any steps that do not list your chosendistribution. For example:

[R4] This step should only be performed on RHEL4.1)Because of a bug in RHEL4's Japanese fonts...

Sometimes commands or command output is distribution specific. Inthese cases, the matching distribution string will be shown to the left ofthe command or output. For example:

$ grep -i linux /etc/*-release | cut -d: -f2Red Hat Enterprise Linux Server release 6.0 (Santiago)[R6]

SUSE Linux Enterprise Server 11 (i586)[S11]

Action Lists

Some lab steps consist of a list of conceptually related actions. Adescription of each action and its effect is shown to the right or underthe action. Alternating actions are shaded to aid readability. For example,the following action list describes one possible way to launch and usexkill to kill a graphical application:

Ô¿Å Open the "Run Application" dialog.

xkillÕ Launch xkill. The cursor should change,usually to a skull and crossbones.

Click on a window of the application to kill.Indicate which process to kill by clicking onit. All of the application’s windows shoulddisappear.

Callouts

Occasionally lab steps will feature a shaded line that extends to a notein the right margin. This note, referred to as a "callout," is used to provideadditional commentary. This commentary is never necessary to completethe lab succesfully and could in theory be ignored. However, calloutsdo provide valuable information such as insight into why a particularcommand or option is being used, the meaning of less obvious commandoutput, and tips or tricks such as alternate ways of accomplishing the taskat hand.

On SLES10, the sux commandcopies the MIT-MAGIC-COOKIE-1so that graphical applicationscan be run after switchingto another user account. TheSLES10 su command did notdo this.

$ sux -[S10]

Password: password# xclock

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 10: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 11: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

Chapter

1WHAT IS LINUX?

ContentUnix and its Design Principles . . . . . . . . . . . . . . . . . . . . . . . . 2FSF and GNU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4GPL – General Public License . . . . . . . . . . . . . . . . . . . . . . . . 5The Linux Kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Linux Kernel and Versioning . . . . . . . . . . . . . . . . . . . . . . . . . . 7Components of a Distribution . . . . . . . . . . . . . . . . . . . . . . . . 9Slackware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10SUSE Linux Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Debian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Ubuntu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Red Hat Linux Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14Oracle Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Mandriva . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 12: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

1-2

Unix and its Design Principles

Inherits features from Multics such as the hierarchical filesystemEverything is a fileSmall single-purpose programsAbility to pipe small programs together to accomplish more complextasks

The kernel makes minimum policy decisions, leaving things up toeasily modifiable userland programs

All configuration data stored as text, (e.g. ASCII, UTF-8)

Unix Origins

The original batch processing systems of the 1950s were limited toprocessing only one job at a time. Batch processing systems werereplaced with time sharing systems, such as the Compatible TimeSharing System. In 1964, AT&T began discussions with MIT and GE tocreate a second generation time sharing system, Multics. Workstarted at BTL in 1965. Over the next four years, cutting-edgeresearch was done by the academics at MIT, and the computerscientists at GE and AT&T, changing the mind set of how computersshould operate, such as the view that computing should be aninteractive and multi-user experience.

AT&T pulled out of the Multics project in 1969. The Multics projecthad been ambitious, and each party had differing visions that werehard to reconcile. Bell Labs researcher Ken Thompson startedworking on an alternative to Multics, later nick named Unics by BrianKernighan, to distinguish it from the complexity of Multics. It wasoriginally written in machine language for the DEC PDP-7 and 9, butran primarily on the PDP-11 through Edition 7.

Unix Design Principles

The researchers, led by Doug McIlroy, developed a set of principlesto guide their work. Among these principles were:

1. Make each program do one thing well. To do a new job, buildafresh rather than complicate old programs by adding newfeatures.

2. Expect the output of every program to become the input to

another, as yet unknown, program. Don't clutter output withextraneous information. Avoid stringently columnar or binaryinput formats. Don't insist on interactive input.

3. Design and build software, even operating systems, to be triedearly, ideally within weeks. Don't hesitate to throw away theclumsy parts and rebuild them.

4. Use tools in preference to unskilled help to lighten aprogramming task, even if you have to detour to build the toolsand expect to throw some of them out after you've finishedusing them.

(From M.D. McIlroy, E.N.Pinson, and B.A. Tague, Unix Time-SharingSystem Forward, The Bell System Technical Journal, July -Aug. 1978vol 57, number 6 part 2, pg. 1902.)

Small programs and pipes are flexible, and build simple, fast solutionsto otherwise complex tasks.

Plain text config data facilitates remote administration. The ANSI textoriginally used is limited by the 127 characters available on USkeyboards. UTF-8 (Unicode), the Plan 9 character set developed byThompson, is now used by many Unix systems, offering aninternational character set while remaining backwards compatible toANSI text. The file command (covered later) will report most textfiles as ASCII text, as it is rare to see characters used outside Latin-1(extended ASCII), though not as rare as it used to be.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 13: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

1-3

The Unix family

In February 1973, the third edition of Unix was released. The prefaceof the UNIX PROGRAMMER'S MANUAL claimed an increase from 10installations to 16, but what was more important was reflected in thisstatement under "Writing a program": "The three principal languagesin Unix are assembly language (see as(1)), FORTRAN (see fc(1)),and C (see cc(1)) . . . " The new C language was a modification ofThompson's B interpreter, adding types, and a compiler. C's simplicityled to the fourth edition Unix being rewritten in C, and to its dominantuse in the Unix family of operating systems.

Starting with the sixth edition of Unix, AT&T licensed the source codeat low cost; however, Bell Labs kept the UNIX name trademarked,and closely held. After AT&T sold UNIX to Novell, the UNIX trademarkwas sold to the Open Group, and the source code licensed to theSanta Cruz Operation. Each licensee had to come up with their ownname, (hence groups that used names like USENIX). Though UNIX isa trademark, in common usage the capitalization "Unix" is used. Seethe preface to A Quarter Century of UNIX (Peter H. Salus – ISBN-13:9780201547771) andhttp://www.opengroup.org/tm-guidelines.htm.

There are two main branches in the Unix family tree, the System Vbranch and the BSD branch. The System V branch was maintained byAT&T and the BSD branch by the University of California at Berkeley,and enhancement of the research system. There was lots ofcross-pollination of features between the two branches, especially inlater editions of research Unix. System V Release 4 is essentially amerger of these two branches. Today, the BSD branch continues inseveral open-source projects, but System V exists primarily incommercial off-shoots, such as Oracle Solaris. Several clones areavailable including Minix and Linux. See http://levenez.com/unix/for a graphical chart of Unix and its derivatives.

Growth of Unix

As the DEC series systems gave way to Sun workstations, mail ordercomputer kits, and the PC era of home computers, it was realized byThompson, Pike, and others that a redesign was needed to takeadvantage of these new, cheaper technologies. Plan 9 succeededUnix as a from scratch rewrite, incorporating a distributed filesystemand applications, and rethinking computing in terms of multiplesystems, not single time-sharing systems communicating with eachother. Though Plan 9 brings along many tools from later editions ofUnix (especially 8-10), it is a new system. Plan 9 is an open-sourceoperating system carrying the Unix philosophy to its pinacle.

Plan 9's most significant influence on Linux was UTF-8. Though Linuxwas intended as a free System V replacement, it has become abridge system, incorporating ideas from Unix and Plan 9, andinteroperating with other systems, such as Microsoft Windows.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 14: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

1-4

FSF and GNU

Richard Stallman – founder of GNU and the FSF1983 – GNU (GNU's not Unix)• goal: create the free GNU Operating System• first programs: emacs and gcc

1985 – Free Software Foundation• nonprofit organization for promotion of free software• manages the GNU project

By 1991 the GNU system was almost complete• only crucial component missing was a kernel

FSF and GNU

The GNU project was announced in September 1983 by RichardStallman with the goal of creating a free software operating system:GNU. In addition to defining the guiding philosophy for the GNUproject, Richard Stallman contributed code, and is the principal authorof several important software components such as GCC (the GNUCompiler Collection), GDB (the GNU Symbolic Debugger), and thepopular GNU Emacs text editor.

Stallman graduated from Harvard with a degree in Physics. Forseveral years, he worked in the Artificial Intelligence lab at MIT,resigning to work on GNU. He has been granted honorary PhDs fromseveral universities, and won numerous prestigious awards for hiscontinuing efforts to advance the ideals of free software asadvocated by the FSF.

The GNU project started work on the Alix kernel in 1990. The kernel isnow called the Hurd, and runs on top of GNU Mach, a Mach 4micro-kernel. Although a micro-kernel architecture is theoretically asuperior kernel design, in practice the Mach design has provencumbersome. The Debian project provides the official release ofGNU/Hurd.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 15: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

1-5

GPL – General Public License

Guarantees that free software remains free (as in freedom)All software under the GPL makes source available to the end userChanges to a GPL licensed software package must also be licensedunder the GPL

Source code from GPL licensed software can be incorporated intoother GPL licensed software

Other Licenses:• http://www.gnu.org/licenses/license-list.html• http://www.opensource.org/licenses/index.html

In 1992, Linus Torvalds released 0.12 of the Linux kernel under theGPL.

Free Software

In the Linux community you will often hear the term "free software."What is meant by this term? What follows is an excerpt from theGNU website: http://www.gnu.org/philosophy/free-sw.html. "'Freesoftware' is a matter of liberty, not price. To understand the concept,you should think of 'free speech', not 'free beer'."

'Free software' refers to the users' freedom to run, copy, distribute,study, change and improve the software. More precisely, it refersto four kinds of freedom, for the users of the software:

The freedom to run the program, for any purpose (freedom 0).

The freedom to study how the program works, and adapt it to yourneeds (freedom 1). Access to the source code is a preconditionfor this.

The freedom to redistribute copies so you can help your neighbor(freedom 2).

The freedom to improve the program, and release yourimprovements to the public, so that the whole communitybenefits. (freedom 3). Access to the source code is a preconditionfor this.

A program is free software if users have all of these freedoms. Thus,you should be free to redistribute copies, either with or withoutmodifications, either gratis, or charging a fee for distribution toanyone, anywhere.

Copyleft

To help guarantee that all software remains free, with the first GNUrelease of Emacs, Stallman wrote a copyright license so that GNUsoftware cannot be hidden in proprietary, "non-free" code. He calledthis copyleft. Seehttp://www.gnu.org/licenses/licenses.html#WhatIsCopyleft

"Copyleft is a general method for making a program free softwareand requiring all modified and extended versions of the programto be free software as well...To copyleft a program, we first statethat it is copyrighted; then we add distribution terms, which are alegal instrument that gives everyone the rights to use, modify, andredistribute the program's code or any program derived from it butonly if the distribution terms are unchanged. Thus, the code andthe freedoms become legally inseparable. Proprietary softwaredevelopers use copyright to take away the users' freedom; weuse copyright to guarantee their freedom. That's why we reversethe name, changing 'copyright' into 'copyleft'."

Licenses

While the GPL license is arguably the most important of the freesoftware licenses. Many other licenses exist.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 16: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

1-6

The Linux Kernel

Linus Torvalds – Finnish college student• wanted to replace Minix, a UNIX-like feature-limited teaching OS

The Linux kernel• fresh re-implementation of the UNIX APIs• under the GPL license

The Linux kernel together with GNU and other programs forms acomplete free operating system

The Linux Kernel

Linus Torvalds made the now famous first post about Linux in thecomp.os.minix newsgroup in August of 1991. It is reproduced here:

From: [email protected] (Linus Benedict Torvalds)Newsgroups: comp.os.minixSubject: What would you like to see most in minix?Summary: small poll for my new operating systemMessage-ID: <[email protected]>Date: 25 Aug. 91 20:57:08 GMTOrganization: University of HelsinkiHello everybody out there using minix -

I'm doing a (free) operating system (just a hobby, won'tbe big and professional like gnu) for 386(486) AT clones.This has been brewing since april, and is starting to getready. I'd like any feedback on things people like/dislikein minix, as my OS resembles it somewhat (same physicallayout of the file-system (due to practical reasons) amongother things).

I've currently ported bash(1.08) and gcc(1.40), and thingsseem to work. This implies that I'll get something practicalwithin a few months, and I'd like to know what features mostpeople would want. Any suggestions are welcome, but I won'tpromise I'll implement them :-)

Linus ([email protected])

PS. Yes - it's free of any minix code, and it has amulti-threaded fs. It is NOT portable (uses 386 task switchingetc.), and it probably never will support anything otherthan AT-harddisks, as that's all I have :-(.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 17: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

1-7

Linux Kernel and Versioning

1994 – Linux kernel 1.0 released1996 – Linux kernel 2.0 released, based on 1.3 development branch2003 – Linux kernel 2.6 released, based on 2.5 development branch2004 – Linux kernel 2.6.8 released, based on Linus' post 2.6.7development branch

2004 – Linux kernel 2.6.8.1 released to fix a NFS code problem2005 – Linux kernel 2.6.11.1 released making stability patches to themainline release kernel official

2006 – Linux kernel 2.6.16 was released, becoming the first of severallongterm release kernels

2011 – 3.0 kernel released (after 2.6.39), patched as 3.0.12011 – 3.1 kernel released, following up on 3.0

Linux Kernel Versioning

The Linux kernel is maintained by a large group of developers headedby Linus Torvalds. Linus acts as a "benevolent dictator" and has finalsay over what changes are introduced into the official kernel. Linus issponsored by the Linux Foundation, a merger of the Open SourceDevelopment Labs (OSDL) and the Free Standards Group. Seehttp://www.linux-foundation.org/en/FAQ.

The Linux kernel version is designated by a major and minor number,a release number, and optionally a patch level. Linux distributors mayadd an additional component, the EXTRAVERSION. For example, anerrata kernel for Red Hat Enterprise Linux 6 is version 2.6.32-71.

Originally, Linux kernels with an even minor number (e.g. 1.2.x, 2.0.x,2.2.x, 2.4.x) were considered stable production kernels. Only bugfixes and isolated features, such as new drivers, were added to thestable kernel tree, indicated by a third number, the patch level. Linuxkernels with an odd minor number (e.g. 1.1.x, 2.1.x, 2.3.x) weredevelopment kernels, not to be used on production systems.

The odd-numbered development kernel was where new featureswere introduced. When all the slated features were added, then thedevelopment kernel went into a feature freeze where only bug fixeswere allowed. After the development kernels became stable, theversion number was bumped so that the minor number was even. Ifthe number or importance of features is large enough, the majornumber is incremented.

In 2004, Linus Torvalds decided that it was not necessary to create a2.7 development branch, as the overall structure and key componentsof the 2.6 kernel were sufficient for future development. Instead,further development kernels would be built within the 2.6 tree. Stablekernels typically now have a fourth version number. The first suchrelease was 2.6.8.1. Kernels with such a fourth digit are stable patchversions. Newly incremented third digit versions are made to signifythe completion of sets of new and revised features. For furtherdetails, see the Documentation/HOWTO file in the kernel sourcedocumentation.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 18: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

1-8

Kernels now have long term service releases. The first such releasewas 2.6.16, released 20 March 2006, and last patched 21 July 2008with release 2.6.16.62. Though the 2.2 series has not officially beenmade end-of-life, it has not received a patch update in years.2.4.37.11 was released 18 December 2010. It is declared end-of-life,but still receives occasional patches upstream. Even though a kernelis declared end-of-life, i.e. it will receive no further updates, kernels

are considered stable for 6 months from release. Other longtermsupported kernels include 2.6.32, 3.0, and 3.4. Longterm kernelsupport is usually about two years, plus another 2 depending on thewillingness of individuals to keep supporting a release. The mainlinekernel is the current release kernel, and the kernel in development forthe next release, e.g. 2.6.39-rc6.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 19: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

1-9

Components of a Distribution

Typical Linux distributions provide• collection of applications along with the Linux kernel• installation program• documentation• support• some are very specialized (e.g. Linux Router Project)• POSIX and Single Unix Specification compliance

Most Linux distributions provide the same basic software:• GNU software

GNU Coding Standards• BSD and Linux utilities• X.Org, GNOME, KDE, and other GUI components

Linux Distributions

Most Linux companies producing distributions have teams ofdevelopers working full time to produce free software. Thecompanies earn money from services related to their distributionincluding support, consulting, and selling boxed copies.

Most distributions are available for download off of the Internet.Since 1999, most distributions have also made ISO CD-ROM imagesavailable for download. If you have a fast Internet connection and aCD/DVD writer, you can download an ISO image and create your owninstallation media.

Linux Standards

There are hundreds of different Linux distributions. At the API/ABIlevel, all Linux distributions share a common kernel, which conformsto the POSIX/IEEE interface specifications and the Single UnixSpecification. The GNU Project follows the design standards of theGNU Operating System, which influence the userland, and othertools, provided by the GNU Project. This is documented in thestandards info manual, found athttp://www.gnu.org/prep/standards/

Components of Distributions

With the plethora of Linux distributions on the market, it might at firstseem that Linux is repeating the same Balkanization that hashampered the Unix world for the past two decades. It's important torealize that, in spite of their brand differences, all main-stream Linux

distributions are compatible with each other at the API and binarylevels, because they all consist of the same core software: GNU andBSD libraries and utilities, the X Window System as implemented bythe X.Org Project, the GNOME and KDE desktops, etc.

In spite of this basic compatibility, distributions are stilldistinguishable because their developers tailor them for variousmarkets. For example, some will include advanced softwarepackaging functions, or commercial support, or automatic updatingcapabilities, while others may include features like commercialword-processing software, or additional free software targeted formore specialized audiences.

Locating Linux Software

Software for Linux is available for download all over the Internet.Most software projects have their own sites. In addition, there areseveral sites that maintain listings of many programs with links fordownloading and more information.

These sources are excellent starting places when looking for Linuxsoftware:http://kernel.org/pub/linuxhttp://www.rpmfind.nethttp://www.freshmeat.nethttp://www.sourceforge.nethttp://directory.fsf.org

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 20: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

1-10

Slackware

Oldest active distributionFork of Softlanding Linux System (SLS)Added simple package management• Uses compressed tarballs

Added an automated installerBecame extremely popular and continues to have a wide following

SLS

The SLS distribution was an early distribution, making it possible fornon-überhackers to install a Linux system on their computer. BeforeLinux distributions, if you wanted to install Linux, you would firstdownload and install Minix, or a 386BSD derivative, then afterbuilding the GNU toolkit (binutils, glibc, and perhaps gcc), youcould begin the process of downloading, configuring, and compilingthe Linux kernel, and a boot loader (e.g. LILO). This gave you akernel, but no commands. Now you could begin downloading theGNU userland, and other source code.

Slackware

First released in April 1993, and a derivative of SLS, Slackware haslong sought to be the most Unix-like of all the Linux distributions. Inaddition, Slackware primarily targets Intel-compatible architectures;few ports to other architectures have been completed and released.Slackware tends to be popular among those who prefer aminimalistic approach to Linux installation and configuration.

The first commercial Linux was S.u.S.E., which originally distributedSlackware. Pat Volkerding assisted in the development of the earlyS.u.S.E. releases, until it switched to RPM and forked as its owndistribution. SUSE still has many underlying similarities to Slackware.

Additional information about how to Get Slack can be found athttp://slackware.com. The name Slackware is derived from theteachings of the Church of the SubGenius, http://subgenius.com.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 21: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

1-11

SUSE Linux Products

SUSE Linux Enterprise Family• Server and Desktop releases• 2 year release cycle• 7-10 year maintenance life cycle• Highly scalable, mature technology• Five platforms: IA-32, AMD64/Intel64, IA-64 (Itanium series),

ppc64, S390x(zSeries)• ISV certifications

The openSUSE Project• Cutting edge• 8 month release cycle• Limited security updates for 1.5-2 years

SUSE Linux Enterprise Family

There are two SUSE Linux Enterprise products available from SUSELinux Products GmbH: SUSE Linux Enterprise Server (SLES) andSUSE Linux Enterprise Desktop (SLED). SUSE Linux Enterprise has a10 year life cycle. Customers can deploy SLES and SLED and havesecurity and bug fixes available for the entire duration. The extended18-24 month release cycle coupled with the 10 year life cycle allowsISVs time to certify their products on a stable Linux platform.

Life Cycle Considerations

The SUSE Linux Enterprise family has three stages of support:general support, extended support, and self-support. The generalsupport period is for the first 5 years of life, and is supported withinperiodic service pack releases. Each service pack has the option forlong term support. Feature additions are only within the first 4 yearsof the general support life cycle. The extended support periodprovides 2 years of extended long term support for server editions,and with SLED11 for desktop editions, with critical bug maintence(such as security patches) for a subset of packages. The self-supportperiod is for the remaining period of the 10 year life cycle. End-of-life,the end of the extended support cycle, is as follows:

y SLES8: 31 October 2007. (Self support through October 2012.The extended support period was for x86/z series server only.)y SLES9: 31 August 2014. (Extended support was extended to the

end of the self support cycle.)y SLES10: 31 July 2016. (Extended support was extended to the

end of the self support cycle.)y SLES11: 31 March 2016. (Extended support is not available.)

Some of the features included in SUSE Linux Enterprise Server are asfollows. For a full list of features, see http://www.opensuse.org/.

y Scalabilityy Scales up to 4096 CPUsy Supports up to 64 TiB of RAM

y Clustering and High Availability (HA)y Support for load balance clustering and HA configurations

y Platform Availabilityy IA-32, AMD64/Intel64, Itanium (not including Merced), ppc64,

IBM zSeries s/390x and s/390

The openSUSE Project

The openSUSE project was founded by Novell to build and maintainan open-source Linux distribution. Focused on the most current andcutting edge open source technologies, openSUSE provides earlyaccess to future SUSE Linux Enterprise features. openSUSE life cycleis 8 months between releases, and supported 2 months after thenext release (effectively 18 months). Versions previous to 11.2 weresupported for 2 years.

For more information on the openSUSE project see:http://www.opensuse.org/

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 22: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

1-12

Debian

Second oldest active distributionInitially sponsored by the FSFAuthored and Controlled by the Debian communityVery committed to free softwareUses own package management, DPKGInnovated with in-place, no reboot upgradabilityEasy to keep your system current• apt-get update• apt-get upgrade

Debian

Begun the same year, shortly before Red Hat Linux, thenon-commercial Debian project sought to develop a package-basedapproach to GNU/Linux installation. Since that time, Debian hasbecome popular for its dedication to free software principles and forits huge variety of packaged software. It is also the most widelyported GNU/Linux distribution, with ports to over a dozenarchitectures, completed or in progress. It has even begun to supportnon-Linux kernels from the Hurd project, to various BSD projects.

Much like Linux itself, Debian is developed and maintained by a cadreof thousands of volunteers from all over the world, working togetherover the Internet.

Additional information about Debian can be found athttp://www.debian.org/.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 23: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

1-13

Ubuntu

Founded by Mark ShuttleworthLicensed by CanonicalBased closely on DebianCommitted to free softwareUses Debian's package management, DPKGEasy to keep your system current• aptitude update• aptitude upgrade

Ubuntu

Ubuntu was first released in October 2004 with the 4.10 release.Since that time Ubuntu has stuck to a strict six-month release cycleusing a "Year.Month" versioning scheme. 4.10, 5.04, 6.06, 6.10, 7.04,7.10, 8.04.

The LTS (Long Term Support) release is given additional preparation.Ubuntu supports each six month released version witheighteen-months of free security and errata updates. Each two years,beginning with 6.06, Ubuntu releases the LTS version, which issupported for three years on the desktop and five years on theserver. Ubuntu also promises that they will never have an "Enterprise"release, meaning that the entire community--business or personal--willbenefit from the same product.

A few of the key things that separate Ubuntu from other distributionsare:

y Community firsty Ubuntu Code of Conducty No "Enterprise" releasey Ubuntu will always be free of charge

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 24: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

1-14

Red Hat Linux Products

Invented the RPM Package ManagerEasy-to-use installer integrates partitioning and leverages RPMLoyal to free software ideals: only ships open-source software withfew exceptions that restrict modification and redistribution.

Fedora• Cutting edge, community oriented project• Provides new technology for future RHEL releases

Red Hat Enterprise Linux (RHEL)• Enterprise targeted distribution with commercial support• CentOS: community maintained, enterprise targeted, distribution• Scientific Linux• Oracle Linux

Red Hat Enterprise Linux

First released in 1994, Red Hat Linux (RHL) quickly became the mostpopular Linux distribution in the United States. Red Hat introduced avariety of tools which simplify system management, such as RPMand Kickstart, and has been ported to several architectures. The fastpace of RHL releases lead ISVs to ask Red Hat for a long-term optionto allow product certification on a stable platform. The result was theintroduction of what became Red Hat Enterprise Linux (RHEL), astability branch of RHL/Fedora. See http://www.redhat.com/.

y RPMs bundled with purchased support contracty Source RPMs freely available and accessibley Ten year life cycle for feature additions and bug/security fixesy Up to three years extended support after end-of-life

Red Hat Enterprise Linux comes in several variants, including:

Red Hat Enterprise Linux for Server ⇒ The primary Enterprise Linuxrelease, but requires a key to unlock add-on software (at install),and in some cases extra media. Not all packages built fromsource RPMs are included on the installation media, but insteadare only available from RHN. These packages are labeled optional,and are not covered by the ABI compatibility guarantees, or erratasupport (though errata may extend from related updates), similarto supplementary packages

Red Hat Enterprise Linux for HPC Head/Compute Node ⇒ IncreasedRHEL Server support options (e.g. more CPUs, SAN) intended forHigh Performance Computing

Red Hat Enterprise Linux for SAP Business Applications ⇒ Shipswith the Server component, plus SAP Business Applicationssupport

Red Hat Enterprise Linux Client ⇒ Desktop oriented, with moreadd-ons, but less server, software.

Red Hat Enterprise Linux Workstation ⇒ The same as Client, butwith development add-ons.

For a complete breakdown of the differences between RHEL variants,and other options, such as support for IBM System Z and POWERsystems, see http://www.redhat.com/rhel/compare/.

Fedora

With the release of RHEL3, Red Hat decided to rename RHL toeliminate confusion with RHEL. What would have been called RedHat Linux 10 became Fedora Core 1. The name change to FedoraCore wasn't only about the name. Fedora is a community project,open to the public. The Fedora Core and Fedora Extras repositorieswere merged for the release of Fedora 7. The word "Core" has,therefore, been dropped.

y Release cycle of 6 monthsy 13 month life cycle for bug/security fixesy Commercial support is not available from Red Hat

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 25: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

1-15

CentOS

CentOS is a community release based on Red Hat Enterprise Linuxsources. It removes trademarked components to allow legalredistribution of "an enterprise class OS without the cost or supportof the prominent North American Enterprise Linux vendor." Seehttp://centos.org.

Similar projects exist, such as Scientific Linux, and Oracle Linux.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 26: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

1-16

Oracle Linux

Oracle Linux• Matched release cycles with RHEL• Binary and Source compatible with RHEL• Highly scalable, mature technology• Three platforms: x86, AMD64, and Itanium• ISV certifications

Oracle Linux

Oracle Linux is an Oracle provided Linux distribution that is sourceand binary compatible to Red Hat Enterprise Linux. Oracle uses thepublicly available source code from Red Hat Enterprise Linux for thecore of its distribution. While Oracle does incorporate additionalpatches and updates, they maintain compatibility with both Red HatEnterprise Linux, and the certified ISV products which run on it.

Patches and modifications to Oracle Linux are released to the Linuxcommunity under the GPL license and are available for anyone,including Red Hat, to use and incorporate into their products.

Oracle Linux (6.2) features include:

CPU ⇒ up to 32 cores (x86), 256 cores (x86_64)Physical memory ⇒ up to 64GB (x86), 2TB(x86_64)ext4 ⇒ up to 16TB filesystemsocfs2 ⇒ up to 4PB filesystemsKernel base version ⇒ 2.6.32

For a complete list of features refer to:http://www.oracle.com/linux/

Oracle Linux is available free of charge fromhttp://linux.oracle.com.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 27: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

1-17

Mandriva

Formerly MandrakeMandrake bought Connectiva, renamed Mandriva"User-Friendly" distributionPowerful installation program (able to resize NTFS and FAT partitions)Mandriva Online update toolDrax configuration toolUses RPM

Mandriva

Mandrake Linux was created in 1998 with the goal of being an "easyto use" distribution. In 2005, Mandrakesoft purchased Linuxdistributor Connectiva; the combined company was named Mandriva.A fork of Mandriva, employing many of the Mandriva developers iscalled mageia. Updates are for one year, with 18 months for the basesystem, and 24 months for server.

Mandriva has been the distro of choice for those trying to migratefrom a Windows or MacOS environment. Mandriva has a veryimpressive installation program that allows you to resize NTFS andFAT partitions to enable a dual-boot system. Updates anddependency problems are all but eliminated by using theMandrivaUpdate software. Mandriva is a good choice for a first Linuxdistribution.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 28: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 29: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

Chapter

2LOGIN ANDEXPLORATION

ContentLogging In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Running Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Interacting with Command Line . . . . . . . . . . . . . . . . . . . . . . 4The X Window System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Starting X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Gathering Login Session Info . . . . . . . . . . . . . . . . . . . . . . . . 9Gathering System Info . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10got root? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Switching User Contexts . . . . . . . . . . . . . . . . . . . . . . . . . . . 12sudo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Help from Commands and Documentation . . . . . . . . . . . 15Getting Help with man & info . . . . . . . . . . . . . . . . . . . . . . . . 16Lab Tasks 19

1. Login and Discovery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202. Help with Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253. Switching Users With su . . . . . . . . . . . . . . . . . . . . . . . . . 29

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 30: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-2

Logging In

Serial terminals — Text mode login via serial port• mgetty+login — Handles modems• agetty+login — Handles VT100/VT220 dumb terminals

Virtual terminals — Text mode login(s) on local console• mingetty+login

Graphical — GUI login on local console• xdm, gdm, kdm, etc.• Terminal Emulator

xterm, rxvt, gnome-terminal, konsoleNetwork logins — Remote text mode login• in.telnetd+login, in.rlogind, sshd, etc.

Logging In

It is essential on a multi-user system that the Operating System beable to identify each user on the system. User identification can beaccomplished in a variety of ways: hardware-based passkeys;biometrics (such as fingerprints, voiceprints, retina scans, etc.); andmany others. The most common method is to prompt the user toenter a username and corresponding password.

To provide authentication services and permit access to the system,Linux will run special processes that are designed to gather a user'susername and authentication token(s) (such as a password). Tounderstand the processes involved, you must examine some basicsof the boot process:

1. When a Linux system boots, it must first locate and load thekernel.

2. When the kernel finishes its loading process, it loads andpasses control to some initial process, usually the programinit.

3. The init process goes through its initialization procedures,part of which is to enter the currently defined run-level.Run-levels (among other things) determine if the system willdisplay a text or graphical login prompt at the console.

4. For a text mode login, init spawns one or more getty-likeprocesses and associates them with the appropriate terminals.A "getty" is a program responsible for configuring the terminalhardware settings. In the case of a modems, the processstarted is usually /sbin/mgetty. Although rarely used today,

for direct attached serial terminals, agetty is preferred. In thecase of the virtual terminals where no serial port managementcode is needed, the light-weight /sbin/mingetty is usuallyinvoked.

5. The mgetty or mingetty process is the second of the threeprograms (init, mgetty/mingetty and login) used by thesystem to allow users to login. mgetty or mingetty is invokedby init to:yOpen tty lines and set their modes.y Print the login banner, usually the contents of the/etc/issue file.

y Spawn a login process for the user, usually /bin/login.6. The login program is what actually prompts the user to input

their password. login will then validate the user's credentialsand start the shell defined in the user's corresponding/etc/passwd entry.

If configured, graphical logins are provided by one of the graphicaldisplay managers, commonly: xdm, gdm, or kdm. After logging ingraphically, a terminal emulator can be run (such as thegnome-terminal command) to get a command shell, or from withinGNOME or KDE, the key combination Ô¿Å can be used.

Network login access is provided by daemons such as in.telnetd,in.rlogind, or sshd which are launched as stand alone services, orfrom a super-server such as xinetd. These programs take the placeof mgetty, and in some cases login as well. For security reasons,SSH has replaced rlogin and telnet in most environments andprovides both strong authentication and encryption.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 31: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-3

Running Programs

Graphical environment (e.g. X+GNOME)Command line (e.g. Bash)

Running Programs Within the GUI

Linux includes a graphical server called X and several full-featureddesktop environments such as GNOME and KDE. Most Linuxworkstations boot automatically to a graphical login. Server systemsmay have the graphical interface installed, but more commonly bootdirectly to a text login.

Most graphical desktops provide an intuitive interface for launchingprograms such as a simple menu. If the name of the program isknown, an alternative is to type that name from a terminal commandprompt and press enter. In the GNOME desktop and KDE, pressingÔ¿Å opens a dialog where programs can be launched by typing thecommand name.

Advantages of the GUI include:

y Aesthetically compelling and inviting to new users.y Ease of multitasking (click and drag to move and resize program

windows, click on a program to bring it to focus and interactwith it, etc.)y Graphical display can convey, and allow interaction with, certain

types of information very efficiently.y Some advanced applications require the GUI (e.g. The Gimp)

Running Programs From the Command Line (Text Interface)

Linux includes special programs called shells that provide a commandline interface to the system. Modern shell programs such as Bash(the default shell) are highly configurable and feature rich. Whenlaunched, shells present a text interface with a string called a promptbeing displayed. Typing the name of a program at this prompt andthen pressing Õ will launch the program.

Advantages of the command line include:

yMost tasks can be accomplished more quickly verses theequivalent option performed within the GUI.y The ability to pass options and arguments to programs provides

finer grained control than most GUI interfaces.y Lower overhead: most command line programs use less

memory and CPU than equivalent GUI programs.y Ease of automation due to shell scripting features and

non-captive program interfaces. Once packaged into a script, asequence of commands can be run on hundreds of systemsnearly as easily as a single system.y Easily accommodates remote access and interaction. Programs

such as SSH can allow secure interaction with a command shellon a remote system, even over low bandwidth links.y The shell provides powerful ways to connect programs together

to accomplish more complex tasks. Almost any command lineprogram can be connected to any other, (although not allcombinations are useful or make sense).

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 32: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-4

Interacting with Command Line

What happens when I pressÕ at the command prompt?• expansion, substitution, and splitting performed• redirection setup• execution

Command optionsCommand argumentsCommon errorsTips and Tricks

Processing of the Command Line

The shell command prompt provides an interactive text interface forrunning programs. Under normal usage, you type the name of theprogram you want to run and hit Õ. The shell executes the programand it may return results which are printed to the same text window.This process is then repeated as needed, (running commands andanalyzing the results).

With a modern shell, several types of pre-processing are performedon the command line before a program is run. For example, manycharacters have special meaning to the shell and cause it to performexpansion or substitution, replacing these special characters withother values. The shell must also break the input into logical pieces,an operation called word splitting, with whitespace acting as theprimary delimiter between words.

By default, commands run from the shell can continue to acceptinput typed into the same terminal while they execute. Output orerrors generated by the program will be displayed on the sameterminal. Alternatively, you can tell the shell to redirect input andoutput to another place. For example, input might be read from a file,or output sent to a file or another program.

Finally, the shell will attempt to run the specified program. If the shellcan't locate the program then an error is displayed. When run, someprograms will exit quickly returning you to a command prompt. Otherprograms may continue accepting input from the terminal effectivelypreventing you from running other programs from that shell.

Command Options

Depending on how they are run, most commands can change theirbehavior. These extra command features are accessed by passing thecorresponding "option" when running the program. To help the shelland command recognize options, they are almost always precededwith either a single dash "-" or two dashes "--".

Letters that follow a single dash are called short options and willactivate the corresponding feature of the program when it runs.Generally, the order of options does not matter. For example, each ofthe following would be operationally identical (causing the commandto run with the a, b, and c options selected:

$ command -abc$ command -cba$ command -a -b -c$ command -c -b -a

Short options are quick to type and generally have some mnemonicsignificance. Some commands support long options as a moredescriptive alternative. These are specified with a preceding doubledash:

$ command --alpha --beta --charlie

Often commands support both short (Unix) and long (GNU) optionsfor the same feature. Other times, a feature will be accessible viaonly one type or the other. A mix of option types can be used:

$ command -a --beta -c --delta

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 33: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-5

Command Arguments

Many commands are designed to operate on one or more objects(often files). This list of objects are called "arguments" and aregenerally listed after the command name options. When the shellruns a command, it passes the list of arguments to the command asan array. Arguments not preceded by a dash are normally delimitedby whitespace. For example:

$ command --option1 arg1 arg2

Common Errors

The shell searches a configurable list of locations for programs. If theprogram you want to run is not installed into one of the configureddirectories, or if you make a typo in specifying the name of theprogram then an error is returned:

$ commandbash: command: command not found

If the file containing the program does not grant you executepermissions then attempts to run it result in an error:

$ commandbash: command: Permission denied

If an invalid (unknown) option is specified, then an error is displayed.Often some basic usage information, or help, for the command isalso displayed:

$ command -acommand: invalid option -- aTry `command --help' for more information.

If an invalid argument is specified (such as a file that doesn't exist),then a command specific error is generated. The following is acommon example:

$ command file1command: cannot stat `file1': No such file or directory

Command Line Tips and Tricks

Modern command shells have a large number of features designed tomake command line access more efficient and increase productivity.The following is a brief list of features. More extensive coverage ofeach of these features is found in later chapters.

History ⇒ The shell keeps a record of commands run in eachsession. Use the arrow keys to bring back previously runcommands to save typing.

Completion ⇒ Context sensitive auto-completion functions can savehuge amounts of typing. With default settings, press the Ð keyto attempt completion.

Aliases ⇒ Give your own names to commands by defining aliases.For example, after running alias p="cd ..", typing pÕ at theprompt would change to the parent directory.

Clear screen ⇒ Pressing Ó¿l will clear the screen.Copy & Paste ⇒ The act of highlighting text with the mouse (by left

clicking and dragging to select it) automatically places a copy ofthat text into a copy buffer. Clicking the middle mouse button willpaste from that buffer.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 34: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-6

The X Window System

GUI infrastructure for Unix and Linux systems• Created in 1984• Both a Protocol and an Implementation

Advantages of X• Operating System Independent• Modular and Extensible• Client-server (Network Transparent!)

XFree86• Original Open Source implementation of the X Window System

X.Org• Forked XFree86 with a more open development model

The X Window System

The graphical environment for Linux is not a core part of theoperating system. Rather, it is a service provided by a runningprocess much like a Web server. This design has many advantages.For example, a fatal failure in the graphical environment will rarelytake down the entire system. Most of the time it is possible to justrestart the graphical environment without rebooting. Depending onthe needs of the system, one of several graphical environments canbe chosen. In fact, it is even possible to build a system without anygraphical environment at all. This is common for systems used asnetwork servers.

By far the most common graphical environment for Linux is the XWindow System, often referred to as X or X11. Originally created in1984 by MIT, the name X refers to both a network protocol and asoftware implementation of that protocol. By 1987, the X protocolhad seen several major redesigns before finally reaching version 11.The X11 protocol was deliberately designed to be modular andextensible allowing interesting and useful features to be added whilemaintaining backwards compatibility.

An X server is responsible for controlling the video card on a system.An X client, for example a graphical text editor, communicates withthe X server in order to display graphical content. One of the greatestadvantages of X is the fact that X clients only communicate with theX server via the X protocol. This means that X clients and X serverscan natively and transparently communicate over a network. In fact,they can even be running on entirely different operating systems.

The X Consortium, XFree86 and the X.Org Foundation

Although originally created and maintained by MIT, responsibility for Xwas first passed to the X Consortium in 1993, and then The OpenGroup in 1997. The X Consortium and The Open Group maintainedthe official reference implementation of X, but over time developmentof official X releases slowed.

Starting in 1992, the XFree86 Project (http://www.xfree86.org) tookthe X386 reference source code, optimized it, added device driversfor many different video cards, and integrated support for advancedfeatures such as hardware-accelerated OpenGL. Originally XFree86only supported x86-compatible hardware, but today it also supportsmany other architectures, such as Alpha, PowerPC, and Sparc. Formany years, XFree86 was the standard Linux X Window System.

Eventually XFree86 also began to stagnate. In 2004, internaldeveloper disputes and a license change resulted in a fork of XFree86and the creation of the X.Org Foundation (http://x.org). The OpenGroup gave not only control of the x.org domain to the X.OrgFoundation, it also made the X.Org Foundation responsible for theofficial reference implementation of the X protocol.

The X.Org Foundation's main goal is to have a more open andtransparent development process. As a result of its more openculture, development of X has again accelerated. Nearly all Linuxdistributions have switched, or are in the process of switching, fromXFree86 to X.Org.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 35: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-7

Starting X

X already running with a graphical login• On Red Hat Enterprise Linux and SUSE Linux Enterprise Server,

runlevel 5 by default• On Ubuntu, runlevels 2-5 by default

From a text virtual terminal login, use startx• startx is a shell script that eventually runs xinit• can run xinit manually, but by default only starts the X server

Starting X

X can be started in a variety of ways. Often, X will already be startedfor you; Linux systems can be configured to boot either to a graphicallogin screen, or a text login prompt.

Starting X on boot

Whether Red Hat Enterprise Linux and SUSE Linux Enterprise Serverboots by default to a text-based login, or to a graphical login, iscontrolled by the /etc/inittab file. To configure the system boot toa text login prompt, make the following change:

File: /etc/inittab- id:5:initdefault:+ id:3:initdefault:

To configure the system to start with a graphical login, the followingline would be present in the /etc/inittab file:

File: /etc/inittab- id:3:initdefault:+ id:5:initdefault:

Starting X at boot on Ubuntu

Whether Ubuntu boots to a text-based login, or graphical login, bydefault is controlled by whether or not the graphical login manager isinstalled. To configure the system to no longer boot to a graphical

login, while leaving the display manager installed, requires amodification to the GRUB boot loader:

File: /etc/default/grub→ GRUB_CMDLINE_LINUX="text"

To complete this change, run the update-grub command.

$ sudo update-grub

The display manager can be manually started from its init script in the/etc/init.d/ directory, or using the service or start command.

To reenable the display manager, revert the change made to/etc/default/grub.

$ sudo sed -i 's/text//' /etc/default/grub$ sudo update-grub

Starting X manually

If X is not started automatically, you can start it manually by runningthe X command to start just the X server, or xinit to start the Xserver and a single xterm (but no window manager), or startx tostart a more usable, full-featured graphical environment. Since X ismodular, you can control exactly how much of it you start.

Accessing Virtual Terminal

Running one or more X graphical servers on a system does notpreclude having simultaneous text login sessions. Each graphical or

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 36: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-8

text session will be associated with a virtual terminal. The first twelvevirtual terminals can be accessed by pressing Ô¿Ä through Ô¿Ïrespectively (when in X, Ó is also necessary). Optionally, usingÔ¿¡ or Ô¿¤ works when not in X and can be used to accesshigh numbered terminals (moving sequentially from one terminal tothe next).

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 37: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-9

Gathering Login Session Info

Who are you really?• UID – user id• GID – group id• terminal: tty, pts, etc.

Commands for gathering information:• id

id -un|whoamiid -Gn|groups

• tty

Identifying Users, Groups, and Terminals

Although it is common to identify users by their username, at a lowerlevel the system uses simple numbers to identify the various userson the system. Each user account on the system is associated with auser identification number called the UID. This UID identifies the user,and is used to track processes and files created by that user.

For ease of administration and use, Linux makes use of a groupscheme. Each group defined on the system has both a name and aunique identification number called a GID. Although a user may be amember of several groups on the system, they can only have onegroup active at any given instant.

When you are interacting with the system, some type of terminal willbe associated with your session. Following the Unix designphilosophy mentioned earlier, terminals are represented on thesystem as files. The following list shows several types of logins, andthe ttys used by each:

Serial terminals ⇒ /dev/ttyS0, /dev/ttyS1, etc.Virtual terminal ⇒ /dev/tty0, /dev/tty1, etc.Network connected terminals (i.e. via ssh) ⇒ /dev/pts/xText terminals in an X Window System terminal emulator ⇒ /dev/pts/x

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 38: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-10

Gathering System Info

Who else is logged into the system?• users• who• w• finger

What type of system is this?• uname -a• free

What is the system's network name• hostname• ip and ifconfig

Determining Who is Using the System

On a multi-user system, sometimes it is helpful to see which otherusers are currently logged onto the system. Maybe you just want tosend a quick message to the console of a friend, or perhaps youwant to run a process that you know will largely monopolize a certainresource on the system, and you want to wait for a time whensystem usage is low. Even more likely, you notice that some resourceis being largely consumed (memory, CPU, disk, etc.) and you want tosee who is using it so you can go complain.

Linux provides several commands such as users, who, w and fingerthat allow you to query the system and determine who is currentlylogged on, as well as gain other useful information such as:

ywhen they logged ony how long they have been idleywhat process they are currently runningywhat tty they are attached to

Many of the commands mentioned above return largely the sameinformation, differing only in supported options, how they obtain theinformation, or in the formatting of the output.

The amount of physical memory in the system and usage can beobtained by running the free command.

The uname command can be used to list information about the hostto which you are currently connected. If your terminal prompt doesnot list the host name of the system, it is very easy to forget on

which system that terminal is connected. This is further complicatedby the fact that it is not at all uncommon to have multiple terminalsopen simultaneously, connected to different machines.

Networking Details

To determine network details, the hostname command can be used todetermine the hostname as well as the domain name. To view justthe hostname, type:

$ hostname -s

To view the domain name run:

$ hostname -d

To view IP settings run the command ip addr. To see what DNSservers are configured look in the file /etc/resolv.conf.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 39: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-11

got root?

Many operating systems have the concept of a super userThis super, or privileged, user has special access rights and privilegeson the system

The root user is the privileged user on most Unix systemsHas the user ID (UID) of zero (0)

root

Many network operating systems support the concept of a privilegeduser. On Linux (as on most Unix systems), this user is called the rootuser. The root user is in many respects all-powerful on the system.Below is a short list of some of the things that the root user can do:

y Change to any directory and read and write to files regardless ofthe permissions set on those filesy Install software and make it available system wide (becauseroot can create/modify/delete files anywhere)yModify device settingsyModify the network configurationy Change the time on the systemy Add/modify/remove users on the systemy Assume the identity of any user on the system

Although the name of the all-powerful, privileged user is normallyroot, the name assigned to the user is not actually important. Thesystem identifies users by assigning a number to each called the useridentifier or UID. The privileged user is identified by the UID of 0.However, it is recommended that the root user name not bechanged, as there are some user-space pieces that actually look atthe username rather than the UID.

[U1204] The following applies to U12.04 only:

On Ubuntu the root account is disabled, though present, by default.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 40: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-12

Switching User Contexts

su: launch a new shell as another user (using the target user'scredentials)• Use - | -l | --login to inherit login profile• Default user is root

sudo: run a single command with another user's privilege• Remembers authentication per-terminal (typically five minutes)• Configuration affects authentication and available privilege

(/etc/sudoers)

Switching User Contexts

On a multi-user system, an individual may have more than oneaccount. Logged in from one account, there may be a need to dosomething using another account. This would require the followingprocedure:

1. log out2. log in using the new account3. execute the needed commands4. log out of the new account5. log back in using the old account

To avoid the above, use the substitute user command (su) totemporarily use the other account. For example:

1. type su - new_username2. execute the needed commands3. type exit to return to the old user account

The original purpose of the su command was to perform systemadministration tasks as the root user. This remains its most commonuse. Unfortunately, in an attempt to avoid being forced to switchbetween accounts, new users are often tempted to log in initially asroot. Using the root account to perform routine tasks is a bad idea!

The sudo command provides administrative access using userauthorization. For example:

y To switch to a login shell (typically root's, depending on

configuration), type sudo -i.y To run a single command using another user's privilege, typesudo command_name.

In both cases, the sudo command will ask for the user's password,and based on the configuration in the file /etc/sudoers, will allowthe user to execute an administrative command.

sudo remembers authentication by username and terminal, typicallyfor five minutes. To extend the time out, run sudo -v. To cancel thetime out, run sudo -k.

[S11] The following applies to SLES11 only:

By default, the sudo command on SUSE Linux Enterprise Server willask for the root user's password, the default target user.

[U1204] The following applies to U12.04 only:

Ubuntu has disabled the root account by default, relying solely onsudo for administration. See the sudo_root(8) man page for details.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 41: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-13

sudo

sudo – a more powerful su• more fine-grained security• able to log commands

sudoedit – a safer way to edit files• sudo -e

visudo – a safer way to manage sudo• /etc/sudoers

Replacing su with sudo• sudo -i

Using sudo with ssh• ssh -t hostname "sudo reboot"

Delegating Privileges

sudo makes it possible to run commands as a different user. It canbe used to replace or complement su. In most situations, sudo issuperior because it supports more fine-grained configuration.

When evaluating security rules, sudo considers many variablesincluding:

y The command being runy Arguments being passed to the commandy The user launching the commandy The user the command will run asy The host the command will run on

By default, sudo logs all commands to syslog. It can also beconfigured to log to another file.

Unless a different user is requested, sudo runs commands as root.Unlike su, by default sudo does not prompt for the target user'spassword. Instead, the user is required to re-authenticate using his orher own password. For example:

$ sudo reboot[sudo] password for guru: work Õ. . . output omitted . . .

[S11] The following applies to SLES11 only:

SLES11 changes the default behavior of sudo by enabling thetargetpw option. Instead of requiring the user's own password, the

target user's password is required. This is done so that all users canbe safely allowed to use sudo without first being granted permissionby an administrator.

$ sudo rebootroot's password: makeitso Õ. . . output omitted . . .

Editing Files with sudo

Failure to consider edge conditions when configuring sudo cancompromise system security. For example, a user permitted to run"sudo vi some_file" can get complete root access by typing":!/bin/bash" within vi.

When granting a user permission to edit files, using the sudoeditcommand may be safer. When launched as either sudoedit or sudo-e, sudo will make a temporary copy of the file to be edited thenlaunch an editor running with normal user privileges. When the userfinishes editing, the contents of the file will be copied back. However,creating temporary copies may not be appropriate for sensitive files.

Configuring sudo

sudo security rules are defined in /etc/sudoers. The visudocommand should be used when editing /etc/sudoers because itprevents simultaneous modifications, and it verifies syntax to preventtypos or other mistakes in the configuration file.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 42: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-14

File: /etc/sudoers%wheel ALL = (ALL) NOPASSWD: ALL%operator ALL = /usr/local/bin/backup,a

/usr/sbin/lpc, /usr/sbin/lprmguru www.example.com = sudoedit /etc/hosts.allow

In this example, members of group wheel can run any command onany host without entering a password. Members of group operatorcan run backup and printing commands on any host. And guru canedit /etc/hosts.allow using sudoedit only on a host namedwww.example.com.

Replacing su with sudo

To launch an interactive shell, similar to default behavior of the sucommand, use the -i option. For example:

$ sudo -i[sudo] password for guru: work Õ# whoamiroot

Using sudo with ssh

When the requiretty option is enabled in /etc/sudoers, sudo cannot be used as part of an ssh command unless the -t option is used.For example:

$ ssh station1.example.com "sudo service cups restart"sudo: sorry, you must have a tty to run sudo$ ssh -t station1.example.com "sudo service cups restart". . . output omitted (cups is restarted) . . .

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 43: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-15

Help from Commands and Documentation

command --helpDocumentation for installed packages• RHEL6 /usr/share/doc/package_name-version• SLES11 /usr/share/doc/packages/package_name• U12.04 /usr/share/doc/package_name

Shipped or online distribution documentationLinux Documentation Project - TLDPOnline help:• web sites, FAQs, Howtos, newsgroups, mailing lists

Linux User Group(s) (LUGs)• membership typically by mailing list subscription (no dues)• monthly presentations/meetings

Getting Help

Most commands have some basic help features built-in. If you type aGNU command with the --help option, you will get at least a list ofthe supported options. Most Unix commands will print a usagesummary if an incorrect option or argument is used. Somecommands have a dedicated option to print the usage summary,which in some cases includes descriptions of the options andarguments printed.

The Linux community has produced lots of documentation to assistusers. One of the most organized and ambitious projects of thisnature is The Linux Documentation Project (TLDP). This goal is statedin their manifesto:

The Linux Documentation Project is working on developing free,high quality documentation for the GNU/Linux operating system.The overall goal of the TLDP is to collaborate in all of the issuesof Linux documentation. This includes the creation of HOWTOsand Guides. We hope to establish a system of documentationfor Linux that will be easy to use and search. This includes theintegration of the manual pages, info docs, HOWTOs, and otherdocuments. TLDP's goal is to create the canonical set of free Linuxdocumentation. While online (and downloadable) documentationcan be frequently updated in order to stay on top of the manychanges in the Linux world, we also like to see the same docsincluded on CDs and printed in books.

— http://tldp.org/

Help Syntax

When invoking a command with the --help option, a usage summarywith option descriptions will be printed to the screen. This usessyntax which may not be readily identifiable:

$ date --helpUsage: date [OPTION]... [+FORMAT] or: date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]

For instance, capital letters (angle brackets < > are sometimes used)specify a variable: OPTION. This variable is enclosed in squarebrackets, indicating an optional argument. Also, a vertical bar (|)separates arguments where only one in a list can be chosen:[-u|--utc|--universal]. Ellipses ( . . . ) are used to specify that morethan one argument may follow. Finally, notice the difference in typesof optional arguments: GNU long (--universal), SysV or POSIX (-u),and those often called BSD style (such as in ps ax).

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 44: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-16

Getting Help with man & info

It may seem cryptic, but at least it's well-documented• man [section] name

man sectionsuseful options

• infocreated by the GNU projectmeant as a "superior" replacement for manuses HTML like navigation with linksif info pages exist, they usually provide betterdocumentation than the corresponding man pageuse pinfo to view pages

Getting Help

If you are new to Linux, and especially if you have no previousexperience using the system from the command line, you may feelintimidated or even confused by the commands. Some commandshave what seem to be countless different options, each causing thecommand to behave in a slightly different manner. Often, even thenames of the commands can seem non-intuitive and confusing.

Fear not! What at first may seem like an insurmountable task isactually far easier than you may think. Linux has excellent onlinedocumentation for the commands and programs found on thesystem. After learning the help systems, and practicing with thecommands, soon what you once found short and cryptic you mayconsider efficient and elegant. Commands that you thought had fartoo many options you will soon describe as flexible or versatile.

The mainstays for command line help are the electronic manualpages commonly called "man pages." Almost all of the commands onthe system have corresponding man pages, and when new softwareis installed it usually comes with additional man pages. Man pagesare organized into sections or books that group similar thingstogether. Although additional sections can be added, the followingsections are defined by default:

man Sections:

(1) ⇒ User Commands(2) ⇒ System Calls(3) ⇒ Subroutines(4) ⇒ Devices(5) ⇒ File Formats(6) ⇒ Games(7) ⇒ Miscellaneous(8) ⇒ System Administration(n) ⇒ new (used for writing and testing new and/or updated man

pages for other sections)

The man command will search the sections in the following order:1,8,2,3,4,5,6,7,n. Usually this will not be a problem, but occasionallyyou will be looking for help on a command that is found in severalsections. In this case, man will return the page for the first instance itfinds. For example, suppose you are adding a new task to the systemcrontab and need to check syntax for the file. You type man crontaband get this output:

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 45: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-17

CRONTAB(1) CRONTAB(1)NAME crontab - maintain crontab files for individual users (V3)SYNOPSIS crontab [ -u user ] file crontab [ -u user ] [ -l | -r | -e ]DESCRIPTION Crontab is the program used to install, deinstall or list the. . . snip . . .

This is not what you were after, and you notice that the very first lineof output starts with CRONTAB(1) indicating that this page is fromsection one. To override the normal search order of the mancommand, you type man 5 crontab and get the output you wereafter:

CRONTAB(5) CRONTAB(5)NAME crontab - tables for driving cronDESCRIPTION A crontab file contains instructions to the cron(8) daemonof the general form: ``run this command at this time on this date'. . . snip . . .

Notice the CRONTAB(5) convention of referring to the manual and itschapter. This was a convention started in the first Unix Programmer'sManual, which was broke up alphabetically into chapters. Whenlooking at the manual online (on the system, not the Internet), itmeans type man 5 crontab. It is therefore common to see 'crontab(5)'as a way to reference the crontab entry in chapter 5 of the manual.

Another command for getting help is the info command. info issimilar to man and just requires one parameter, the command youwant help on. info organizes help into different topic pages withlinks leading from page to page. It is the format preferred by the FSFto man pages, and if the software, or command, in question is fromthe FSF, the info pages will likely be more complete than the manpages for that command. A good viewer to use to read info pages ispinfo. Also, the Emacs editor provides an excellent info viewer,(info was originally designed as the documentation system forEmacs).

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 46: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-18

Graphical Help

The Linux Programmer's Manual and GNU info manuals can beviewed graphically with the GNOME yelp command, or the KDE HelpCenter (the khelpcenter command). Yelp can also be used withGNOME applications. The KDE Help Center can also be used withany KDE application. In GNOME, typing Ä will bring up an activeprogram's documentation. In KDE, individual application handbookscan be located from the Help menu.

[R6 S11] The following applies to RHEL6/SLES11 only:

[S11 U1204] The following applies to SLES11/U12.04 only:

The xman command can also be used to browse man pages.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 47: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-19

Lab 2Estimated Time:R6: 25 minutes

S11: 25 minutes

U1204: 25 minutesTask 1: Login and DiscoveryPage: 2-20 Time: 10 minutesRequirements: b (1 station) d (graphical environment)

Task 2: Help with CommandsPage: 2-25 Time: 10 minutesRequirements: b (1 station) c (classroom server)

Task 3: Switching Users With suPage: 2-29 Time: 5 minutesRequirements: b (1 station)

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 48: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-20

Objectivesy Login to the workstation using a virtual console.y Use the various virtual console changing keystrokes.y Login to the workstation using a GUI interface.y Use a variety of commands to gather information about the current login

and the other users on the system.

Requirementsb (1 station) d (graphical environment)

RelevanceThe commands covered in this task will help you be able to login to aLinux system and identify the state of the system. These commands areparticularly important, because it is common when using Linux to accessmany user accounts and systems, often from the same terminal.

Noticesy If this lab exercise is being run within a virtual environment, the use of

special keystrokes may be needed to switch between virtual terminals.

Lab 2

Task 1Login and DiscoveryEstimated Time: 10 minutes

If the system is currently logged in, log out. Use the menus to log out from the1)graphical interface, or type logout at the command prompt if logged into the textterminal.

Switch to the second virtual terminal and login as the guru user:2)Some virtual machines, or remote interfaces, do nothave a way to pass the Ó¿Ô¿Å key sequence.An alternative is the command su -c "chvt 2" whichwill switch the display to /dev/tty2. (You will beprompted for the root password.)

Ó¿Ô¿ÅstationX login: guruPassword: work Õ. . . output omitted . . .

Use the whoami command to see what account name you are logged in as:3)

$ whoamiguru

Use the id command to see the user id(uid) and group id(gid):4)

$ id

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 49: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-21

uid=500(guru) gid=500(guru) groups=500(guru)context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023[R6]

uid=1000(guru) gid=100(users) groups=16(dialout),33(video),100(users)[S11]

uid=1000(guru) gid=1000(guru) groups=1000(guru),4(adm),24(cdrom),a[U1204]

27(sudo),30(dip),46(plugdev),109(lpadmin),110(sambashare)

Use the tty command to observe what terminal is associated with the login:5)

$ tty/dev/tty2

Switch to the third virtual terminal and login as the visitor user:6)

Ó¿Ô¿ÆstationX login: visitorPassword: work Õ. . . output omitted . . .

Since you logged into the third virtual terminal, the associated terminal will be7)different. Verify which terminal is in use:

$ tty/dev/tty3

Use the who and w command to see all users logged onto the workstation:8)

$ whoThere should be at least two users logged in to theworkstation.

. . . output omitted . . . $ w. . . output omitted . . .

Use the finger command to find out more information on the user visitor that9)is logged in to the workstation:

$ su -c "yum install -y finger"[R6]

Password: makeitso Õ[R6]

$ sudo apt-get install -y finger[U1204]

Password: work Õ[U1204]

$ finger visitor. . . output omitted . . .

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 50: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-22

Besides GECOS field information (Name, Primary contact info such as roomnumber, office phone number, other contact info), finger prints the following files:~/.pgpkey, ~/.project, ~/.plan, and ~/.forward (PGP public key, currentprojects summary, general schedule such as work hours, and where email isforwarded, respectively).

[R6] This step should only be performed on RHEL6.10)Press Ô¿Ä, or run su -c "chvt 1" (with the accompanying root password ofmakeitso), to bring up the GUI login screen, and if needed, log in with accountname guru and password work.

[S11 U1204] This step should only be performed on SLES11/U12.04.11)Press Ô¿Ê, or run sudo "chvt 7" (with the accompanying guru password ofwork), to bring up the GUI login screen, and if needed, log in with account nameguru and password work.

Open a terminal window. Observe that the terminal window does not use a virtual12)terminal, but a pseudo terminal:

$ tty/dev/pts/1

With three different logins and terminal sessions on the system, use the who and13)w commands to see all the active sessions:

$ who. . . output omitted . . .$ w

Note that the second column of both commands liststhe associated terminal and that the displayed TTY isdifferent. Be aware that the :0 is the graphical loginsession itself.

. . . output omitted . . .

Press Ó¿Ô¿Å to return to the second virtual terminal where the guru user is14)still logged in:

[guru@stationX ~]$

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 51: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-23

Determine how much physical RAM and swap is configured in the system:15)

$ free total used free shared buffers cachedMem: 1034880 1013264 21616 0 135708 266452-/+ buffers/cache: 611104 423776Swap: 1959888 0 1959888

Output on the system will likely vary from this example output. The top leftnumber is the installed physical RAM in bytes on your system. The bottom leftnumber is the amount of swap.

Pass an option to the free command to display numbers in megabytes instead of16)kilobytes:

$ free -m total used free shared buffers cachedMem: 1010 974 36 0 129 254-/+ buffers/cache: 590 420Swap: 1913 0 1913

Display the IP address of the main network adapter using the ifconfig command.17)The primary network interface is called eth0 and ifconfig can show a specificinterface's details by specifying the interface name:

$ /sbin/ifconfig eth0. . . output omitted . . .

Display the default IP gateway currently configured:18)

$ netstat -rnKernel IP routing tableDestination Gateway Genmask Flags MSS Window irtt Iface10.100.0.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0127.0.0.0 0.0.0.0 255.0.0.0 U 0 0 0 lo0.0.0.0 10.100.0.254 0.0.0.0 UG 0 0 0 eth0

The entry starting with 0.0.0.0 is the default gateway. The second column liststhat router's IP.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 52: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-24

Display the currently configured DNS server(s):19)

$ cat /etc/resolv.confsearch example.comnameserver 10.100.0.254

The DNS servers are defined using the nameserver lines. Up to three nameserverlines are supported. When using DHCP for network configuration this file willautomatically be modified. In this situation there are normally comments at thetop of the file to this effect.

Using the Ò¿Ü and Ò¿Ý keys, the terminal window can be scrolled. Use20)these keys to scroll back as far as possible in the terminal. Note that scroll back ispossible using these same key sequences out at the full screen text virtualterminals. However, when using scroll back at the virtual terminal the scroll backbuffer is cleared when switching to another terminal or X.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 53: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-25

Objectivesy Use the built-in manual (man) system.y Use the built-in info documentation system.y Access usage information built into commands.y Locate a program's README file and other bundled documentation.

Requirementsb (1 station) c (classroom server)

RelevanceBeing able to effectively use the powerful documentation system built intoLinux is an important skill useful in many situations. This lab task coversthe man and info systems.

Lab 2

Task 2Help with CommandsEstimated Time: 10 minutes

Use the man command to find which of its options is equivalent to the apropos1)command.

$ man 1 man

When finished reading, press the q key to exit.

Use the -k option to discover what manual pages contain the term "delete" in their2)description:

$ man -k delete. . . output omitted . . .

This command uses a database that may not exist on the system (it is usuallyrebuilt on a daily basis). If it fails, run the command makewhatis as root to buildthe database.

Use the man command to view one of the specific man pages returned by the3)previous search:

$ man userdel. . . output omitted . . .

The man command uses another command to display the output one page at a4)time. By default, on Linux this is the less command. You can easily search withina man page using the / key.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 54: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-26

Search for the words SEE ALSO to view other related manual pages:

/SEE ALSOÕ the SEE ALSO section of the man page is displayed

q the man command exits

Using the man command, open the first chapter of the intro manual, and peruse5)the contents:

$ man 1 intro

When finished reading, press the q key to exit.

Use the info command to learn about the wget downloading utility:6)

$ info wget the info page for the wget command is displayed

press the down arrow key until the cursor is on the Overview line

Õ the overview page for wget is displayed

p the previous info page is displayed again

q the man command exits

[R6] This step should only be performed on RHEL6.7)Try using the newer pinfo viewer to browse the same wget info page:

$ pinfo wget

Notice the more browser-like interface compared with the traditional infocommand. Use the arrow keys and Õ to navigate. When you are ready, press qto quit.

Another useful resource for getting help is the package documentation directories.8)Most commands and programs will have an entry in these directories. Usually, theinformation in these text files is different than what is found with man or info.They commonly contain release notes, installation notes, etc. See whatinformation exists for the command wget:

$ cd /usr/share/doc/[R6 U1204]

$ cd /usr/share/doc/packages/[S11]

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 55: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-27

Lists all files and directories contained in the currentdirectory.

$ ls. . . output omitted . . .

Replace version with the real wget version numberseen in the directory listing. Hint: Press Ð to useshell auto-completion.

$ cd wget-version/[R6]

$ cd wget/[S11 U1204]

See what documentation files exist$ ls. . . output omitted . . .

Display the contents of the file (showing who theauthors of wget are).

$ more AUTHORS

Commands also have runtime help available. When a command is mistyped, this9)will generate a usage summary. If a command requires an argument, typing thecommand by itself will display a summary of the required syntax. Try this with themore command:

$ moreusage: more [-dflpcsu] [+linenum | +/pattern] name1 name2 ...

Note the brevity, but comprehensive summary, of available arguments andoptions, and the syntax of their use.

With wget and other GNU commands, and many Linux commands, a list of10)possible command line arguments can be obtained by running the command withthe --help option. This doesn't provide the brevity of the Unix usage summary,nor the more detailed information provided by the info manual. Instead, --helpprovides a basic template of how to run the command, and then a one linesummary of each argument and option. With GNU commands, this is commonlyused to build man pages (since GNU prefers the textbook style of the Emacs infoformat). Run the wget command with this option to see the list of availablearguments:

$ wget --help. . . snip . . . -c, --continue resume getting a partially-downloaded file. --progress=TYPE select progress gauge type. -N, --timestamping don't re-retrieve files unless newer than local. -S, --server-response print server response. --spider don't download anything. -T, --timeout=SECONDS set all timeout values to SECONDS.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 56: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-28

--dns-timeout=SECS set the DNS lookup timeout to SECS. --connect-timeout=SECS set the connect timeout to SECS. --read-timeout=SECS set the read timeout to SECS.. . . snip . . .

This output illustrates the GNU long option format common in many commandline utilities on Linux. Most options have an equivalent POSIX flag (e.g. -h) to eachGNU long option. Some options have only a short (POSIX) or long (GNU) version.All the long versions are prefixed by a double dash. Also, some GNU commandsmay request that the --help option be run, when mistyping a command, andsometimes provide an equivalent to the Unix usage summary.

Use the wget command a couple of times, with and without one of the options:11)

$ cd /tmp/$ wget http://server1.example.com/. . . output omitted . . .$ wget --server-response http://server1.example.com/

This time the server responses are printed.. . . output omitted . . . $ wget --server-response --spider http://server1.example.com/

This time the server responses are printed, but withoutdownloading the file.

. . . output omitted . . .

If time permits, use the different help resources explored in this lab task to find12)out more about the ls and cat commands.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 57: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-29

Objectivesy Use and explore the use of the su command.yObserve the operation differences between su and su -.

Requirementsb (1 station)

RelevanceThis lab task illustrates the difference between using su and su - on theenvironment.

Lab 2

Task 3Switching Users With suEstimated Time: 5 minutes

Ensure that guru is the currently logged in user:1)

$ cd$ whoami

If result is different, logout and log back in as the guruuser. The id command can also be used to identifywhich user is currently logged in.

guru$ id. . . output omitted . . .

Observe and record the value of the existing environment variable $PATH:2)

$ echo $PATH. . . output omitted . . .

Result:

[U1204] This step should only be performed on U12.04.3)Ubuntu makes the first user of the system the administrative user. This meansthat the path will be different for the guru and visitor users. Switch user tovisitor and compare the path difference:

$ su - visitorPassword: work Õ$ echo $PATH. . . output omitted . . .$ exit

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 58: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-30

Observe and record the current working directory:4)

$ pwd. . . output omitted . . .

Result:

[S11] This step should only be performed on SLES11.5)The ifconfig utility can be used to display network card IP address assignmentand other NIC parameters and statistics. Try to use ifconfig (expecting an error):

$ ifconfigThis message is to be expected as the ifconfigprogram is located in a directory that is not in anunprivileged user's $PATH by default.

-bash: ifconfig: command not found

[U1204] This step should only be performed on U12.04.6)With Ubuntu the root user is disabled by default. Follow the instructions in thesudo_root(8) manual to enable the root user:

$ sudo passwd root[sudo] password for guru: work ÕEnter new UNIX password: makeitso ÕRetype new UNIX password: makeitso Õpasswd: password updated successfully

Use the su command to become the root user:7)

$ suPassword: makeitso Õ

Observe how you have root privileges, yet your environment has not changed.8)First check your user and group membership:

Note how the prompt has changed to ending in a #instead of $ or > now that you are root.

# id -u0# id -unroot

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 59: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-31

Compare the output of these commands to the previously obtained (and recorded)9)output:

# echo $PATH. . . output omitted . . .# pwd. . . output omitted . . .

[S11] This step should only be performed on SLES11.10)Attempt to run the ifconfig utility again:

On SLES the su command is customized so that whensu is run without --login, the sbin directories areadded to the user's inherited $PATH variable.

# ifconfig. . . output omitted . . .

Return to the regular, unprivileged user account:11)

# exit

Use the su command with the - option to become the root user via a login shell12)(which processes root's login scripts):

$ su -Password: makeitso Õ

This time, the root shell has the correct environment. Check the user ID and13)group memberships:

# id -uRemember that UID of 0 is root0

Compare the output of these commands to the previously obtained output:14)

# echo $PATH. . . output omitted . . .# pwd. . . output omitted . . .

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 60: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

2-32

Note how the environment has changed to be root's native environment. Mostdistributions only include the sbin directories in the $PATH of the root user.

[S11] This step should only be performed on SLES11.15)Run the ifconfig utility again:

# ifconfig. . . output omitted . . .

It works as the ifconfig utility is located at /sbin/ifconfig and that directory isin the root user's $PATH.

Observe how with root privileges the su command will switch to another account16)without knowing or supplying a password:

There is no prompt for a password.# su - guru

See that the environment has changed to that of the guru user:17)$ id. . . output omitted . . .$ pwd. . . output omitted . . .

Return to the root shell:18)$ exit

[R6 S11] This step should only be performed on RHEL6/SLES11.19)Administrative privileges are no longer required; exit the root shell to return to anunprivileged account:

# exit

[U1204] This step should only be performed on U12.04.20)Return to the guru user's shell and remove the root user's password:

# exit$ sudo passwd -l root[sudo] password for guru: work Õ

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 61: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

Chapter

12PROCESSMANAGEMENTAND JOBCONTROL

ContentWhat is a Process? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Process Lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Process States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Viewing Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Tools to Send Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Job Control Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Job Control Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Persistent Shell Sessions with Screen . . . . . . . . . . . . . . . . 10Using screen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Advanced Screen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Lab Tasks 14

1. Job Control Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152. Process Management and Job Control Basics . . . . . . 213. Screen Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254. Using Screen Regions . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 62: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-2

What is a Process?

A process is a launched programAssociated with a process:• process ID (PID)• priority• nice value• memory• security context• environment• file handles• exit status

What is a Process?

A process is often described as a program. This definition, while easyto understand, may lead to an inaccurate view of what a processreally is. For example, launching a single program may in fact startseveral processes. Each process on the system has certain resourcesassociated with it. These resources include:

y Thread(s) – or in other words, executable codey Process ID – a number that uniquely identifies the process on

the systemy Virtual memory – a combination of both RAM and swap spacey Security context – effective UID and GID, and occasionally

additional information like POSIX capabilities, used to determinewhich resources the process can accessy Environmental variables – inherited from the parent process that

spawned it

Mozilla application

Mozilla web browser Mozilla email client

web

bro

wse

r th

read

web

bro

wse

r th

read

web

bro

wse

r th

read

web

bro

wse

r th

read

emai

l clie

nt

thre

ad

Application

Processes

Threads

Consider the Mozilla application. Although it is just one application,Mozilla, when run it consists of multiple separate processes whichinteract. A process is run for the Mozilla web browser, and additionalprocesses are run for the supplemental components (such as thechat client, and the Email client). Some of these processes which runare multi threaded. For example, the Mozilla web browser processtypically spawns off three or four different threads which are used fordifferent purposes (one thread does DNS queries, another does webrequests, and so forth).

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 63: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-3

Process Lifecycle

Processes are organized in a hierarchy• init – first process spawned by kernel with PID of 1

the only process directly launched by the kernelinit will spawn child processes

• child processes spawn other children, etc.Processes can be created by two methods• fork() – create child duplicate of self• exec() – spawn completely new process that replaces parent• fork() + exec() – method for launching different process

Process termination methods• Normal termination via exit()• Abnormal termination via abort() or uncaught signal

Process Creation

As the system boots, the kernel will locate and load the initialprocess init. As the first process, init will be assigned a PIDnumber of 1. Part of init's loading procedure is to determine thedesired run level, and load the services necessary for that run level. Inother words, init will launch other processes which become childprocesses. These children may in turn launch additional processeswhich in turn become children. These processes can be viewed as ahierarchy with init acting as the head.

There are two basic methods that can be used by a process tospawn another process. In the first, the process will fork(). When aprocess fork()s, it creates a duplicate of itself. This duplicateprocess need not behave exactly like the parent. This method isfrequently used by programs that need to simultaneously acceptseveral sessions. For example, consider a web server process that islistening for connects. When a connection is made, the process couldfork() a child and hand the connection to the child for processing.The original parent web process could then return to listening foradditional connection requests.

The second method of creating a new process is to exec() a newprocess. When a process exec()'s a new process, it actuallybecomes a completely new process. In other words, the old processis destroyed, and the new process takes its place. The execcommand allows this method to be used from the command line. Forexample, from a login prompt the following example will cause thessh command to replace the bash shell so that when the SSH

session is exited, the terminal will close:

# exec ssh [email protected]

When a process wants to launch a different process, for examplewhen bash runs ls, the fork() + exec() method is used. When ls istyped at the command prompt, bash will fork a copy of itself, andthen that new copy will exec() the ls command.

Process Termination

Typically when a process is done it will gracefully exit. This is mostcommonly done internally in the process by returning from main() orby calling exit(). When a program calls exit() it supplies an integerargument from 0 to 255 that is used as the exit status for theprocess. The convention is that zero indicates success and non zeroindicates an error or non-success. For example, grep uses a statusvalue of 1 to indicate that a match wasn't found. The exit status forthe child process is read by the parent process calling wait(2) orwaitpid(2). A parent is automatically notified by the kernel of a childprocess exiting by a SIGCHLD signal.

A process can abnormally terminate either explicitly by callingabort() or by receiving a signal that isn't caught. A specific signalcan be caught by a process that causes certain instructions to beexecuted when the signal is received. A signal can be sent by aparent process or manually via the kill command.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 64: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-4

Process States

Processes can transition between states upon receipt of signalsrunning ⇒ currently being allocated CPU slicesstopped ⇒ still loaded in memory, but not runningsleeping ⇒ waiting for some event (ex. user input)un-interruptible sleep ⇒ as the name suggests; usually caused

when waiting for I/Ozombie ⇒ a terminated process whose resources have all been

freed except for a PID and exit status

Process States

Just because a program has been launched does not necessarilymean that it is actively running. In fact, processes can be in severalstates. On a multitasking system, this functionality is importantbecause many processes can be loaded at any given time.Frequently, the majority of the processes will be sleeping as theywait for some specific event to occur.

It is important to understand the difference between sleepingprocesses, and stopped processes. When a process is stopped, it isno longer receiving any CPU cycles.

Zombie Processes

When a process terminates, all resources such as memory and filehandles are freed. However, its exit status is stored and the PIDnumber is still assigned and is listed in the process table viewable bythe ps command. The process will show the zombie (Z) status. ThePID and exit status remain until the parent process calls wait(2) orwaitpid(2) to read the exit status. At that point the PID number isfreed and the process is fully terminated.

Usually the parent calls wait(2) or waitpid(2) immediately on theterminating child process when it receives the automatic SIGCHLDsignal. This calling of wait/waitpid is known as reaping. Until theparent makes the wait/waitpid call, the terminated process will bein zombie status; all processes are zombies for a short period oftime. However, if the parent fails to call wait/waitpid the process is

stuck in zombie status. It is worth reiterating that a zombie processconsumes no system resources so they are not detrimental to thesystem unless so many exist that PID numbers become scarce. Ifthere are many zombie processes on a system it can indicate abuggy or inattentive parent.

If a developer decides that the parent process doesn't need to checkthe exit status of its children, the developer can explicitly define asignal handler for SIGCHLD to ignore, or set a special flag,SA_NOCLDWAIT. This way exit status information for child processes isdiscarded and terminating child processes never enter zombie status.

To manually remove a zombie process try re-sending SIGCHLD to theparent process to see if the parent will call wait/waitpid. If theparent still doesn't issue the wait/waitpid call, terminate the parent.The zombie processes will now become orphan processes and willbe re-parented to init. Periodically init will call wait/waitpid onany zombie processes that are its children causing them to fullyterminate.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 65: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-5

Viewing Processes

ps – standard command to view process info• supports many options to modify output• can emulate behavior of other Unix variants ps• reads information from the /proc/ filesystem

top – similar to ps, but interactive• refreshes display every 3 seconds by default• can sort processes by various criteria such as CPU usage,

memory, UID, etc.• can send signals to processes

gnome-system-monitor – limited GUI top-like programKDE System Guard (ksysguard) – GUI with extensive local & remotemonitoring capabilities

Viewing Processes with ps

The ps or process status command will report information aboutprocesses running on the system. It is very flexible in formatting andsorting its output. The many different ps commands for Unix behavedifferently. The Linux ps command attempts to support or emulatethe behavior of as many variations as possible by default. Tocompletely emulate the behavior of a specific platform's ps, you canset the PS_PERSONALITY environment variable to the desired systemtype. Because it supports so many options, special care must betaken to ensure syntax is correct:

y Standard Unix98 options (typically used on commercial Unixvariants such as Solaris) have a single dash (-ef)y Traditional BSD options don't have a dash (aux)y GNU specific options have two dashes (--sort user)

For example, the command ps -a specifies that the ps commandshould use the Unix98-style a option (which, according to the Unix98standard, displays all child processes which have associatedterminals), while the command ps a specifies that the ps commandshould use the BSD-style a option (which traditionally displays allprocesses running within the current terminal).

ps extracts information about processes from the /proc filesystem. Ifyou have not compiled support for the /proc filesystem into yourkernel, then ps will not work.

The top Command

If you want to see process information displayed in a more real-timefashion, then you can use the top command. By default, top willdisplay processes sorted by CPU usage and will auto refresh every 3seconds, though you can press the space bar to manually refresh atany time. This provides for an extremely convenient way of locatingprocesses that have gone crazy and are eating up excessive CPUtime. Once you locate a process that is consuming more CPU timethan it should, you can send the process a TERM (15) or KILL (9)signal right from top. For a list of the commands supported, press hwhile top is running.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 66: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-6

Signals

Special message that can be sent to a processProcesses can install signal handlers that catch signals and triggersome action

Signals can have different meanings on different architecturesSome signals cannot be caught or ignored and are processed by thekernel (ex. SIGKILL (9))

Signals

Signals provide a mechanism that is used to communicate theoccurrence of important events to a process. At their lowest level,signals are represented by a number. Furthermore, signals are givensymbolic names that correspond to their intended or conventionaluse. Some signal are architecture-dependent and only found onspecific platforms. Associated with each signal is some type ofdefault action. For example, when a process receives a SIGFPE (8)from the system, this indicates that the process has caused a floatingpoint error (attempted to divide by zero, or some similar action) andthe default action is for the process to terminate and dump core.

Signal Handlers

As part of their code, processes can contain signal handlers. Thesesignal handlers are installed by the process, and catch signals thatare sent to the process. The process can then handle the signal inwhatever fashion it chooses. For example, consider a calculatorprogram that installs a signal handler for the SIGFPE (8) signal. Whenfloating point error signal is received, the process may choose todisplay an error message to the user instead of the default action ofterminating and dumping core.

Processes cannot install signal handlers for the SIGSTOP (19) andSIGKILL (9) signals. To provide the desired behavior, these twosignals are caught and enforced by the kernel.

The following table lists important signals supported by Linux. The

table is based off of information in the signal(7) man page.

Signal Value Action Comment

SIGHUP 1 Term Hangup detected on controlling terminal ordeath of controlling process

SIGINT 2 Term Interrupt from keyboard

SIGQUIT 3 Core Quit from keyboard

SIGFPE 8 Core Floating point exception

SIGKILL 9 Term Kill signal

SIGSEGV 11 Core Invalid memory reference

SIGPIPE 13 Term Broken pipe: write to pipe with no readers

SIGTERM 15 Term Termination signal

SIGCHLD 17 Ign Child stopped or terminated

SIGCONT 18 Continue if stopped

SIGSTOP 19 Stop Stop process

Term ⇒ Default action is to terminate the process.Ign ⇒ Default action is to ignore the signal.Core ⇒ Default action is to terminate the process and dump core.Stop ⇒ Default action is to stop the process.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 67: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-7

Tools to Send Signals

kill – Send arbitrary signals to process by PID• sends a SIGTERM (15) by default• -l lists all signals supported on the machine

killall – Send signal to process by namepkill – Send signal to process by terminal, group, username, PID, orcommand nametop, gnome-system-monitor, ksysguard can also send signalsCertain key bindings send signals• Ó¿c = SIGINT (2)• Ó¿z = SIGSTOP (19)

Sending Signals

There are many ways that you can send signals to processes on thesystem. Probably the most common way is through the killcommand or one of its derivatives. Perhaps because of its name,many people incorrectly assume that this family of commands canonly be used to send a kill signal. To be fair, this is probably the mostcommon use, although any valid signal can be sent with thesecommands by specifying the signal number (or symbolic name) tosend. For example, to send a SIGHUP (1) signal to the inetd process(assume it has a PID of 445), execute any of these commands:

# kill -s 1 445# killall -HUP inetd# killall -1 inetd

The pkill command can be used to pass signals to processes basedon the UID that owns the process. For example, to stop all processesowned by the username guru you can execute the followingcommand:

# pkill -STOP -u guru

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 68: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-8

Job Control Overview

Job control gives you the ability to do multitasking at the commandline

Job control refers to the ability to selectively stop (suspend) theexecution of processes and continue (resume) their execution at alater point

These functions are exposed to the user via the shell• Older or minimalist shells may not support job control

Multi-Tasking

In a graphical windowing environment, you may have severalprograms open and running at the same time. When you press a keyor click the mouse, how does the system know which programshould receive that input? The program that receives the input iswhichever program is currently in the foreground (active). In mostgraphical environments, if you want to make another program active,you can switch the focus by clicking on another window. This movesthe program into the foreground, and allows you to interact with it.

Multi-Tasking from the Command Line

From the command line, the task of juggling and interacting withmany processes poses a more difficult problem. Normally, when youlaunch a program from the shell it becomes the new foregroundprocess, and you then have no way of launching a new process. Inessence, the new program has taken control of the shell. The jobcontrol functions provided by the shell allow you to temporarily stopthe process which returns control to the shell. You can then use thevarious job control commands to start the process running in thebackground or foreground, or kill the process. You can also choosejust to leave the process stopped for the time being, and move someother process to the foreground.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 69: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-9

Job Control Commands

Start a process as a background process by running program &Stop an already running process by sending it a SIGSTOP (19), (ex.pressingÓ¿z)• fg – run the job in the foreground• bg – run the job in the background• kill – terminate the job

Refer to jobs using %n, where n is the job numberThe jobs command will list all jobs present on the shell but can notlist jobs for other shells

Managing Jobs

Typing the SUSPEND character (typically Ó¿z) while a process isrunning causes that process to be stopped and returns you to theshell prompt. Typing the DELAYED SUSPEND character (typicallyÓ¿y) causes the process to be stopped when it attempts to readinput from the terminal, and control to be returned to bash. You maythen manipulate the state of this job, using the bg command tocontinue it in the background, the fg command to continue it in theforeground, or the kill command to kill it. A Ó¿z takes effectimmediately, and has the additional side effect of causing pendingoutput and typeahead to be discarded.

$ man screenÓ¿z[1]+ Stopped man screen$

Referencing Jobs

There are a number of ways to refer to a job in the shell. Thecharacter % introduces a job name. Job number n may be referred toas %n. A job may also be referred to using a prefix of the name usedto start it, or using a sub-string that appears in its command line. Forexample, %ce refers to a stopped ce job. Using %?ce, on the otherhand, refers to any job containing the string ce in its command line. Ifthe prefix or sub-string matches more than one job, Bash reports anerror. The symbols %% and %+ refer to the shell's notion of the currentjob, which is the last job stopped while it was in the foreground. Theprevious job may be referenced using %-. In output pertaining to jobs(e.g., the output of the jobs command), the current job is alwaysflagged with a +, and the previous job with a -.

Simply naming a job can be used to bring it into the foreground: %1 isa synonym for fg 1, bringing job 1 from the background into theforeground. Similarly, %1 & resumes job 1 in the background,equivalent to bg 1

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 70: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-10

Persistent Shell Sessions with Screen

Terminal Multiplexer (window manager)Allows for very efficient multitasking from a virtual terminalSessions can be disconnected and reconnected at willUseful for remote administration

Screen

One of the biggest problems with running programs in a terminal isthat if the terminal disappears, or is killed, the processes running aschildren will receive a HUP signal. Most programs which write to aterminal are designed to exit upon receiving that signal.

Screen is a text-terminal multiplexer which allows for running one ormore programs at the same time without using more than oneterminal. Each window is independent, and the programs running oneach window run as normal, even if not in the foreground, (avoidingchanging the process state, as required with job control).

The real power of screen comes from the fact that each session iscontrolled by a terminal manager. The terminal manager senses whenthe connection to the terminal is broken (such as a ssh connectiondying) and detaches the screen session from the terminal. Allowingyou to re-attach to the session later as if nothing had happened at all.

Each window under screen is completely vt100 compliant, and has itsown scroll-back buffer.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 71: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-11

Using screen

Starting screenCommandsDetaching and re-attaching to sessionsSession basics

Starting Screen

Starting screen without any arguments will launch a new screensession and spawn a shell. You can also specify a command to runfrom the command line:

$ screen program

In this example, the screen command will run the specified programand unless you create other windows screen will terminate when thatprogram exits.

Screen Commands

All keystrokes are sent through the screen session to the program orshell that is running under it, with the exception of the screencommand character (Ó¿a by default). Any keystroke that followsthe command character is interpreted by the screen manager.

Basic Commands

Command Function

Ó¿a0-9 Switch to window number 0-9

Ó¿ad Detach session

Ó¿aÒ¿DÒ¿D Detach and logout

Ó¿ac Create a new window with a shell

Ó¿aÓ¿a Switch to previously displayed window

Ó¿an Switch to next window numerically

Ó¿ap Switch to the previous window numerically

Ó¿ak Kill the current window

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 72: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-12

Screen Command-line Options

The screen program supports quite a few command-line options thatmay be combined for powerful session management. The table thatfollows, details the function of a few important command line optionsfor the screen command:

Option Function

-r [pid] re-attach to a session

-R re-attach to the first detected detached session; if itdoesn't exist create it.

-r -x[pid] attach to live session (multi display mode)

-d [pid] detach a screen session

-D [pid] detach a screen session and logout

-m ignore $STY variable (create new session no matter ifcalled in screen or not)

-d -m start screen in "detached" mode

The [pid] option may be needed to differentiate between two ormore running screen sessions. A session must first be in thedetached state in order to re-attach to it unless you use the -doption. You can see a list of all current screen sessions by running:

# screen -list

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 73: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-13

Advanced Screen

Session lockingSplit-screenMonitoring sessionsSharing screen sessionsDefault settings• System-wide: /etc/screenrc• Per user: ~/.screenrc

Advanced Screen

Screen is impressively feature rich. Advanced features include thingssuch as the ability to lock a terminal, the ability to share a session,split screen, and the ability to monitor a session.

Session Locking

To lock a Screen session: use the command Ó¿ax. This will lockthe session with your user password by default. You can specify apassword by inserting the crypted hash in your ~/.screenrc file.

Split-Screen

Screen allows you to divide your terminal horizontally into differentregions. Each of these regions can contain an independent windowfrom your Screen session. To split the current region in half use thecommand Ó¿aÒ¿S, you can then toggle between the differentregions using the command Ó¿aÐ. Use the other Screencommands to control each region and its corresponding window.Ó¿ax kills a screen.

Monitoring Screen Windows

When working with multiple windows on a single terminal, it can behelpful to know when a window that is not in the foreground hasfinished a task, or has been written to by some program. Screen hasa monitoring function to do just that. Use the command Ó¿aÒ¿Mto toggle monitoring for activity on a window. Use Ó¿aÒ¿_ tomonitor for 30 seconds of inactivity (this value can be modified by an

entry to your ~/.screenrc file).

Sharing Screen Sessions

One advanced feature of screen allows two or more people to viewand use a screen window at the same time. This is very useful forteaching someone a procedure or to troubleshoot a problem whileone or more persons follow along. The people attending the sessioncan SSH into the system from multiple remote locations. If twosystem admins are both logged into the same system as root, dothe following to share a screen session:

[sys admin 1]# screen[sys admin 2]# screen -x -r

To do screen session sharing between multiple non-root usersrequires that you change the screen binary to SUID root in order forscreen to be able to access another user's socket files. This could bea security issue if there are bugs in screen. If you are willing to takethe risk take the following steps:

1. Make the binary (usually /usr/bin/screen) SUID root2. Start the desired Screen session3. Use the command Ó¿a:multiuser on to enable multi-user

mode4. Use the command Ó¿a:acladd username to enable access

to the specified user5. Have that user connect to your session using the command:

$ screen -r -x screenuser/pid

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 74: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-14

Lab 12Estimated Time:U1204: 45 minutes

R6: 45 minutes

S11: 45 minutesTask 1: Job Control BasicsPage: 12-15 Time: 10 minutesRequirements: b (1 station) d (graphical environment)

Task 2: Process Management and Job Control BasicsPage: 12-21 Time: 10 minutesRequirements: b (1 station) d (graphical environment)

Task 3: Screen BasicsPage: 12-25 Time: 15 minutesRequirements: b (1 station)

Task 4: Using Screen RegionsPage: 12-28 Time: 10 minutesRequirements: b (1 station)

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 75: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-15

Objectivesy Create jobs on the command line to explore simple multi-tasking.

Requirementsb (1 station) d (graphical environment)

RelevanceThis task covers the basics of multi-tasking from the command line. Manydifferent tasks can be completed at the same time or suspended to workon more important tasks.

Noticesy This lab must be run from within the graphical environment. If you are

unsure how to login to the graphical environment, ask your instructor forhelp.

Lab 12

Task 1Job Control BasicsEstimated Time: 10 minutes

[R6 U1204] This step should only be performed on RHEL6/U12.04.1)Install X Window System applications for demonstrating job control:

$ su -c "yum install -y xorg-x11-apps xterm"[R6]

Password: makeitso Õ[R6]

$ sudo apt-get install -y x11-apps gedit xterm gcalctool[U1204]

[sudo] password for guru: work Õ[U1204]

Open the man page for the Bash shell:2)

$ man bashBASH(1) BASH(1)

NAME bash - GNU Bourne-Again SHell. . . snip . . .

Move to the JOB CONTROL section of the Bash man page, and suspend the man3)process:

/ˆJOB CONTROLÕJOB CONTROL Job control refers to the ability to selectively stop (suspend) the execution of processes and continue (resume) their execution at a later

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 76: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-16

point. A user typically employs this facility via an interactive interface supplied jointly by the system's terminal driver and bash.. . . snip . . .Ó¿z[1]+ Stopped man bash

List the jobs running in the background:4)

$ jobs -l[1]+ 4434 Stopped man bash

Start an instance of vim and then suspend it:5)

$ vim /etc/fstabÓ¿z[2]+ Stopped vim /etc/fstab

Start a second instance of vim running in the background:6)

$ vim /etc/pam.d/ &[3] 14444

Launch some X applications from the command line, forking them into the7)background:

$ xlogo &Notice that the ampersand can be placed at the end ofa command with or without space between them.

$ gnome-calculator&$ gedit &$ xterm &

Run xclock from the GUI launcher:8)

Ô¿Å Open the "Run Application" window.

xclockÕ Execute the xclock command.

View all of the tasks now currently executing on the system:9)

$ jobs -l

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 77: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-17

Notice that the process id (in the second column)numbers may be different on your system.

[1] 4434 Stopped man bash[2]- 4526 Stopped vim /etc/fstab[3]+ 4527 Stopped (tty output) vim /etc/pam.d/[4] 4573 Running xlogo &[5] 4574 Running gnome-calculator &[6] 4575 Running gedit &[7] 4576 Running xterm &

One thing to notice from this output is the fact that xclock is not listed. This isbecause it was not launched from this shell (where jobs -l was run).

Use various command to see the relationship between the shell and these jobs:10)f option shows ASCII-art "forest" view and t optionselects just processes on this terminal

$ ps f t. . . output omitted . . .

$$ variable resolves to pid of this shell$ ps --ppid $$. . . output omitted . . .$ pstree. . . output omitted . . .

Bring the most recently suspended process back to the foreground and suspend11)it again. Then bring job [1] to the foreground and suspend it:

$ fgÓ¿z$ fg 1Ó¿z

Launch the find command in the background while redirecting both STDOUT and12)STDERR:

$ find / > output.txt 2> errors.txt &

Move through the next few steps quickly.

Run the jobs command and notice that find is running in the background:13)

$ jobsId numbers may be different on your system.[1]+ Stopped man bash

[2] Stopped vim /etc/fstab

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 78: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-18

[3]- Stopped vim /etc/pam.d/[4] Running xlogo &[5] Running gnome-calculator &[6] Running gedit &[7] Running xterm &[8] Running find / >output.txt 2>errors.txt &

Use the tail command to watch the output.txt file grow:14)

$ tail -f output.txt

After a few seconds of watching output.txt grow, kill the tail process:15)

Watch the output of tail for a couple of seconds.As the find command discovers additional files and they are added to output.txt, the tail process willdisplay the new lines of data.

Ó¿c Send the TERM signal to the tail process.

Launch another find program, this time redirecting output to a different file.16)Because of disk caching, the command will execute much faster this time. After itlaunches, quickly suspend it:

$ find / &> stderrandstdout.txt

Quickly suspend with Ó¿z.

Investigate which processes are running:17)

$ jobs. . . output omitted . . .$ bg

Continue working while the find process(es) run in the background.

Bring the gedit program into the foreground, then suspend the job:18)Depending on when the find command finished the jobnumber for gedit will be different. If so, get the correctjob number with the jobs command.

$ fg 6Ó¿z

Try using the gedit application window. It will not respond.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 79: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-19

Send the gedit process directly to running in the background from the stopped19)state, without bringing it into the foreground first:

$ bg 6

Try using the gedit application window. This time, it works and the commandprompt is still available in the shell.

Use jobs to check on the current state of all jobs under control:20)

$ jobs -l[1]+ 4434 Stopped man bash[2] 4526 Stopped vim /etc/fstab[3] 4527 Stopped vim /etc/pam.d/[4] 4573 Running xlogo &[5] 4574 Running gnome-calculator &[6] 4574 Running gedit &[7]- 4575 Running xterm &

Bring each of the vim jobs into the foreground and close them:21)

$ jobs. . . output omitted . . .$ fg %2:q!Õ$ fg %3:q!Õ

Use kill from the command line to end the process running man:22)

$ kill %man

Make sure that there are no more stopped jobs using the jobs command:23)

$ jobs -l[4] 4573 Running xlogo &[5] 4574 Running gnome-calculator &[6]- 4574 Running gedit &[7]+ 4575 Running xterm &

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 80: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-20

Clean up by terminating all the remaining running jobs:24)

$ kill %{4..7}EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 81: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-21

Objectivesy Explore process management tools and investigate the current state of

the system.y Use a "fork bomb" to create a large number of processes to manage.y Use kill, killall, pgrep, pkill, and gnome-system-monitor to kill

processes.

Requirementsb (1 station) d (graphical environment)

RelevanceThis lab task focuses on many different process management tools. Theability to manage processes helps greatly in the control of your system.Creating a "fork bomb" will automatically create a large number ofprocesses which will need to be managed. Processes over-running yoursystem can cause issues. Learn how to destroy processes using variousprocess management tools.

Noticesy This task should be run as the guru user to limit the damage that can be

caused to the system.

Lab 12

Task 2Process Management andJob Control BasicsEstimated Time: 10 minutes

[U1204] This step should only be performed on U12.04.1)Install the GNOME System Monitor:

$ sudo apt-get install -y gnome-system-monitor[sudo] password for guru: work Õ

Change to the guru user's home directory:2)$ cd

Create a simple shell script that will launch several child processes. Create the3)script fork-script:

File: fork-script+ #!/bin/sh+ for i in $(seq $1); do+ /tmp/bomb.sh &+ done

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 82: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-22

Set the file executable:4)

$ chmod u+x fork-script

The fork-script script relies on the presence of the /tmp/bomb.sh script. Create5)the script:

File: /tmp/bomb.sh+ #!/bin/sh+ sleep 10+ cat /dev/zero > /dev/null

Set the file executable:6)

$ chmod u+x /tmp/bomb.sh

Run the fork script:7)

$ ./fork-script 10

Viewing Running Processes

Use ps to find the bombs running on the system:8)

$ psNotice that the process id numbers may be different onyour system.

1660 pts/1 00:00:01 bash4529 pts/1 00:00:06 bomb.sh4691 pts/1 00:00:00 bomb.sh4694 pts/1 00:00:00 bomb.sh. . . snip . . .4699 pts/1 00:00:01 cat5079 pts/1 00:00:02 cat5080 pts/1 00:00:01 cat. . . snip . . .5080 pts/1 00:00:00 ps

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 83: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-23

Use GNOME System Monitor to view processes, (KDE has an equivalent graphical9)process monitoring tool called KDE System Guard):

Ô¿Å Open the Run Program dialog.

gnome-system-monitorÕStart GNOME System Monitor.

Click the Processes tab.Scroll down the list to find the bomb.sh processes. Each bomb.sh script will show up as an sh process with achild cat process.

Feel free to change the view options and explore the different informationavailable from the GNOME System Monitor. Leave the program running whenmoving on to the next step.

Use pstree on the command line to see the relationships between various10)processes on the system:

The -c option prevents pstree from visually mergingidentical branches of output.

$ pstree -c. . . output omitted . . .

Use GNOME System Monitor to kill some of the bomb.sh instances:11)

Click the Processes tab.Locate the bomb.sh sh processes.

Right-click on one of the bomb.sh instances.This opens up a context menu.

Select Kill Process.Terminate the selected bomb.sh process.

Repeat this process on two more of the bombs.

In the xterm shell (launched earlier) find and kill the remaining bombs. Verify that12)all of the bombs are gone:

$ ps -ef | grep bomb[.]shguru 8313 1 0 18:04 pts/4 00:00:00 /bin/sh /tmp/bomb.shguru 8314 1 0 18:04 pts/4 00:00:00 /bin/sh /tmp/bomb.sh

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 84: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-24

guru 8315 1 0 18:04 pts/4 00:00:00 /bin/sh /tmp/bomb.shguru 8316 1 0 18:04 pts/4 00:00:00 /bin/sh /tmp/bomb.sh$ killall bomb.sh$ ps -ef | grep bomb[.]sh

The bomb.sh script launched child cat processes. Use the pkill command to13)terminate any stray cats:

The -x option causes pkill to only select processeswhose name matches exactly instead of a sub-stringmatch.

$ pkill -x cat. . . output omitted . . .

Close the xterm process:14)

Ó¿d Send an EOL (end of line) character to tell the shell to exit.

Repeat until xterm closes.Nested shells may require closing more than one shell.

Close each window still on the desktop.15)

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 85: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-25

Objectivesy Create a screen session.y Detach from the screen session and attach to a lab partner's session.

Requirementsb (1 station)

RelevanceScreen is a very useful way of doing more than just multi-tasking. In thistask, you will explore the usability and power of the screen command.

Lab 12

Task 3Screen BasicsEstimated Time: 15 minutes

[R6 U1204] This step should only be performed on RHEL6/U12.04.1)Install the screen package:

$ su -c "yum install -y screen"[R6]

Password: makeitso Õ[R6]

. . . output omitted . . .[R6]

$ sudo apt-get install screen[U1204]

[sudo] password for guru: work Õ[U1204]

. . . output omitted . . . [U1204]

Verify that there are no screen sessions running on your machine:2)

$ screen -listNo Sockets found in /var/run/screen/S-guru.[R6 U1204]

No Sockets found in /var/run/uscreens/S-guru.[S11]

Start screen, run some commands, open new screen windows, and switch3)between the windows:

$ screenThis closes the screen copyright information window.You may have to space through two pages.

$ Ö[S11 U1204]

[window 0]$ echo this is window 0this is is window 0[window 0]$ Ó¿a c[window 1]$ echo this is window 1this is is window 1[window 1]$ Ó¿a Ó¿a[window 0]$ Ó¿a Ó¿a

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 86: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-26

[window 1]$

List the windows in the screen session:4)

Double quote character.[window 1]$ Ó¿a Ò¿"Num Name Flags 0 bash $ 1 bash $

Return to window 0:5)

Select "0 bash". Use the arrow keys to highlight the line starting "0 bash".

Õ Change to window 0.

Create another screen window by pressing:6)

[window 0]$ Ó¿a c[window 2]$ man screen

Show a list of all windows in the screen session:7)

Double quote character.[window 2]$ Ó¿a Ò¿"Num Name Flags 0 bash $ 1 bash $ 2 bash $

Switch directly between windows:8)

Ó¿a 1 Switch directly to window number 1.

Ó¿a 0 Switch directly to window number 0.

Ó¿a 2 Switch back to window 2.

Give window 2 a title other than the default of "bash":9)

Ó¿a Ò¿A Tell screen that you want to change the name of the window.

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 87: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-27

× × × ×

Use × to delete the word "bash".Window for manÕ

Enter the new title.

Show a list of all windows in the screen session:10)

[window 2]$ Ó¿a Ò¿" 0 bash $ 1 bash $ 2 Window for man $

Detach from the screen session:11)

Ó¿a d[detached]

Display, then reconnect to, your screen session:12)

$ screen -listThere is a screen on: 29765.pts-1.stationX (Detached)1 Socket in /var/run/screen/S-guru.[R6 U1204]

1 Socket in /var/run/uscreens/S-guru.[S11]

$ screen -dR

Exit from the screen session and all windows:13)

[window 0]$ Ó¿a:quit[screen is terminating][U1204]

$ screen -listNo Sockets found in /var/run/screen/S-guru.[R6 U1204]

No Sockets found in /var/run/uscreens/S-guru.[S11]

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 88: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-28

Objectivesy Create a split screen session.

Requirementsb (1 station)

RelevanceScreen can do much more than just multi-tasking. Discover some otherpowerful modes and uses of screen in this task.

Lab 12

Task 4Using Screen RegionsEstimated Time: 10 minutes

Make sure that you are not already running a screen session:1)

$ screen -listNo Sockets found in /var/run/screen/S-guru.[R6 U1204]

No Sockets found in /var/run/screens/S-guru.[S11]

Create a screen session:2)

$ screenThis closes the copyright information screen.$ ÖÖ[S11 U1204]

$ screen -listThere is a screen on: 32333.pts-1.stationX (Attached)1 Socket in /var/run/screen/S-guru.[R6 U1204]

1 Socket in /var/run/screens/S-guru.[S11]

[R6 S11] This step should only be performed on RHEL6/SLES11.3)Split the terminal into two regions. In the first region start the tail command tomonitor /var/log/messages:

$ Ó¿a Ò¿S[region 1]$ su -c "tail -f /var/log/messages"Password: makeitso Õ. . . snip . . .

[U1204] This step should only be performed on U12.04.4)Split the terminal into two regions. In the first region start the tail command tomonitor /var/log/syslog:

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 89: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-29

$ Ó¿a Ò¿S[region 1]$ sudo tail -f /var/log/syslog[sudo] password for guru: work Õ. . . snip . . .

Move to the second region and create a new screen window:5)

Ó¿a Ð Switch to the second region.

Ó¿a c Create a new window in the second region.

[R6 S11] This step should only be performed on RHEL6/SLES11.6)The following actions require administrative privileges. Switch to a root loginshell:

$ su -lPassword: makeitso Õ

Restart a few daemons. Note that both the output of the init script and updates7)to /var/log/messages are displayed:

[region 2]# service autofs restart[R6 S11]

. . . output omitted . . .[R6 S11]

[region 2]# service sshd restart[R6 S11]

. . . output omitted . . .[R6 S11]

[region 2]$ sudo service ssh restart[U1204]

. . . output omitted . . .[U1204]

[region 2]$ sudo service cups restart[U1204]

. . . output omitted . . . [U1204]

[R6 S11] This step should only be performed on RHEL6/SLES11.8)Administrative privileges are no longer required; exit the root shell to return to anunprivileged account:

# exit

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.

Page 90: GL120 Linux Fundamentals - ITCourseware · 2013-02-15 · LINUX FUNDAMENTALS RHEL6 SLES11 U12.04 The contents of this course and all its modules and related materials, including handouts

12-30

Remove the first region from your terminal and send its window to the9)background:

$ Ó¿a Ò¿Q

Switch between the two screen windows:10)

[window 1]$ Ó¿a Ó¿a[window 0]$ Ó¿a Ó¿a[window 1]$

Switch to window 0 and stop the tail command:11)

[window 1]$ Ó¿a 0Ó¿c

End the current screen session:12)

[window 0]$ Ó¿a:quit

Exit from the screen session.13)

$ Ó¿d

EVALUTION COPY

Unauthorized reproduction or distribution is prohibited.