an introduction to linux - cmpe webuskudarli/courses... · the linux equivalent of help is man...
TRANSCRIPT
An Introduction to An Introduction to LinuxLinux
What is LinuxWhat is Linux A fully-networked 32/64-Bit A fully-networked 32/64-Bit Unix-like Unix-like Operating SystemOperating System
Unix Tools Like sed, awk, and grep Unix Tools Like sed, awk, and grep Compilers Like C, C++, FortranCompilers Like C, C++, Fortran
Network Tools Like telnet, ftp, ping, tracerouteNetwork Tools Like telnet, ftp, ping, traceroute Multi-user, Multitasking, MultiprocessorMulti-user, Multitasking, Multiprocessor Has the X Windows GUI Has the X Windows GUI
Runs on multiple platformsRuns on multiple platforms Includes the Source CodeIncludes the Source Code
Where did it come from?Where did it come from? Linus Torvalds created itLinus Torvalds created it
with assistance from programmers around the worldwith assistance from programmers around the world first posted on Internet in 1991first posted on Internet in 1991
Linux 1.0 in 1994; 2.2 in 1999Linux 1.0 in 1994; 2.2 in 1999 Today used on 7-10 million computersToday used on 7-10 million computers
with 1000’s of programmers working to enhance itwith 1000’s of programmers working to enhance it
Logging InLogging In login with account and password:login with account and password:
ubuntu login: uskudarliPassword:Last login: Tue Oct 15 10:13:13 from ubuntu[uskudarli@ubuntu uskudarli]$
Root Login!!!Root Login!!!
Do not login as root unless you have toDo not login as root unless you have to root is the system superuser root is the system superuser
Normal protection can be overriddenNormal protection can be overridden Careless use can cause damageCareless use can cause damage Has full access to everything by defaultHas full access to everything by default
root is the only user defined when you installroot is the only user defined when you install change root’s passwordchange root’s password define “regular” users for everyday usedefine “regular” users for everyday use
Creating a new userCreating a new user
Use the Use the useradduseradd command command Use the Use the passwdpasswd command to set password command to set password
[root@ubuntu]# useradd yildirim[root@ubuntu]# passwd yildirimChanging password for user yildirimNew UNIX password:Retype new UNIX password:passwd: all authentication tokens updated successfully[root@ubuntu]#
Adding a new userAdding a new user Limits on users can be controlled byLimits on users can be controlled by
QuotasQuotas ulimitulimit command command
Authority levels for a user controlled by Authority levels for a user controlled by groupgroup membershipmembership
Users and GroupsUsers and Groups
Users are identified by user identifications (UIDs)Users are identified by user identifications (UIDs) UIDs are associated with an integer [0 - 4 294 967 295UIDs are associated with an integer [0 - 4 294 967 295]]
(X� FFFFFFFF� ). (X� FFFFFFFF� ). Users with UID=0 have superuser privileges. Users with UID=0 have superuser privileges. Users are placed in groups, Users are placed in groups, Group have identifications (GIDs). Group have identifications (GIDs). Each GID is associated with an integer [0 to 4 294 967 Each GID is associated with an integer [0 to 4 294 967
295]295] System assigns UID (avoid duplicates)System assigns UID (avoid duplicates) Use Use idid to display your user and group information to display your user and group information
uid=300(uskudarli) gid=300(uskudarli) groups=300(uskudarli),3(sys),4(adm)
Users and GroupsUsers and Groups Groups define functional areas/responsibilitiesGroups define functional areas/responsibilities They allow a collection of users to share filesThey allow a collection of users to share files A user can belong to multiple groupsA user can belong to multiple groups You can see what groups you belong to using the You can see what groups you belong to using the groupsgroups command: command:
uskudarli sys adm
Typical Group SetupTypical Group Setup
sys bin adm staff
Using the new userUsing the new user Now logoff using the Now logoff using the exitexit command command login as the new userlogin as the new user
ubuntu login: uskudarliPassword:[uskudarli@ubuntu uskudarli]$
You need help?You need help? The Linux equivalent of HELP is The Linux equivalent of HELP is manman
(manual)(manual) Use Use man -k <keyword>man -k <keyword> : all commands with : all commands with
that keywordthat keyword Use Use man <command>man <command> : help for the command : help for the command Output is presented a page at a time. Output is presented a page at a time.
typetype b b to scroll backward to scroll backward ff or a or a spacespace to scroll forward to scroll forward qq to quit to quit
Unix StructureUnix Structure
More detailMore detail
User commands Shell
File Systems Kernel Device Drivers
Hardware
User commands includes executable programs and scripts
The shell interprets user commands.
The kernel manages the hardware resources for the
rest of the system.
Shells Shells
Several ‘shells’ available: Several ‘shells’ available: ksh,csh, bsh...ksh,csh, bsh... Linux Linux ==>==> bashbash Shell ScriptsShell Scripts
File SystemFile System
Hierarchical file systemHierarchical file system Data files are stored in Data files are stored in
directories (folders)directories (folders) Directories are nestedDirectories are nested
Root of hierarchyRoot of hierarchy / /
Directories
User home directories
Data Files
root
directory
Naming FilesNaming Files Files are named byFiles are named by
naming each directorynaming each directory starting at the rootstarting at the root
pathnamepathname
/home/amy/try
/etc/passwd
The Current DirectoryThe Current Directory
current (present) working current (present) working directorydirectory
pwdpwd returns value of returns value of current working current working directorydirectory
Current working directory
doc/letter./doc/letter/home/neale/doc/letter
Special File NamesSpecial File Names
Some file names are special:Some file names are special: // The root directory The root directory .. The current directory The current directory
.. .. The parent directoryThe parent directory ~~ My home directory My home directory
Examples:Examples: ./a ./a same as same as aa ../uskudarli/.bash../uskudarli/.bash go up one level search for go up one level search for
directory directory uskudarliuskudarli for for .bashrc.bashrc
Special FilesSpecial Files /home/home - all users’ home directories are stored here - all users’ home directories are stored here /bin/bin, , /usr/bin/usr/bin - system commands - system commands /sbin/sbin, , /usr/sbin/usr/sbin - commands used by sysadmins - commands used by sysadmins /etc/etc - all sorts of configuration files - all sorts of configuration files /var/var - logs, spool directories etc. - logs, spool directories etc. /dev/dev - device files - device files /proc/proc - special system files - special system files
Linux Command BasicsLinux Command Basics To execute a command, type its name and To execute a command, type its name and
arguments at the command linearguments at the command line
ls -l /etc
Command nameOptions(flags)
Arguments
Standard FilesStandard Files standard input standard input
input to commandinput to command default is the default is the terminalterminal
standard output standard output output of commandoutput of command default is the default is the terminalterminal
standard error standard error output for error messages output for error messages default is the terminaldefault is the terminal
standard input/outputstandard input/output
Redirecting OutputRedirecting Output The output of a command is sent to a fileThe output of a command is sent to a file
ls -l > out1“>” redirects to output file
Input RedirectionInput Redirection Contents of file1 become input to wc Contents of file1 become input to wc
wc < in1“<” redirects the file as input to wc
Connecting commands with Connecting commands with PipesPipes
The output of one command becomes the input The output of one command becomes the input of another command:of another command:
ps aux | grep ubuntu | wc -l
output of ps is sent to grep
grep searches for “ubuntu”
counts the lines and outputs to console
“|” separate processes
pipes – more examplespipes – more examples
ps -ef | grep group1ps -ef | grep group1(this shows all processes related with userid group1)(this shows all processes related with userid group1)
ps -ef | grep group1 | wc -lps -ef | grep group1 | wc -l
this will count the number of processes related with group1this will count the number of processes related with group1
Command OptionsCommand Options Command options allow you to control a Command options allow you to control a
command to a certain degreecommand to a certain degree Conventions:Conventions:
Usually being with a single dash and are a single Usually being with a single dash and are a single letter (“letter (“-l-l”)”)
Sometimes have double dashes followed by a Sometimes have double dashes followed by a keyword (“keyword (“--help--help”)”)
Sometimes follow no pattern at allSometimes follow no pattern at all
Common CommandsCommon Commands pwdpwd - print (display) the working directory - print (display) the working directory cdcd <<dir>dir> - change the current working directory to - change the current working directory to
dirdir lsls - list the files in the current working directory - list the files in the current working directory lsls -l -l - list the files in the current working directory - list the files in the current working directory
in long formatin long format
File CommandsFile Commands cpcp <fromfile> <tofile><fromfile> <tofile>
Copy from the <fromfile> to the <tofile> Copy from the <fromfile> to the <tofile> mvmv <fromfile> <tofile><fromfile> <tofile>
Move/rename the <fromfile> to the <tofile>Move/rename the <fromfile> to the <tofile> rmrm <file><file>
Remove the file named <file>Remove the file named <file> mkdirmkdir <newdir><newdir>
Make a new directory called <newdir>Make a new directory called <newdir> rmdirrmdir <dir><dir>
Remove an (empty) directoryRemove an (empty) directory
More CommandsMore Commands
whowho List who is currently logged on to the systemList who is currently logged on to the system
whoamiwhoami Report what user you are logged on asReport what user you are logged on as
psps List your processes on the systemList your processes on the system
ps auxps aux List all the processes on the systemList all the processes on the system
echo echo “Something to say…”“Something to say…” Echo a string to the terminalEcho a string to the terminal
More CommandsMore Commands
aliasalias - customize commands: - customize commands: alias del=rmalias del=rm alias grep=”grep -i”alias grep=”grep -i”
More CommandsMore Commands awkawk - - a file processing language a file processing language chownchown - - sets the user ID (UID) to owner for sets the user ID (UID) to owner for
the files and directories named by pathname the files and directories named by pathname arguments. arguments.
chown -R apache:httpd /usr/local/apache
More CommandsMore Commands diffdiff - determines the minimal set of - determines the minimal set of
changes needed to convert file1 to file2changes needed to convert file1 to file2 diff file1 file2diff file1 file2
findfind - - Searches a given file hierarchy specified Searches a given file hierarchy specified by path, finding files that match the criteria by path, finding files that match the criteria given by expressiongiven by expression
More CommandsMore Commands grepgrep -- Searches files for one or more pattern Searches files for one or more pattern
arguments. It does plain string, basic regular arguments. It does plain string, basic regular expression, and extended regular expression expression, and extended regular expression searchingsearching
find examplefind example find ./ -name "*.c" | xargs grep -i "fork"
find files with an extension “c” pass files to xargs•takes the names •constructs a command line of the form:
•grep -i fork <file1>…<filen>
•This command will search the files for the “fork”. •The “-i” flag makes the search case insensitive.
More CommandsMore Commands killkill - sends a signal to a process or process - sends a signal to a process or process
groupgroup You can only kill your own processes unless you You can only kill your own processes unless you
are rootare root
UID PID PPID C STIME TTY TIME CMDroot 6005 6692 2 14:34 ttyp0 00:00:00 sleep 10hroot 6716 6692 0 14:34 ttyp0 00:00:00 ps -ef[root@ubuntu log]# kill 6005[1]+ Terminated sleep 10h
More CommandsMore Commands
makemake – – manage projects containing a set of interdependent manage projects containing a set of interdependent
files files makemake keeps all such files up to date with one keeps all such files up to date with one
another: If one file changes, another: If one file changes, makemake updates all the updates all the other files that depend on the changed fileother files that depend on the changed file
More CommandsMore Commands
sedsed - - applies a set of editing subcommands applies a set of editing subcommands contained in a script to each argument input filecontained in a script to each argument input file
find ./ -name "*.c,v" | sed ’s/,v//g’ | xargs grep "PATH"
This finds all files in the current and subsequent directories with an extension of c,v. sed then strips the ,v off the results of the find command. xargs then uses the results of sed and builds a grep command which searches for occurrences of the word PATH in the C source files.
processesprocessesps -efps -ef
shows the processes that are running for this sessionshows the processes that are running for this session
More CommandsMore Commands tartar - manipulates archives - manipulates archives
An archive file that contains the complete contents An archive file that contains the complete contents of a set of other filesof a set of other files
preserves the directory hierarchy that contained the preserves the directory hierarchy that contained the original files. original files.
tar -tzf imap-4.7.tar.gzimap-4.7/imap-4.7/src/imap-4.7/src/c-client/imap-4.7/src/c-client/env.himap-4.7/src/c-client/fs.h
ShellsShells An interface between the Linux system and the An interface between the Linux system and the
useruser Used to call commands and programsUsed to call commands and programs An interpreterAn interpreter Powerful programming languagePowerful programming language Many available (bsh; ksh; csh; bash; tcsh)Many available (bsh; ksh; csh; bash; tcsh)
Another definition of a ShellAnother definition of a Shell
A shell is any program that A shell is any program that takes input from the usertakes input from the user translates it into instructions that the OS translates it into instructions that the OS
understandsunderstands presents the OS output to the user. presents the OS output to the user.
Why Shell?Why Shell?
Shell is Not Integral Part of OS Shell is Not Integral Part of OS UNIX is among first to separate UNIX is among first to separate Compare to MS-DOS, Mac, Win95, VM/CMSCompare to MS-DOS, Mac, Win95, VM/CMS GUI is NOT RequiredGUI is NOT Required Default Shell Can Be Configured Default Shell Can Be Configured
chsh -s /bin/bash chsh -s /bin/bash /etc/passwd/etc/passwd
Helps To Customize EnvironmentHelps To Customize Environment
#!/bin/bash#!/bin/bashwhilewhiletruetruedodo cat somefile > /dev/nullcat somefile > /dev/null echo .echo .donedone
Shell ScriptsShell Scripts
Switching UsersSwitching Users susu <accountname><accountname>
switch user accounts. switch user accounts. prompted for a password. prompted for a password. When this command completes, you will be logged into the When this command completes, you will be logged into the
new account. new account. Type Type exitexit to return to the previous account to return to the previous account
susu Switch to the root user account. Switch to the root user account. Warning: Use only when neededWarning: Use only when needed Note: Note: The root user does not need to enter a password when switching The root user does not need to enter a password when switching
users. It may become any user desired.users. It may become any user desired.
Environment VariablesEnvironment Variables
global settings for a shell and other Linux global settings for a shell and other Linux programs. programs.
global shell variablesglobal shell variables Setting:Setting:
VAR=/home/uskudarli/docVAR=/home/uskudarli/doc export TERM=vt100export TERM=vt100 SYSTEMNAME=`uname -n`SYSTEMNAME=`uname -n`
Environment VariablesEnvironment Variables
Using Environment Variables:Using Environment Variables: echo $VARecho $VAR cd $VARcd $VAR cd $HOMEcd $HOME echo “You are running on $SYSTEMNAME”echo “You are running on $SYSTEMNAME”
Displaying - use the following commands:Displaying - use the following commands: set set (displays local and environment variables)(displays local and environment variables) exportexport
Vars can be retrieved by a script or a programVars can be retrieved by a script or a program
Some Important Environment Some Important Environment VariablesVariables
HOMEHOME Your home directory Your home directory ~~
TERMTERM The type of terminal you are running The type of terminal you are running
PWDPWD Current working directoryCurrent working directory
PATHPATH List of directories to search for commandsList of directories to search for commands
PATH Environment VariablePATH Environment Variable
List of paths, where commands are searchedList of paths, where commands are searched PATH is a list of directory pathnames separated by PATH is a list of directory pathnames separated by
colons. colons. Example:Example: PATH=/bin:/usr/bin:/usr/X11R6/bin:/uPATH=/bin:/usr/bin:/usr/X11R6/bin:/usr/local/bin:/home/scully/binsr/local/bin:/home/scully/bin
If a command does not contain a slash, the shell tries If a command does not contain a slash, the shell tries finding the command in each directory in PATH. The finding the command in each directory in PATH. The first match is the command that will runfirst match is the command that will run
PATH Environment VariablePATH Environment Variable
Usually set in Usually set in /etc/profile /etc/profile May be modified in May be modified in ~/.profile~/.profile
File PermissionsFile Permissions Every file Every file
Is owned by someone Is owned by someone Belongs to a group Belongs to a group Has certain access permissions for owner, group, Has certain access permissions for owner, group,
and othersand others Default permissions determined by Default permissions determined by umaskumask
File PermissionsFile Permissions Every user:Every user:
Has a uid (login name)Has a uid (login name) gid (login group) gid (login group) membership of a "groups" list:membership of a "groups" list:
The The uiduid is who you are (name and number) is who you are (name and number) The The gidgid is your initial “login group” is your initial “login group” The The groups listgroups list is the file groups you can access via group is the file groups you can access via group
permissionspermissions
File PermissionsFile Permissions Linux provides three kinds of permissions:Linux provides three kinds of permissions:
ReadRead - read the file or list the directory - read the file or list the directory WriteWrite - write to the file or create new files to the - write to the file or create new files to the
directorydirectory ExecuteExecute - execute the file or lookup a specific file - execute the file or lookup a specific file
within a directorywithin a directory
File PermissionsFile Permissions The long version of a file listing (The long version of a file listing (ls -lls -l) ) displays the file permissions:displays the file permissions:
-rwxrwxr-x 1 uskudarli uskudarli 5224 Sep 30 03:22 hello-rw-rw-r-- 1 uskudarli uskudarli 221 Sep 30 03:59 hello.c-rw-rw-r-- 1 uskudarli uskudarli 1514 Sep 30 03:59 hello.sdrwxrwxr-x 7 uskudarli staff 1024 Sep 31 14:52 posixuft
Permissions
Owner
Group
Interpreting File PermissionsInterpreting File Permissions
-rwxrwxrwxOther permissions
Group permissions
Owner permissions
Directory flag (d=directory; l=link)
Changing File PermissionsChanging File Permissions Use the Use the chmodchmod command to change file command to change file
permissionspermissions The permissions are encoded as an octal numberThe permissions are encoded as an octal number
chmod 755 file # Owner=rwx Group=r-x Other=r-xchmod 500 file2 # Owner=r-x Group=--- Other=---chmod 644 file3 # Owner=rw- Group=r-- Other=r--
chmod +x file # Add execute permission to file for allchmod o-r file # Remove read permission for otherschmod a+w file # Add write permission for everyone
Links?Links? Links are references to files (aliases)Links are references to files (aliases) Two forms:Two forms:
HardHard SymbolicSymbolic
Can point to files on different physical devicesCan point to files on different physical devices Delete of original leaves link Delete of original leaves link Delete of link leaves originalDelete of link leaves original Can be created for directoriesCan be created for directories
Create using Create using lnln command command
PermissionsPermissions
All directories are special filesAll directories are special files The read/write/execute scheme is usedThe read/write/execute scheme is used
EditorsEditors
People are fanatical about their editorPeople are fanatical about their editor Several choices available:Several choices available:
vivi Standard UNIX editorStandard UNIX editor xeditxedit X windows text editorX windows text editor emacsemacs Extensible, Customizable Self-Extensible, Customizable Self-
Documenting Display EditorDocumenting Display Editor picopico Simple display-oriented text editor Simple display-oriented text editor
Linux Device HandlingLinux Device Handling
Devices are the way linux talks to the worldDevices are the way linux talks to the world Devices are special files in the Devices are special files in the /dev/dev directory (try directory (try ls /devls /dev))/dev/ttyx TTY devices/dev/hdb IDE hard drive/dev/hdb1 Partition 1 on the IDE hard drive/dev/mnda VM Minidisk /dev/dda Channel Attached DASD/dev/dda1 Partition 1 on DASD/dev/null The null device (“hole”)/dev/zero An endless stream of zeroes/dev/mouse Link to mouse (not /390)
PermissionsPermissions
All directories are special filesAll directories are special files The read/write/execute scheme is usedThe read/write/execute scheme is used
Devices and DriversDevices and Drivers Each Each /dev/dev file has a major and minor number file has a major and minor number
Major defines the device typeMajor defines the device type Minor defines device within that typeMinor defines device within that type Drivers register a device typeDrivers register a device type
brw-r--r-- 1 root root 64, 0 Jun 1 1999 /dev/mndacrw-r--r-- 1 root root 5, 0 Jan 5 09:18 /dev/tty
Major no. Minor no.Device Type: b - blockc - character
Special Files - /procSpecial Files - /proc Information about internal Linux processes are Information about internal Linux processes are
accessible to users via the accessible to users via the /proc/proc file system (in file system (in memory)memory)
/proc/cpuinfo CPU Information/proc/interrupts Interrupt usage/proc/version Kernel version/proc/modules Active modules
cat /proc/cpuinfovendor_id : IBM/S390# processors : 1bogomips per cpu: 86.83processor 0: version = FF, identification = 045226, machine = 9672
File SystemsFile Systems Linux supports many different typesLinux supports many different types Most commonly, ext2fsMost commonly, ext2fs
Filenames of 255 charactersFilenames of 255 characters File sizes up to 2GB File sizes up to 2GB Theoretical limit 4TBTheoretical limit 4TB
Derived from extfsDerived from extfs
File SystemsFile Systems mountmount
Mounts a file system froma device to the main file Mounts a file system froma device to the main file systemsystem
/etc/fstab/etc/fstab used to establish boot time used to establish boot time mountingmounting
Virtual File System (VFS)Virtual File System (VFS)
Logical file systemsLogical file systems compatibility with other O/S standards compatibility with other O/S standards portabilityportability VFS abstracts details of physical device and VFS abstracts details of physical device and
logical file system logical file system Processes access files using a common interface, Processes access files using a common interface,
without knowing what physical or logical system without knowing what physical or logical system of the fileof the file
Security GuidelinesSecurity Guidelines Take Care With Passwords Take Care With Passwords
Choose good passwords Choose good passwords Don't Use Real Words Don't Use Real Words Make Sure They Are Not Easily Guessed Make Sure They Are Not Easily Guessed Use Combinations Of Upper and Lower Case, Use Combinations Of Upper and Lower Case,
Numbers, Punctuation Numbers, Punctuation
Security GuidelinesSecurity Guidelines Restrict Superuser Access Restrict Superuser Access
Restrict where root can log in from Restrict where root can log in from /etc/securetty/etc/securetty restricts root access to devices listed restricts root access to devices listed
Use wheel group to restrict who can Use wheel group to restrict who can susu to root to root Put users who can Put users who can susu to root in wheel group to root in wheel group
in in /etc/group/etc/group file. file.
Security - Important FilesSecurity - Important Files
/etc/passwd - password file/etc/shpasswd - shadow password file/etc/group -lists groups and users contained in groups/etc/services - lists network services and their ports/etc/ftpusers - contains list of accounts that cannot use ftp/etc/hosts.equiv - generic list of remote users~/.rhosts - list of remote users for a specific account/etc/hosts - host definition list/etc/hosts.lpd - hosts who can use remote printing/etc/hosts.allow - lists services that remote users are allowed to use/etc/hosts.deny - lists services tthat remote users are not allowed to use/etc/nologin - no login message that also disables logins/etc/securetty - lists legal terminals for root to login from/etc/exports - lists locations that can be remotely accessed via NFS/etc/syslog.conf - configures the syslog facility/etc/inetd.conf - configures inetd
Three important tips:Three important tips:
ArrowsArrows Retrieve commands using Retrieve commands using ⇑⇑ or or ⇓⇓
ctrl-Cctrl-C stop programs at oncestop programs at once
cntl-Zcntl-Z execute process in backgroundexecute process in background
Additional ResourcesAdditional Resources UNIX Systems Administrator ResourcesUNIX Systems Administrator Resources
http://www.ugu.com/http://www.ugu.com/ Linux/390 Observations and Linux/390 Observations and NotesNotes
http://penguinvm.princeton.eduhttp://penguinvm.princeton.edu Introduction to LinuxIntroduction to Linux Linux Administration Made EasyLinux Administration Made Easy
http://www.linuxninja.com/linux-http://www.linuxninja.com/linux-admin/book1.htmladmin/book1.html
Additional ResourcesAdditional Resources http://http://www.linux.orgwww.linux.org http://www.tux.orghttp://www.tux.org http://www.li.orghttp://www.li.org www.linux.orgwww.linux.org www.be.itu.edu.tr/kaynak/kaynak/www.be.itu.edu.tr/kaynak/kaynak/ www.redhat.com www.redhat.com
More infoMore info
sunsite.bilkent.edu.tr sunsite.bilkent.edu.tr www.linuxfocus.org www.linuxfocus.org www.linas.org/Linux www.linas.org/Linux www.ext2.org www.ext2.org www.linuxhelp.org www.linuxhelp.org
www.linuxprogramming.org www.linuxprogramming.org www.linuxworld.com www.linuxworld.com www.linuxpowered.com www.linuxpowered.com www.linuxtoday.com www.linuxtoday.com www.linuxresources.com www.linuxresources.com www.kde.org www.kde.org www.caldera.com www.caldera.com www.debian.org www.debian.org www.gnome.org www.gnome.org portal.suse.com portal.suse.com www.kernel.org www.kernel.org www.linux.router.org www.linux.router.org