Tài liệu LPI-102 Junior Level Administration

Tài liệu Tài liệu LPI-102 Junior Level Administration: Version 2.0 Lưu hành nội bộ LPI-102 Junior Level Administration Exam: 117-102 INDEX Chapter 1 The Linux Documentation Chapter 2 Managing Users Chapter 3 Shells, Scripting, Programming and Compiling Chapter 4 Boot, Initialization, Shutdown and Runlevels Chapter 5 The Linux Kernel Chapter 6 System Logging and Automation Chapter 7 Maintain system Chapter 8 Printing Chapter 9 Networking Fundamentals Chapter 10 Networking Services, Part 1 Chapter 11 Networking Services, Part 2 Chapter 12 Distributed File System Chapter 13 Network Security 1Linux Junior Level Administration - LPI 102 1 2004, SaigonCTT All rights reservedLast updated: 26 December 2003 The Linux Documentation Chapter 1 22 Last updated: 26 December 2003 Objectives • Use and manage local system documentation • Find Linux documentation on the Internet • Notify users on system-related issues LPI Topics 1.108.1 Use and manage local system documentation This objective includes finding relevant man pages...

pdf441 trang | Chia sẻ: honghanh66 | Lượt xem: 851 | Lượt tải: 0download
Bạn đang xem trước 20 trang mẫu tài liệu Tài liệu LPI-102 Junior Level Administration, để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên
Version 2.0 Lưu hành nội bộ LPI-102 Junior Level Administration Exam: 117-102 INDEX Chapter 1 The Linux Documentation Chapter 2 Managing Users Chapter 3 Shells, Scripting, Programming and Compiling Chapter 4 Boot, Initialization, Shutdown and Runlevels Chapter 5 The Linux Kernel Chapter 6 System Logging and Automation Chapter 7 Maintain system Chapter 8 Printing Chapter 9 Networking Fundamentals Chapter 10 Networking Services, Part 1 Chapter 11 Networking Services, Part 2 Chapter 12 Distributed File System Chapter 13 Network Security 1Linux Junior Level Administration - LPI 102 1 2004, SaigonCTT All rights reservedLast updated: 26 December 2003 The Linux Documentation Chapter 1 22 Last updated: 26 December 2003 Objectives • Use and manage local system documentation • Find Linux documentation on the Internet • Notify users on system-related issues LPI Topics 1.108.1 Use and manage local system documentation This objective includes finding relevant man pages, searching man page sections, finding commands and man pages related to them, and configuring access to man sources and the man system. It also includes using system documentation stored in /usr/share/doc/ and determining what documentation to keep in /usr/share/doc/. 1.108.2 Find Linux documentation on the Internet This objective includes using Linux documentation at sources such as the Linux Documentation Project (LDP), vendor and third-party websites, newsgroups, newsgroup archives, and mailing lists. 1.108.5 Notify users on system-related issues This objective includes automating the communication process, e.g. through logon messages. 33 Last updated: 26 December 2003 Different sources of help • man, xman • info, xinfo • /usr/share/doc/howto • /usr/share/doc/packages Linux Documentation Project which is responsible for: –ManPages –FAQs –HOWTOs –Tutorials 44 Last updated: 26 December 2003 • You can get information about most commands. • Man pages contains: – Object name – Synopsis and description – List and definition of all options – Environment and parameters • Related commands are listed at the end of the man page. Man pages and the man command Man page structure: 1. NAME 2. SYNOPSIS 3. DESCRIPTION 4. OPTIONS 5. EXIT CODE 6. CONFORMING TO 7. FILES 8. BUGS 9. SEE ALSO 10.AUTHOR 55 Last updated: 26 December 2003 Man pages and the man command – Used to look up certain commands and their use. – Man pages are divided in 9 sections man [options] [section] command_name 66 Last updated: 26 December 2003 Kernel routines9 Administration commands8 Macro packages7 Games6 Configuration files and formats5 Devices (files in /dev)4 Library calls, e.g stdio3 System calls2 Information on executables1 man page sections To view a particular section of the man pages, include the section number with the man command and the term you are looking for: man Note: When no type is given, the type search sequence until one is found is: 1,8,2,3,4,5,6,7,9 77 Last updated: 26 December 2003 • Spacebar Move forward one screen • Return Move forward one line • b Move back one screen • f Move forward one screen • q Quit the man command • /string Find forward • ?string Find back • n Find the next occurrence of string • h Help more Scrolling in Man pages Example: $ man 8 mount –displays the mount administration command $ man 2 mount –displays the mount system call man -a command –Display all the man page for the command . They are displayed one after the other, each one being terminated with 'q'. 88 Last updated: 26 December 2003 Files, programs and variables • /usr/bin/mandb – Program to create or update the man page caches. • MANPATH – Contains the PATHs where mandb looks while indexing pages. • /usr/bin/manpath – Program to display the paths searched for man pages. • /etc/manpath.config – mandb configuration file. • man can be searched in multiple directories by setting the MANPATH variable. MANPATH=/usr/man:/usr/X11R6/man:/usr/share/man •If the MANPATH is not set then man will assume /usr/man (Redhat: /usr/share/man) 99 Last updated: 26 December 2003 Files, programs and variables • /usr/share/man/index.(bt|db|dir|pag) – A traditional global 'whatis' index database cache. • /var/cache/man/index.(bt|db|dir|pag) – Alternate/FHS compliant global 'whatis' index database cache. 10 10 Last updated: 26 December 2003 Locations of man pages • /usr/man/* – Old location of man pages • /usr/share/man/* – A global manual page hierarchy. • /usr/local/man/* – Extra man pages for user commands • /usr/local/share/man/* – Extra man pages for user commands • /usr/X11R6/man/* – X11 Applications man pages 11 11 Last updated: 26 December 2003 Locations of man pages • /usr/X11R6/man/* – X11 Applications man pages • /opt/gnome/man/* – Gnome Desktop applications man pages • /opt/kde3/man/* – KDE Desktop applications man pages • /usr/openwin/man/* – Openwindows Desktop applications man pages • /var/cache/man/* – catman pages files and index of manpages Note: –Most man pages in these directories are classified in subdirectories by their respective type (sections) as in ..../man1/ ..../man2/ –The man pages are normally in compressed (.gz) GROFF source format. They are decompressed automatically before the page is displayed. –The cat pages are preformatted text man pages including the formatting characters. They are normally saved in .../cat1 .../cat2 .... directories. 12 12 Last updated: 26 December 2003 PAGER variable • The man pages use a display mode as less by default. • Change display mode by change the PAGER environment variable value. • Example: – less mode: export PAGER=/usr/bin/less – more mode export PAGER=/usr/bin/more 13 13 Last updated: 26 December 2003 apropos command – Searches short descriptions for the topic in the keywords – Same result as: man -k topic • Example $ apropos password chage (1) - change user password expiry information chpasswd (8) - update password file in batch crypt (3) - password and data encryption endpwent [getpwent] (3) - get password file entry apropos topic This command searches whatis database to get result. So, you must create whatis database first. # makewhatis 14 14 Last updated: 26 December 2003 whatis command – Searches the man page keywords and presents the first short description of the command. – Same result as: man -f command • Example $ whatis password password: nothing appropriate $ whatis passwd passwd (1) - update a user's authentication tokens(s) passwd (5) - password file passwd [sslpasswd] (1ssl) - compute password hashes whatis command The exact command must be found otherwise nothing is displayed. It displays the single line description found in the manpage. It first searches in the man page index and then its own database if the man page index file is not found. You must create whatis database first. # makewhatis 15 15 Last updated: 26 December 2003 info Command – Info pages are supposed to have more information than the man pages. – Some individuals write a short description of their programs in the man pages and a longer one in the info pages. • Example $ info passwd • Read passwd command info. $ info 5 passwd • View passwd file info. info [section] [command] Not all man pages are being maintained and are therefore out of date, so info yields more current information. Some topics treated in info are not discussed in man at all, info also uses hypertext links, so it is a more powerful utility. Navigation through info pages: helph last text displayedl search * finds directoryd previous nodep next node n up node u end of nodee begin of nodeb move backward, Page-Up-Key move forward, Page-Down-Key 16 16 Last updated: 26 December 2003 Find Linux documentation on the Internet • – Linux Documentation Project • The Linux Documentation Project web site. Contains Handbooks, Books, HOWTOs, FAQs and lots more. • – The official Linux web site with more Documentation and links to other Linux web sites. • – Google search engine for linux 17 17 Last updated: 26 December 2003 Find Linux documentation on the Internet • Newsgroups • Newsgroup Archives • Mailing lists Newsgroups comp.os.linux.advocacy General discussion about the advantages of using Linux vs. other OS. comp.os.linux.announce Commented Linux news comp.os.linux.answers Commented sending of Linux FAQ's. HOWTO's, and README's. comp.os.linux.apps General discussion about Linux Applications. comp.os.linux.development.apps Discussion about programming and porting applications for Linux. comp.os.linux.development.system Discussions about the Linux kernel, device drivers and loadable modules. comp.os.linux.hardware General discussion regarding Linux hardware compatibility. comp.os.linux.misc Different themes about Linux which are not found in other newsgroups. comp.os.linux.networking General discussions regarding networking and communications. comp.os.linux.setup General discussions regarding Linux installation and System Administration. 18 comp.os.linux.x Discussions about The X Window System under Linux. alt.os.linux General discussion regarding Linux. Newsgroup Archives Archives of all Newsgroups. Google has taken over this function. Mailing lists The following mailing lists are running off a central Majordomo server. To subscribe to one of these mailing list, send an email to majordomo@vger.kernel.org with the following as the mail text body: subscribe ListName ListName = One of the mailing lists below. The text in the subject area is ignored. linux-8086 linux-admin linux-alpha linux-apps linux-arm linux-bbs linux-c-programming linux-config linux-console linux-diald linux-doc linux-fido linux-fsf linux-ftp linux-gcc linux-gcc-digest linux-hams linux-hppa linux-ibcs2 linux-ipx linux-isdn linux-japanese linux-kernel linux-kernel linux-kernel-digest linux-kernel-patch linux-laptop linux-linuxss linux-lugnuts linux-mca linux-mips linux-msdos linux-msdos-digest linux-msdow-devel linux-net linux-new-lists linux-newbie linux-newbiew linux-nys linux-oasg linux-oi linux-opengl linux-pkg linux-ppp linux-pro linux-qag linux-raid linux-scsi linux-serial linux-seyon linux-smp linux-sound linux-standards linux-svgalib linux-tape linux-term linux-training@lists.iphil.net linux-userfs linux-word linux-x11 linux-x25 sparclinux ultralinux 19 19 Last updated: 26 December 2003 Notify users on system-related issues • /etc/issue – pre-login message and identification file • /etc/issue.net – pre-login message and identification file, use for remote user. • /etc/motd – message of the day. – The contents of /etc/motd are displayed after a successful login but just before it executes the login shell. Login Sequence When the system boots-up, right at the end of its default runlevel, init starts the program mingetty for each virtual console defined in /etc/inittab. Here is the sequence of events: –The mingetty (getty) process displays the contents of the file /etc/issue. –Then it displays the “HostName login:” prompt and waits for the user to enter a username. –When the username is entered and the user presses , mingetty replaces itself with the program login and login gets the username from mingetty and waits for the password from the user. login's configuration file /etc/login.defs describes the behavior of login. –If the file /etc/nologin exists, login will allow access only to root. Other users will be shown the contents of this file and their logins will be refused. –If this authentication succeeds, the login process then starts a shell (usually bash). –bash reads its configuration scripts (/etc/profile etc.) and displays the content of the file /etc/motd (message of the day), then displays its prompt. 20 Overall sequence: Escaped characters for /etc/issue Waits for password login---------------> Shows /etc/motdShows /etc/issue waits for user name and prompt bash------------->mingetty Kernel version (Buils Date) \v The word User(s) and the Elapsed time since last login for this user.\U Elapsed time since last login for this user\u Present time.\t Release number of the Kernel\r Domain name\o Hostname\n System Architecture (eg. i386)\m Name of the current TTY\l Operating System Name (eg. 'Linux' )\s Today's date\d Baudrate of terminal connection (only for serial terminal connection)\b 21 21 Last updated: 26 December 2003 Summary • Use and manage local system documentation • Find Linux documentation on the Internet • Notify users on system-related issues Key files, terms, and utilities include: MANPATH man apropos whatis /etc/issue /etc/issue.net /etc/motd 22 1Linux Junior Level Administration - LPI 102 1 2004, SaigonCTT All rights reservedLast updated: 26 December 2003 Managing Users Chapter 02 22 Last updated: 26 December 2003 Objectives • add, remove, suspend and change user accounts • add and remove groups • change user/group info in passwd/group databases • modify global and user profiles • set environment variables • maintain skel directories LPI-102 Topics: 1.111.1 Manage users and group accounts and related system files Description: Candidate should be able to add, remove, suspend and change user accounts. Tasks include to add and remove groups, to change user/group info in passwd/group databases. The objective also includes creating special purpose and limited accounts. 1.111.2 Tune the user environment and system environment variables Description: Candidate should be able to modify global and user profiles. This includes setting environment variables, maintaining skel directories for new user accounts and setting command search path with the proper directory. 33 Last updated: 26 December 2003 Part 1 Manage Users 44 Last updated: 26 December 2003 User Account • /etc/passwd – information of all users: Login name, User ID, Group ID, Descriptive name, Home directory, Login shell • /etc/shadow – stores parameters to control account access: user’s password hash and password aging information • /etc/group – information about user’s groups • /etc/gshadow – stores group’s password hash, 55 Last updated: 26 December 2003 /etc/passwd • Each line in this file correspond to a user 1. Login name 2. Password (or x if using a shadow file) 3. The UID 4. The GID 5. Text description for the user 6. The user’s home directory 7. The user’s shell name:password:UID:GID:comment:home directory:shell 7654321 1. Username, up to 8 characters. Case-sensitive, usually all lowercase 2. the password field. x = reference to /etc/shadow, empty = no password, * or ! = no login possible 3. Numeric user id. This is assigned by the ``adduser'' script. Unix uses this field, plus the following group field, to identify which files belong to the user. 4. Numeric group id. Red Hat uses group id's in a fairly unique manner for enhanced file security. Usually the group id will match the user id. 5. Full name of user. I'm not sure what the maximum length for this field is, but try to keep it reasonable (under 30 characters). 6. User's home directory. Usually /home/username (eg. /home/smithj). All user's personal files, web pages, mail forwarding, etc. will be stored here. 7. User's "shell account". Often set to “/bin/bash” to provide access to the bash shell (my personal favorite shell). # cat /etc/passwd 66 Last updated: 26 December 2003 /etc/passwd # cat /etc/passwd | grep root root:$1$K05gMbOv$b7ryoKGTd2hDrW2sT.h:0:0:Super User:/root:/bin/bash # cat /etc/passwd | grep root root:x:0:0:Super User:/root:/bin/bash # cat /etc/shadow | grep root root:$1$K05gMbOv$b7ryoKGTd2hDrW2sT.h::::::: Traditional Unix systems keep user account information, including one-way encrypted passwords, in a text file called “/etc/passwd”. As this file is used by many tools (such as “ls”) to display file ownerships, etc. by matching user id #'s with the user's names, the file needs to be world-readable. Consequentally, this can be somewhat of a security risk. Another method of storing account information, one that I always use, is with the shadow password format. As with the traditional method, this method stores account information in the /etc/passwd file in a compatible format. However, the password is stored as a single "x" character (ie. not actually stored in this file). A second file, called “/etc/shadow”, contains encrypted password as well as other information such as account or password expiration values, etc. The /etc/shadow file is readable only by the root account and is therefore less of a security risk. 77 Last updated: 26 December 2003 /etc/shadow A reserved field9 Absolute date, beyond which the account will be disabled8 Number of inactivity days allowed for this user7 Number of days before expiration that user will be warned6 Maximum number of days password is valid5 Minimum number of days between password changes4 Number of days since the last password change, from 1/1/703 Encrypted password. 2 User login name, mapped to /etc/passwd1 name:password:lastchange:min:max:warn:inactive:expire:flag 87 9654321 CommentsDescription# Reserved for future use9 empty = will never be disabledDays since Jan 1,1970 when account will be disabled 8 empty= never inactiveDays before account becomes inactive7 empty=no warningDays warning before expiration6 Normal is 10000 daysDays before change required5 0=always allowed to changeDays until change allowed4 never emptyDays since Jan 1, 1970 when password was last changed 3 empty = no password * = no login possible Encrypted password2 User login name1 88 Last updated: 26 December 2003 Create / Delete shadow – Convert passwd --> shadow – Convert shadow --> passwd /usr/sbin/pwconv /usr/sbin/pwunconv • pwconv command will remove passwords from /etc/passwd and store in the /etc/shadow • Password field in /etc/passwd is replaced by an ‘x’ • Process can be reversed with the pwunconv command 99 Last updated: 26 December 2003 – Create new user – Save user information to /etc/passwd and /etc/shadow • Options Make new user Secondary groups-G GID Specify login shell-s shell Skeleton directory-k skel_dir Make home directory-m Specify home directory-d directory Description of user-c comment Specify primary group-g GID Specify new user ID-u UID useradd [options] new_user •Several users pre-configured and assigned with UID less than 100: root, bin, daemon, sys, adm, lp, •Administration tools allocate UIDs automatically, greater than 100 in general Skeleton directory ( default /etc/skel )-k skel_dir List system Defaults-D Specify login shell ( default /bin/bash )-s shell Make home directory if it does not exist.-m Define home directory ( default /home/username )-d directory Description of user ( default: blank )-c comment A list of supplementary groups which the user is also a member of. Each group is separated from the next by a comma, with no intervening white space. -G GID Specify default (primary) group ( default other group )-g GID Specify new user ID (default: next available number)-u UID 10 10 Last updated: 26 December 2003 Make new user • Example # groupadd lpiusers # useradd -g lpiusers -d /home/lpi102 -m -c "LPI's Member" lpi102 # grep lpi102 /etc/passwd lpi102:x:504:556:LPI's Member:/home/lpi102:/bin/bash # Example: List system default # useradd -D GROUP=100 HOME=/home INACTIVE=-1 EXPIRE= SHELL=/bin/bash SKEL=/etc/skel 11 11 Last updated: 26 December 2003 File: login.defs – the mail spool directory • MAIL_DIR – password aging controls • PASS_MAX_DAYS, PASS_MIN_DAYS, PASS_MAX_LEN, PASS_WARN_AGE – max/min values for automatic UID selection in useradd • UID_MIN, UID_MAX – max/min values for automatic GID selection in groupadd • GID_MIN, GID_MAX – automatically create a home directory with useradd • CREATE_HOME /etc/login.defs # cat /etc/login.defs MAIL_DIR /var/spool/mail PASS_MAX_DAYS 99999 PASS_MIN_DAYS 0 PASS_MIN_LEN 5 PASS_WARN_AGE 7 UID_MIN 500 UID_MAX 60000 GID_MIN 500 GID_MAX 60000 CREATE_HOME yes # 12 12 Last updated: 26 December 2003 Directory: skel – Contains default files that will be copied to the home directory of newly created users: • .bashrc • .bash_profiles • ... /etc/skel/* # ls -la /etc/skel/ total 20 drwxr-xr-x 2 root root 4096 Sep 6 18:41 . drwxr-xr-x 33 root root 4096 Nov 3 10:47 .. -rw-r--r-- 1 root root 24 Feb 11 2003 .bash_logout -rw-r--r-- 1 root root 191 Feb 11 2003 .bash_profile -rw-r--r-- 1 root root 124 Feb 11 2003 .bashrc # 13 13 Last updated: 26 December 2003 Change Password – l Superuser command which locks account passwd • Example # passwd blobby New password: Re-enter new password: Password changed passwd [-l] username 14 14 Last updated: 26 December 2003 Modify user – Changing User Attributes • Options – d the users directory – g the users initial GID – l the user's login name – u the user's UID – s the default shell. • Notice these options are the same as for useradd usermod [options] username If you edit files manually, you risk corrupting file, resulting with users not being able to log in at all. Instead, use usermod utility 15 15 Last updated: 26 December 2003 Changing Group Membership • Example # usermod –g users –c “Henry Blake” henry # usermod –u 321 –s /bin/ksh majorh # usermod –e 2004-12-20 majorh Each user belongs to a primary group: usermod –g User can also belongs to secondary groups: usermod –G # grep figo /etc/passwd figo:x:416:400::/home/figo:/bin/bash # groupadd –g 600 realmadrid # usermod –g realmarid figo # grep realmadrid /etc/group realmadrid:x:600:figo 16 16 Last updated: 26 December 2003 Removing Users userdel [option] username – Remove user from system • Options – r This option will remove home directory When a user leaves, there are two main concerns: –Protect the system from unauthorized access via his/her account –Protect and manage his/her files, directories left on the system. The userdel command takes care of removing a user account. userdel can remove user’s home directory but does not user’s mail, crontab table, atd queues, 17 17 Last updated: 26 December 2003 Managing Groups • Group commands and files – /etc/group – /etc/gshadow – groupadd – groupmod – groupdel – gpasswd – id – groups Groups not only allow for a second level of access control but also allow the members in group to share files in secured environment. Every new user is assigned to an initial (or primary) group. Two conventions exist. –Traditionally this primary group is the same for all users and is called users with a group id (GID) of 100. Many Linux distributions adhere to this convention such as Suse and Debian. –The User Private Group scheme (UPG) was introduced by RedHat and changes this convention without changing the way in which UNIX groups work. With UPG each new user belongs to their own primary group. The group has the same name as the login-name (default), and the GID is in the 500 to 60000 range (same as UIDs). 18 18 Last updated: 26 December 2003 /etc/group – Contains a list of groups, each on a separate line. 1. Group name 2. The group password (or x if gshadow file exists) 3. The GID 4. A comma separated list of members • Example daemon:x:2:root,bin,daemon name:password:GID:MEMBERs 4321 The /etc/group is world-readable. Each line is a four field, colon delimited list including the following information: Group name –The name of the group. Used by various utility programs to identify the group. Group password –If set, this allows users who are not part of the group to join the group by using the newgrp command and typing the password stored here. If a lower case x is in this field, then shadow group passwords are being used. Group ID (GID) –The numerical equivalent of the group name. It is used by the system and applications when determining access privileges. Member list –A comma delimited list of users in the group. # cat /etc/group root:x:0:root bin:x:1:root,bin,daemon daemon:x:2:root,bin,daemon .... 19 19 Last updated: 26 December 2003 /etc/gshadow – Contains an encrypted password for each group. 1. Group name 2. The group password 3. Group Administrators 4. Group Members • Example general:!!:shelley:juan,bob name:password:GroupAdmins:MEMBERs 4321 The /etc/gshadow file is readable only by the root user, and contains an encrypted password for each group, as well as group membership and administrator information. Just as in the /etc/group file, each group's information is on a separate line. Each of these lines is a four field, colon delimited list including the following information: Group name –The name of the group. Used by various utility programs to identify the group. Encrypted password –The encrypted password for the group. If set, non-members of the group can join the group by typing the password for that group using the newgrp command. If the value is of this field ! then no user is allowed to access the group using the newgrp command. A value of !! is treated the same as a value of ! only it indicates that a password has never been set before. If the value is null, only group members can log into the group. Group administrators –Group members listed here (in a comma delimited list) can add or remove group members using the gpasswd command. Group members –Group members listed here (in a comma delimited list) are regular, non- administrative members of the group. 20 20 Last updated: 26 December 2003 Group commands – Add group to the system. • Option – g gid The numerical value of the group's ID. • Example # groupadd -g 501 lpiusers # cat /etc/group | grep –i lpiusers lpiusers:x:501: groupadd [option] groupname -g gid The numerical value of the group's ID. This value must be unique, unless the - o option is used. The value must be non-negative. The default is to use the smallest ID value greater than 500 and greater than every other group. Values between 0 and 499 are typically reserved for system accounts. 21 21 Last updated: 26 December 2003 Group commands – modify the parameters of group • Option – n NewName change the name of group to NewName – g gid The numerical value of the group's ID. • Example # groupmod –g 505 lpiusers # cat /etc/group | grep –i lpiusers lpiusers:x:505: groupmod [option] groupname 22 22 Last updated: 26 December 2003 Group commands – Delete group from the system. • Example # groupdel lpiusers # cat /etc/group | grep –i lpiusers # groupdel groupname 23 23 Last updated: 26 December 2003 Group commands – Change Group’s password • Example # groupadd lpiusers # gpasswd lpiusers Changing the password for group lpiusers New Password: Re-enter new password: # gpasswd groupname 24 24 Last updated: 26 December 2003 Create/Delete gshadow – creates the /etc/gshadow file – deletes the gshadow file /usr/sbin/grpconv /usr/sbin/grpunconv • grpconv command will remove passwords from /etc/group and store in the /etc/gshadow • Password field in /etc/group is replaced by an ‘x’ • Process can be reversed with the grpunconv command 25 25 Last updated: 26 December 2003 Group commands – List group ID – List groups • Example # id uid=0(root) gid=0(root) groups=0(root), 1(bin), 2(daemon), 3(sys), 4(adm), 10(wheel), 600(sales) # groups root bin daemon sys adm wheel sales id groups A user can belong to any number of groups. However at any one time (when creating a file for example) only one group is the effective group. The list of all groups a user belongs to is obtained with either the groups or id commands. 26 26 Last updated: 26 December 2003 – changes the number of days between password changes and the date of the last password change. • Options Account Security Warning days-W Expiration (YYYY-MM-DD or MM/DD/YY)-E Inactive lock-I Day last changed-d Maximum days-M Minimum days-m chage [options] # chage -E 4/3/2002 blobby # chage -l blobby Minimum: 0 Maximum: 99999 Warning: 7 Inactive: -1 Last Change: Feb 06, 2002 Password Expires: Never Password Inactive: NeverAccount Expires: Apr 03, 2002 # chage -l blobby Minimum: 0 Maximum: 99999 Warning: 7 Inactive: -1 Last Change: Feb 06, 2002 Password Expires: Never Password Inactive: Never Account Expires: Never 27 Solution for chage command: 1. Lock the account password until you are ready to remove it # chage –E 1999-01-01 figo 2. Save all file owned by the user somewhere outside the home directory # find / -user henry –print | cpio ov | gzip >/hold/henry # find / -user henry –type f –exec rm –f {} \; # find / -user henry –type d –depth –exec rmdir {}\; 3. Change access permission on saved files to root only # chown root /home/figo ; chmod 700 /home/figo 4. Consider crontab and at jobs setup by the user 5. Setup mail forwarding to send mail to a manager 28 28 Last updated: 26 December 2003 User and Group guidelines • Use passwd command to change the password # passwd current password : new password: retype new password: Choosing password: • Not use proper words or names • Use letters and digits • Include symbols: !, @, #, $, %, • Do not allow guest account to login to your system. When creating a password, it is a good idea to follow these guidelines: Do Not Do the Following: 1. Do Not Use Only Words or Numbers — You should never use only numbers or words in a password. – Some examples include the following: 8675309 juan hackme 2. Do Not Use Recognizable Words — Words such as proper names, dictionary words, or even terms from television shows or novels should be avoided, even if they are bookended with numbers. john1 DS-9 mentat123 3. Do Not Use Words in Foreign Languages — Password cracking programs often check against word lists that encompass dictionaries of many languages. Relying on foreign languages for secure passwords is of little use. 29 – Some examples include the following: cheguevara bienvenido1 1dumbKopf 4. Do Not Use Hacker Terminology — If you think you are elite because you use hacker terminology — also called l337 (LEET) speak — in your password, think again. Many word lists include LEET speak. – Some examples include the following: H4X0R 1337 5. Do Not Use Personal Information — Steer clear of personal information. If the attacker knows who you are, they will have an easier time figuring out your password if it includes information such as: • Your name • The names of pets • The names of family members • Any birth dates • Your phone number or zip code 6. Do Not Invert Recognizable Words — Good password checkers always reverse common words, so inverting a bad password does not make it any more secure. – Some examples include the following: R0X4H nauj 9-DS 7. Do Not Write Down Your Password — Never store your password on paper. It is much safer to memorize it. 8. Do Not Use the Same Password For All Machines — It is important that you make separate passwords for each machine. This way if one system is compromised, all of your machines will not be immediately at risk. 30 Do the Following: 1. Make the Password At Least Eight Characters Long — The longer the password is, the better. If you are using MD5 passwords, it should be 15 characters long or longer. With DES passwords, use the maximum length - eight characters. 2. Mix Upper and Lower Case Letters — Red Hat Linux is case sensitive, so mix cases to enhance the strength of the password. 3. Mix Letters and Numbers — Adding numbers to passwords, especially when added to the middle (not just at the beginning or the end), can enhance password strength. 4. Include Non-Alphanumeric Characters — Special characters such as &, $, and > can greatly improve the strength of a password. 5. Pick a Password You Can Remember — The best password in the world does you little good if you cannot remember it. So use acronyms or other mnemonic devices to aid in memorizing passwords. 31 31 Last updated: 26 December 2003 Part 2 User Environment 32 32 Last updated: 26 December 2003 /etc/profile $ cat /etc/profile if [ `id -u` = 0 ]; then pathmunge /sbin pathmunge /usr/sbin pathmunge /usr/local/sbin fi # No core files by default ulimit -S -c 0 > /dev/null 2>&1 USER="`id -un`" LOGNAME=$USER MAIL="/var/spool/mail/$USER" HOSTNAME=`/bin/hostname` HISTSIZE=1000 export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE INPUTRC /etc/profile Files and commands to be executed at login or startup time by the Bourne or C shells. These allow the system administrator to set global defaults for all users. /etc/profile.d Shells scripts to be executed upon login to the Bourne or C shells. These scripts are normally called from the /etc/profile file. 33 33 Last updated: 26 December 2003 Environment Files SYSTEM WIDE: /etc/profile /etc/bashrc USER 1 ~/.bash_profile ~/.bash_login ~/.profile ~/.bashrc ~/.bash_logout ~/.inputrc USER 1 ~/.bash_profile ~/.bash_login ~/.profile ~/.bashrc ~/.bash_logout ~/.inputrc USER 2 ~/.bash_profile ~/.bash_login ~/.profile ~/.bashrc ~/.bash_logout ~/.inputrc USER 2 ~/.bash_profile ~/.bash_login ~/.profile ~/.bashrc ~/.bash_logout ~/.inputrc USER 3 ~/.bash_profile ~/.bash_login ~/.profile ~/.bashrc ~/.bash_logout ~/.inputrc USER 3 ~/.bash_profile ~/.bash_login ~/.profile ~/.bashrc ~/.bash_logout ~/.inputrc 34 34 Last updated: 26 December 2003 Environment Files login /etc/profile ~/.bash_profile ~/.bash_profile ~/.bash_login ~/.bash_login ~/.profile ~/.bashrc ~/.bash_logout /etc/bashrc yes yes no no bash start logout 35 35 Last updated: 26 December 2003 Environment Variables commands • set – shows all variables (local and exported) • env – shows only exported variables • unset – used to remove variables 36 36 Last updated: 26 December 2003 • export – shows exported variables • export – make as exported (global) variables Environment Variables commands VAR=value VAR=?? parent child LOCAL export VAR=value VAR=value parent child GLOBAL -When you defile new variable as local variable (without export), any child processes can not use it. -Global variable (with export) allow child processes use it. 37 37 Last updated: 26 December 2003 Summary • Manage users and group accounts and related system files • Tune the user environment and system environment variables Key files, terms, and utilities include: chage gpasswd groupadd groupdel groupmod grpconv grpunconv passwd pwconv pwunconv useradd userdel usermod env export set unset /etc/passwd /etc/shadow /etc/group /etc/gshadow /etc/profile /etc/skel CommandsFiles 38 1Linux Junior Level Administration - LPI 102 1 2004, SaigonCTT All rights reservedLast updated: 26 December 2003 Shells, Scripting and Programing Chapter 03 22 Last updated: 26 December 2003 Objectives • Identify Linux shell environments • Write and configure BASH script using variables, flow controls interactive input, functions, arithmetic and arrays LPI Topics 1.109.1 Customize and use the shell environment Candidate should be able to customize shell environments to meet users' needs. This objective includes setting environment variables (e.g. PATH) at login or when spawning a new shell. It also includes writing bash functions for frequently used sequences of commands. 33 Last updated: 26 December 2003 Introduction • Shell is a interface between OS and user. It provides : – A facility for launching and managing commands and programs – An operating environment – A programming language – ... # cat test.sh #!/bin/bash cd /var/log grep “Error” *.log Shell script : –a text file that contains a list of commands, variables, comments, flow control structures, loops, functions, –All comments begin with # except #! 44 Last updated: 26 December 2003 Shell Configuration Files • Type of configuration files : – Global (system-wide) : apply to all users. – Local : apply to each user. • bash configuration files : – Global: /etc/profile – Local: • ~/.bash_profile • ~/.bash_login • ~/.profile Type of shell : –Bourne shell (sh) –Bourne Again shell (bash) –Korn shell (ksh) –C shell (csh,tcsh) –... A new shell is started when a programs is started; and it will have separate environments: parameters, variables, functions, aliases ... 55 Last updated: 26 December 2003 Shell Environment • Environment: variables, functions, aliases,... • Type of variables: local (shell variable), global (environment variable) • Commands – set : define a new variable – unset : undefine a variable – export: make a local variable becomes a global variable – set : list all local variables – env : list all global variables Default environment variables: –PS1, PS2 –HOME, PATH, PWD –LOGNAME –SHELL –PAGER, LPDEST, DISPLAY –... 66 Last updated: 26 December 2003 Redirecting Input and Output • Redirect input : use (<) or (<0) • Redirect output, overwrite : use (>) or (1>) ( Use set –o noclobber : prevent file overwriting ) # mailx admin@saigonctt.com < content # ls –l > list_file 77 Last updated: 26 December 2003 Redirecting Input and Output • Redirect output, append : use (>>) • Redirect error : use (2>) # ls –l >> list_file # ls –l > list_file 2>&1 88 Last updated: 26 December 2003 Pipe and Back ticks ` ` • Pipe ( | ) : command1 | command2 – Output of command1 becomes input of command2 • Back ticks (` `) or “$()” # ls –l |grep samba # which passwd /usr/bin/passwd # ls –l /usr/bin/passwd # ls –l `which passwd` 99 Last updated: 26 December 2003 Shell Scripts Variables • Naming : – not begin with a digit, usually in upper case letters • Assigning : not SPACES around “=“ VAR=value : assign value string to VAR VAR=`cmd` : the same VAR=$(cmd) , assign output of cmd to VAR # VAR1=`ls /var/log | wc –l` # echo $VAR1 65 10 10 Last updated: 26 December 2003 Shell Scripts Variables • Variable declaration: • Options: -i integer -r read-only -x export: variable retains value outside script declare –i vcount=1 declare –r vwellcome=‘Hello World’ $ declare = 11 11 Last updated: 26 December 2003 Shell Scripts Variables • Single quotation ' ' – Ignore all special characters • Double quotation " " – Ignore all special characters, except $ ' ' \ # VAR=“Hello World” # echo “$VAR” Hello World # echo ‘$VAR’ $VAR 12 12 Last updated: 26 December 2003 Variable Notation • Use ${VAR} # VAR1=“This is a String” ; echo $VAR1 This is a String # VAR2=“$VAR1xyz” ; echo $VAR2 Nothing #default # VAR3=“${VAR1}xyz” ; echo $VAR3 This is a Stringxyz # VAR4=‘${VAR1}xyz’ ; echo $VAR4 ${VAR1}xyz 13 13 Last updated: 26 December 2003 Passing Information to Script • On the command line, information can be passed to script through pre-set positional parameters – $0 The name of the script – $1-$9 Parameters are being passed to script – $* List all variables entered at command line – $# Number of parameters – $! PID of the most recent backgroud command – $$ PID of the current SHELL The shift command will shift the positional parameters one or more position from left to right $1 --> $2 $2 --> $3 14 14 Last updated: 26 December 2003 Return codes/Exit status • The variable $? contains the return code of the previous executed command or application. – 0 Success – ≠0 Failure • The exit n command will cause the script to quit and assign the value of n to $? variable 15 15 Last updated: 26 December 2003 Flow control • Loop : do something more than one time • Loop commands : for, while, until 16 16 Last updated: 26 December 2003 The for Loop • Syntax : for in do # list of commands to do done 17 17 Last updated: 26 December 2003 The for Loop Example • This script will rename all file .txt in current directory to .html #!/bin/bash for files in $(ls *.txt) do newname=“$(basename $file .txt).html” mv $file $newname done 18 18 Last updated: 26 December 2003 The while and until Loop • Syntax : while do # list of commands to do done until do # list of commands to do done 19 19 Last updated: 26 December 2003 The while loop Example • Code: • Output : 0 1 2 3 count=0 while [ $count –lt 4 ] do echo $count count=$((count+1)) done 20 20 Last updated: 26 December 2003 The until Loop Example • Code: • Output : 0 1 2 3 count=0 until [ $count –ge 4 ] do echo $count count=$((count+1)) done 21 21 Last updated: 26 December 2003 Tests and Conditions • Test command test FILE • Option: -d FILE : FILE exists and is directory -f FILE : FILE exists and is file -e FILE : FILE exists -x FILE : FILE is executable -r FILE : FILE is readable -w FILE : FILE is writable -O FILE : FILE is owned by your UID Example: bash exists and executable ? test –x /bin/bash Or [ -f /bin/bash ] 22 22 Last updated: 26 December 2003 Condition Operators Ex: -lt : < -gt : > -le : <= -ge : >= -eq : = -ne : != $VAR1 -eq $VAR2 : VAR1 = VAR2 23 23 Last updated: 26 December 2003 Tests and Conditions • Test : use “[ ]” around expression • If-then-else structure: if [ ] # include SPACEs then #commands to do if the exp1 is true elif [ ] then #commands to do if the exp2 is true else #commands to do if the exp1 and exp2 is NOT true fi Example: scriptx.sh #!/bin/bash declare name declare cmd echo –n “Enter name: “ ; read name cmd=$1 if [ “$1” = “Hello” ] then echo “Hello $name” elif [ “$cmd” = “Good-bye” ] then echo “Bye $name” else echo “Did not understand” done 24 24 Last updated: 26 December 2003 case Structure case expression in pattern1 ) action ;; pattern2 ) action ;; * ) default action esac Where: text) Condition Text D|d) Multiple values for conditions: | = or *) Default case ;; End of condition break 25 25 Last updated: 26 December 2003 case Test Example #!/bin/bash echo; echo "Hit a key, then hit return." read Keypress case "$Keypress" in [a-z] ) echo "Lowercase letter“ ;; [A-Z] ) echo "Uppercase letter“ ;; [0-9] ) echo "Digit“ ;; * ) echo "Punctuation, whitespace, or other“ ;; esac #!/bin/bash echo; echo "Hit a key, then hit return." read Keypress case "$Keypress" in [a-z] ) echo "Lowercase letter“ ;; [A-Z] ) echo "Uppercase letter“ ;; [0-9] ) echo "Digit“ ;; * ) echo "Punctuation, whitespace, or other“ ;; esac 26 26 Last updated: 26 December 2003 read Command • Allow to read values into variables • Syntax : – read VAR1 VAR2 • If there is more input than you are looking for, all the extras are put in the last variable. •We can input information into script when executing the script •Commands : read select 27 27 Last updated: 26 December 2003 read Command Example #!/bin/bash echo "Enter 2 number, I will add them" read VAR1 VAR2 echo "$VAR1 + $VAR2 = $(($VAR1+$VAR2))" 28 28 Last updated: 26 December 2003 select Command • It is great for creating menu • Syntax : select in do # commands done 29 29 Last updated: 26 December 2003 select Command #!/bin/bash echo select vday in "MON" "WED" "FRI" do echo echo "Select $vday." echo break #if no 'break' here, keeps looping forever. done 30 30 Last updated: 26 December 2003 Functions • Syntax : Or function function_name () { #commands } function_name () { #commands } –Functions can be called in main script by function’s name. –It inherits ALL parameters in the main script –We can change the return code of the function by using return n command 31 31 Last updated: 26 December 2003 Addition functions • seq x y : set of " from x to y " Ex: for vitem in $(seq 1 10) do #commands done • expr : execute Ex: echo ` expr 1 + 1 ` 32 32 Last updated: 26 December 2003 Deploy • Step 1 : – create script file (cat, vi, mc, ...), enter script codes. • Step 2 : – add execute permission mode to file ( chmod u+x file ) • Step 3 : – run it (add script directory to PATH environment or use absolute path) 33 33 Last updated: 26 December 2003 Summary • Identify Linux shell environments • Write and configure BASH script using variables • Flow controls • Interactive input, functions Key files, terms, and utilities include: ~/.bash_profile ~/.bash_login ~/.profile ~/.bashrc ~/.bash_logout ~/.inputrc function (Bash built-in command) export env set (Bash built-in command) unset (Bash built-in command) 34 1Linux Junior Level Administration - LPI 102 1 2004, SaigonCTT All rights reservedLast updated: 26 December 2003 Boot, Initialization Shutdown and Runlevels Chapter 4 22 Last updated: 26 December 2003 Objectives • giving commands to the boot loader. • giving options to the kernel at boot time. • checking the events in the log files. • changing to single user mode. • shutdown or rebooting the system. • alert users before switching runlevel. • setting the default runlevel. LPI topics: 1.106.1 Boot the system Candidates should be able to guide the system through the booting process. This includes giving commands to the boot loader and giving options to the kernel at boot time, and checking the events in the log files. 1.106.2 Change runlevels and shutdown or reboot system Candidates should be able to manage the runlevel of the system. This objective includes changing to single user mode, shutdown or rebooting the system. Candidates should be able to alert users before switching runlevel, and properly terminate processes. This objective also includes setting the default runlevel. 33 Last updated: 26 December 2003 Boot stages 1. BIOS Stage – BIOS checks the system (POST - Power On Self Test) 2. Bootloader Stage – The bootloader loads the second stage into memory 3. Kernel Stage – The Kernel is loaded in to memory 4. Init Stage – init load all services and user space tools and mounts all from /etc/fstab Stage 1: –POST •Check the system board •Check memory •Check system configuration •Starts the video operation •... –Check bootloader in MBR (Master Boot Record) Stage 2: –Lilo 1. Firmware loads the LILO bootsector and executes it. 2. LILO loads its map file 3. The User selects which kernel to boot 4. LILO loads the kernel 5. LILO executes the kernel 4–Grub GRUB is more advanced bootloader than LILO 1. Firmware loads the GRUB bootsector and executes it. 2. The code loaded using BIOS, with knowledge filesystem 3. GRUB puts up a menu of defined boot options Stage 3: –The RAM disk •load the initial ramdisk •load the kernel into memory –nash •is a very simple script interpreter - not shell •dedigned to run simple linuxrc scripts –Kernel stages •the kernel takes over for bootloader •the kernel and the initial RAM disk image are already into memory. Stage 4: –The final for the boot process is handled by /sbin/init –Runlevel Scripts •init call the rc script with an argument that tells it which is the target runlevel. 55 Last updated: 26 December 2003 Giving kernel options to the bootloader • The list of options supported by the current kernel can be found in /usr/src/linux/Documentation/kernel-parameters.txt • The kernel options used are always readable from the file /proc/cmdline • Example: options given to LILO bootloaders LILO boot: linux aha152x=0x300,10,7 • Means that the Adaptec SCSI adapter is at address 0x300 IRQ 10 and SCSI-ID 7 Before the kernel loads it is normally possible to give kernel options on the boot loader command line. The can be SCSI adapter addresses, root partition, VGA terminal mode, default runlevel, etc. 66 Last updated: 26 December 2003 Giving kernel options to the bootloader • Kernel options that must always be used can be entered in the bootloader's configuration file. • LILO append=vga=791 hdc=ide-scsi splash=verbose acpi=off • GRUB kernel (hd0,2)/boot/vmlinuz.2.4.20 root=/dev/hda3 vga=791 splash=verbose Note: Options are separated with a space but continuous within the option. 77 Last updated: 26 December 2003 /etc/modules.conf (or conf.modules) • Kernels can be of 2 types: – Monolithic: All device drivers are compiled into the kernel. – Modular: Some device drivers are compiled as loadable modules. • Module configuration file: – New name: /etc/modules.conf – Old name: /etc/conf.modules For modular kernels the modules can be loaded/unloaded manually or automatically. The parameters needed to define the addresses, irq, dma, etc. for a module, as well as their system alias names. 88 Last updated: 26 December 2003 Boot Log files • As the kernel boots it saves its log messages in an internal buffer which is readable with the command dmesg • most of the system messages including kernel messages are stored in – /var/log/messages • The command – tail -f /var/log/messages • allows you to read the last 10 lines of the log file, refreshing it once a second. 99 Last updated: 26 December 2003 LiLo configuration file • This file is read by the LiLo boot loader. $cat /etc/lilo.conf prompt timeout=50 default=linux boot=/dev/sda map=/boot/map image=/boot/vmlinuz-2.4.20-8 label=linux initrd=/boot/initrd-2.4.20-8.img read-only append="root=LABEL=/" The /etc/lilo.conf file contains options and kernel image information. Popular LILO directives are: The amount of time, in tenths of a second, that the system waits for user input. timeout Used following each image, this specifies the device that should be mounted as the / (root) directory. root The root filesystem should initially be mounted read-only.read-only Prompts the user for input (such as kernel parameters or runlevels) before booting. prompt Directory where the map file is located.map Provides a label, or name, for each image.label The file installed as the new boot sector.install Refers to a specific kernel file.image The name of the hard disk partition that contains the boot sector.boot 10 10 Last updated: 26 December 2003 Grub configuration file • This file is read by the Grub boot loader. • Location: – /boot/grub/grub.conf – /etc/grub.conf – /boot/grub/menu.lst $ cat /etc/grub.conf default=0 timeout=10 splashimage=(hd0,0)/grub/splash.xpm.gz title Red Hat Linux (2.4.20-8) root (hd0,0) kernel /vmlinuz-2.4.20-8 ro root=LABEL=/ initrd /initrd-2.4.20-8.img <= origin file <= soft link <= soft link Some explanations. default=0 and timeout=10 means that unless I say otherwise, Grub will load the first operating system (again counting from zero) - Fedora Core 2 . splashimage=(hd0,0)/grub/splash.xpm.gz is the full name of the pretty splash image that is placed behind the Grub menu. 11 11 Last updated: 26 December 2003 Runlevels Reboot6 Full multi-user and GUI mode (redhat)5 unused4 Full multi-user mode3 Multi-user mode (without Network)2 Single user mode1 Shutdown0 DescriptionRunlevel • The default runlevel is defined in /etc/inittab id:5:initdefault – Will start the system in runlevel 5 A runlevel is a software configuration of the system which starts a selected group of processes. Runlevels are identified by: 0 1 2 3 4 5 6 S and s S & s Scripts to run before entering runlevel 1 (single login). 12 12 Last updated: 26 December 2003 The /etc/init.d directory Directories containing symlinks to scripts in /etc/init.drc[0-6].d A script used to change runlevels.rc A script for local startup customizations, started automatically after the system is running. rc.local The startup script launched by init at boot time.rc.sysinit Names of the links are in the format [K|S][nn][init.d_name] –K and S prefixes mean kill and start, respectively. –The script names starting with S are run with the argument start, and the ones with K are run with the argument stop. –Upon entering a new runlevel: K scripts are run if their equivalent S scripts had been started in the previous runlevel, S scripts are run if they had not already been started in the previous runlevel. –Therefore on each change of runlevel, the rc script checks the scripts of the previous and new runlevels to determine which K or S scripts should be run. –nn is a sequence number controlling startup or shutdown order. –init.d_name is the name of the script being linked. 13 13 Last updated: 26 December 2003 Displaying the current runlevel – Find the current and previous system runlevel. • Example # runlevel runlevel N 3 • The command runlevel displays the Previous ('N' if None) and the current • The previous runlevel was None (After Booting) and present: 3 runlevel 14 14 Last updated: 26 December 2003 Changing the runlevel – Changes the current runlevel. – /sbin/telinit is linked to /sbin/init. • Example # init 6 • restart system. # init 1 • change to single mode. telinit The following arguments serve as directives to telinit: telinit (or init) can also tell the init process how long it should wait between sending processes the SIGTERM and SIGKILL signals when shutting down a runlevel service. The default is 5 seconds, but this can be changed with the -t sec option. re-execute itself (preserving the state). The /etc/inittab file is not re-examined. Run level should be one of Ss12345, otherwise request will be silently ignored. U or u switch to single user mode.S or s re-examine the /etc/inittab file.Q or q process only those /etc/inittab file entries having runlevel a,b or c. a,b,c switch to the specified run level.0,1,2,3,4,5,6 15 15 Last updated: 26 December 2003 /etc/inittab file format • Each line starting with '#' is a comment. • Each entry uses one line. • Each entry's syntax is as follows: id:runlevels:action:process Specifies the process (or command) to be executed.process Describes which action should be taken (see below).action Lists the runlevels for which the specified action should be taken. The runlevels field may contain multiple characters for different runlevels. For example,123 specifies that the process should be started in runlevels 1, 2, and 3. runlevels A unique sequence of 1-4 characters which identifies an entry in inittab. Note: For gettys or other login processes, the id field should be the tty suffix of the corresponding tty, e.g. 1 for tty1. Otherwise, the login accounting might not work correctly. id 16 Most common actions: See man inittab for more info on other actions like: sysinit, powerwait, powerfail, powerokwait, powerfailnow, resume, kbrequest, ondemand. The process will be executed when init receives the SIGINT signal. This means that someone on the system console has pressed the CTRL-ALT-DEL key combination. Typically one wants to execute some sort of shutdown either to get into single-user level or to reboot the machine. Often used to reboot the machine in many distributions. ctrlaltdel An initdefault entry specifies the default runlevel to use. If not specified, init will ask for a runlevel on the console. The process field is ignored. initdefault This does nothing.off The process will be executed during system boot, while init waits for its termination (e.g. /etc/rc). The runlevels field is ignored. bootwait The process will be executed during system boot. The runlevels field is ignored. boot The process will be executed once when the specified runlevel is entered.once The process will be started once when the specified runlevel is entered and init will wait for its termination. wait The process will be restarted whenever it terminates (e.g. getty).respawn 17 17 Last updated: 26 December 2003 Shutting down the system properly • Before the system is turned off, it needs: – shut down every current runlevel service properly; – unmount all filesystems • Shutdown – init 0 – shutdown -h now – halt – poweroff • Reboot – init 6 – shutdown -r now Reboot the system. If /etc/inittab is set accordingly , pressing will also reboot the system. shutdown -c –Cancels the already scheduled shutdown. Note: The reboot, poweroff and suspend commands are symbolic links to halt. 18 18 Last updated: 26 December 2003 shutdown command – bring the system down. • Options shutdown [options] time Delay time after killing process (before init)-t {Seconds} Reboots, does not halt-r Shuts down without calling init-n Sends warning / does not shutdown-k Halts system after shutdown-h This WILL run fsck on reboot-F Will not run fsck on the reboot-f Cancels a shutdown-c Time format: Command access rights: The file /etc/shutdown.allow may contain user names (one per line) who have permission to run the shutdown command. At the specified timehh:mm In 4 minutes4 In 2 minutes+2m Well...NOW!now 19 19 Last updated: 26 December 2003 Summary • giving commands to the boot loader. • giving options to the kernel at boot time. • checking the events in the log files. • changing to single user mode. • shutdown or rebooting the system. • alert users before switching runlevel. • setting the default runlevel. Key files, terms, and utilities include: /var/log/messages /etc/conf.modules or /etc/modules.conf dmesg LILO GRUB /etc/inittab shutdown init 20 1Linux Junior Level Administration - LPI 102 1 2004, SaigonCTT All rights reservedLast updated: 26 December 2003 The Linux Kernel Chapter 05 22 Last updated: 26 December 2003 Objectives • managing a kernel and kernel loadable modules • loading and unloading modules as appropriate • customizing the current kernel • configuration, building a new kernel • building kernel modules as appropriate. • installing the new kernel as well as any modules LPI Topics: 1.105.1 Manage/Query kernel and kernel modules at runtime Description: Candidates should be able to manage and/or query a kernel and kernel loadable modules. This objective includes using command-line utilities to get information about the currently running kernel and kernel modules. It also includes manually loading and unloading modules as appropriate. It also includes being able to determine when modules can be unloaded and what parameters a module accepts. Candidates should be able to configure the system to load modules by names other than their file name. 1.105.2 Reconfigure, build, and install a custom kernel and kernel modules Description: Candidates should be able to customize, build, and install a kernel and kernel loadable modules from source This objective includes customizing the current kernel configuration, building a new kernel, and building kernel modules as appropriate. It also includes installing the new kernel as well as any modules, and ensuring that the boot manager can locate the new kernel and associated files (generally located under /boot, see objective 1.102.2 for more details about boot manager configuration). 33 Last updated: 26 December 2003 The Linux Kernel • It’s loaded at initial bootup of Linux system, manages activities : I/O, memory, processes, network interface, • Kernel can be built with 2 basic options : – Device drivers can be built directly into the kernel binary itself – Device drivers can be built as external modules to the kernel Why would you want to build a new kernel ? (newer hardware, faster, more stable, ) 44 Last updated: 26 December 2003 Kernel Version Numbering • Kernel version numbers: 1. The major number 2. The minor number 3. The micro number (patch number) 4. The patch level , applied by kernel maintainers • Example 2.4.7-10 View kernel version by command : # uname -r 55 Last updated: 26 December 2003 Kernel Version Numbering ƒ Kernel version numbering is very structured : - The minor number is even = stable version - The minor number is odd = development ver. - A patch constitutes a more precise measurement of the kernel version. ƒ To find out what kernel you are running : # uname -r Notes: All patchs to the kernel are cumulative. You simply have to obtain and apply the latest patch for the kernel to be sure you have the most up-to-date patched support. There are many changes from 2.2 to 2.4 -Itanium and X86-64 AMD Hamer CPU support -Improve PnP/hot swappable device recognition -Journaling file systems : ext3, ReiserFS, JFS,.. - 66 Last updated: 26 December 2003 uname command – Get name and information about current kernel • Options – a Combine all the system information. – o Print the operating system name. – r Print the release number of the kernel. • Example # uname -a Linux lpilabs 2.4.20-8 #1 Thu Mar 13 17:54:28 EST 2003 i686 i686 i386 GNU/Linux uname [options] Some other option: –i Print the system's hardware platform. –m Print the name of the hardware the system is running on. –n Print the machine's hostname. –p Print the type of processor (not available on all versions). –v Print build information about the kernel. Example: $ uname -n lpilabs $ uname -p i686 $ uname -v #1 Thu Mar 13 17:54:28 EST 2003 $ uname -o GNU/Linux $ uname -r 2.4.20-8 $ uname -i i386 $ uname -m i686 77 Last updated: 26 December 2003 make command – Determines which pieces of a large program need to be recompiled and compile them. – Executes commands in Makefile to update programs or module components. make [targets] Ref: More about make command and Makefile in LPI-101 course. 88 Last updated: 26 December 2003 make command • [targets] config • Configure a new kernel line by line on text mode menuconfig • Configure a new kernel by text menu xconfig • Configure a new kernel by graphic menu (require X Windows) ==> All three methods will save the configuration file as /usr/src/linux/.config make menuconfig –Text based color menus, radiolists & dialogs. make xconfig –X windows based configuration tool. 99 Last updated: 26 December 2003 make menuconfig Interface 10 10 Last updated: 26 December 2003 make xconfig Interface 11 11 Last updated: 26 December 2003 make command • [targets] oldconfig • Configure a new kernel using an older .config file clean • delete *.o files dep • Create .depend file make oldconfig –Default all questions based on the contents of your existing ./.config file. –It is often easier to configure a new kernel using an older .config file by using the make oldconfig command. This will prompt the user only for new features in the kernel source tree (if the kernel is newer or has been patched). make clean –The make command gets instructions from the Makefile and will build what is needed. If some files are already present make will use them as is. In particular files with *.o extensions. To make sure that all the configuration options in .config are used to rebuild the files needed one has to run make clean. make dep –.depend file containing paths to header files present in the kernel source tree (/usr/src/linux/include) 12 12 Last updated: 26 December 2003 /usr/src/linux/.config • Verify : allow load modules # cat .config | grep -i module # Loadable module support CONFIG_MODULES=y • Verify : support ext3 # cat .config | grep -i ext3 CONFIG_EXT3_FS=m CONFIG_EXT3_INDEX=y CONFIG_EXT3_FS_XATTR=y CONFIG_EXT3_FS_XATTR_SHARING=y CONFIG_EXT3_FS_XATTR_USER=y CONFIG_EXT3_FS_POSIX_ACL=y 13 13 Last updated: 26 December 2003 make command • [targets] zlilo • Make a compressed vmlinuz image and update LILO. zImage • Make a simple compressed image bzImage • Build an image compressed with gzip. 14 14 Last updated: 26 December 2003 make command • [targets] modules • The modules are compiled with make modules. modules_install • Copy modules file to the /lib/modules/ directory. install • move the new kernel and its associated files into the correct directories. 15 15 Last updated: 26 December 2003 The Source Tree • Kernel source released as a tarball file Example: linux-2.4.31.tar.bz2 • Should NEVER extract to /usr/src/linux/ # tar xjvf linux-2.4.31.tar.bz2 –C /usr/src/ 16 16 Last updated: 26 December 2003 The Source Tree ƒ Subdirectories in the source tree : /usr/src/linux-2.4.31/ kernel lib mm modules net scripts Documentation arch drivers fs include init ipc ƒ This is the structure that most kernel sources will follow. 17 17 Last updated: 26 December 2003 The Modular Kernel – Store the modules for a particular kernel. – List of module dependencies – Is generated by the depmod command /lib/modules/ /lib/modules//modules.dep Many components of the Linux kernel may be compiled as modules which the kernel can dynamically load and remove as required. The best components to modularize are ones not required at boot time, for example peripheral devices and supplementary file systems. Kernel modules are controlled by utilities supplied by the modutils package: –lsmod –rmmod –insmod –modprobe –modinfo # ls /lib/modules/`uname -r` build modules.generic_string modules.parportmap modules.usbmap kernel modules.ieee1394map modules.pcimap modules.dep modules.isapnpmap modules.pnpbiosmap 18 18 Last updated: 26 December 2003 The Modular Kernel – Configuration file for loading kernel modules – Often contains a list of aliases • Example alias char-major-10-181 toshiba options toshiba tosh_fn=0x62 /etc/modules.conf or /etc/conf.modules /etc/modules.conf is consulted for module parameters (IRQ and IO ports) but most often contains a list of aliases. These aliases allow applications to refer to a device using a common name. For example the first ethernet device is always referred to as eth0 and not by the name of the particular driver. # cat /etc/modules.conf alias eth0 pcnet32 alias scsi_hostadapter BusLogic alias sound-slot-0 es1371 post-install sound-slot-0 /bin/aumix-minimal -f /etc/.aumixrc -L >/dev/null 2>&1 || : pre-remove sound-slot-0 /bin/aumix-minimal -f /etc/.aumixrc -S >/dev/null 2>&1 || : alias usb-controller usb-uhci 19 19 Last updated: 26 December 2003 The Modular Kernel – Shows information about all loaded modules – Handle dependency descriptions for loadable kernel modules depmod [module] lsmod The depmod and modprobe utilities are intended to make a Linux modular kernel manageable for all users, administrators and distribution maintainers. # lsmod Module Size Used by Not tainted autofs 13268 0 (autoclean) (unused) pcnet32 18240 1 mii 3976 0 [pcnet32] ipt_REJECT 3928 6 (autoclean) iptable_filter 2412 1 (autoclean) ip_tables 15096 2 [ipt_REJECT iptable_filter] keybdev 2944 0 (unused) mousedev 5492 0 (unused) hid 22148 0 (unused) input 5856 0 [keybdev mousedev hid] usb-uhci 26348 0 (unused) usbcore 78784 1 [hid usb-uhci] ext3 70784 2 jbd 51892 2 [ext3] BusLogic 100796 3 sd_mod 13452 6 scsi_mod 107128 2 [BusLogic sd_mod] 20 20 Last updated: 26 December 2003 The Modular Kernel – Installs a loadable module in the running kernel. – Load the module and any dependent modules listed in modules.dep modprobe [module] insmod [module] Options for modprobe: -a, --all Load all matching modules instead of stopping after the first successful loading. -c, --showconfig Show the currently used configuration. -C, --config config Use the file config instead of (the optional) /etc/modules.conf to specify the configuration. The environment variable MODULECONF can also be used to select (and override) a different configuration file from the default /etc/modules.conf (or /etc/conf.modules (deprecated)). 21 21 Last updated: 26 December 2003 The Modular Kernel – Display information about a kernel module • Options – a Display the module's author. – d Display the module's description. – n Display the module's filename. – p Display the typed parameters that a module may support. modinfo [module] Example: Get infomation from the network module driver. $ modinfo pcnet32 filename: /lib/modules/2.4.20-8/kernel/drivers/net/pcnet32.o description: "Driver for PCnet32 and PCnetPCI based ethercards" author: "Thomas Bogendoerfer" license: "GPL" parm: debug int, description "pcnet32 debug level (0-6)" parm: max_interrupt_work int, description "pcnet32 maximum events handled per interrupt" parm: rx_copybreak int, description "pcnet32 copy breakpoint for copy-only-tiny-frames" parm: tx_start_pt int, description "pcnet32 transmit start point (0-3)" parm: pcnet32vlb int, description "pcnet32 Vesa local bus (VLB) support (0/1)" parm: options int array (min = 1, max = 8), description "pcnet32 initial option setting(s) (0-15)" parm: full_duplex int array (min = 1, max = 8), description "pcnet32 full duplex setting(s) (1)" 22 22 Last updated: 26 December 2003 The Modular Kernel – Unloads loadable modules from the running kernel. • Options – a Remove all unused modules – e Save persistent data, do not unload module – r Remove stacks, starting at the named module – s Use syslog for error messages rmmod [module] Example: unloads the raid0 module. $ lsmod Module Size Used by Not tainted raid0 3880 0 (unused) autofs 13268 0 (autoclean) (unused) pcnet32 18240 1 mii 3976 0 [pcnet32] ........ $ rmmod raid0 $ 23 23 Last updated: 26 December 2003 General Procedure to build kernel Step 1: Configure kernel’s parameters and build it make config or make menuconfig or make xconfig make clean; make dep; make bzImage Step 2: Compile modules make modules Step 3: Install modules make modules_install 24 24 Last updated: 26 December 2003 General Procedure to build kernel Step 4: Copy new kernel to /boot cp arch/i386/boot/bzImage /boot/vmlinuz-2.4.19-16 Step 5: Copy Sytem.map to /boot cp Sytem.map /boot/System.map-2.4.19-16 Step 6: Copy .config to /boot cp .config /boot/config-2.4.19-16 Step 7: Make ramdisk mkinitrd /boot/initrd-2.4.19-16.img 2.4.19-16 25 25 Last updated: 26 December 2003 General Procedure to build kernel Step 8a: Using : lilo ƒ Add new entry to /etc/lilo.conf image=/boot/vmlinuz-2.4.19-16 label=linux initrd=/boot/initrd-2.4.19-16.img read-only append="hdc=ide-scsi root=LABEL=/" ƒ Execute /sbin/lilo –v -t Notes: You must be run “lilo –v” for update lilo map file. 26 26 Last updated: 26 December 2003 General Procedure to build kernel Step 8b: Using : grub ƒ Add new entry to /etc/grub.conf title Red Hat Linux (2.4.19-16) root (hd0,0) kernel /vmlinuz-2.4.19-16 ro root=LABEL=/ hdc=ide-scsi initrd /initrd-2.4.19-16.img 27 27 Last updated: 26 December 2003 Summary • managing a kernel and kernel loadable modules • loading and unloading modules as appropriate • customizing the current kernel • configuration, building a new kernel • building kernel modules as appropriate. • installing the new kernel as well as any modules Key files, terms, and utilities include: depmod insmod lsmod rmmod modinfo modprobe uname make make targets: config menuconfig xconfig oldconfig modules install modules_install depmod /lib/modules/kernel- version/modules.dep /etc/modules.conf & /etc/conf.modules /usr/src/linux/* /usr/src/linux/.config /lib/modules/kernel-version/* /boot/* 28 1Linux Junior Level Administration - LPI 102 1 2004, SaigonCTT All rights reservedLast updated: 26 December 2003 System Logging and Automation Chapter 06 22 Last updated: 26 December 2003 Objectives • System logging – syslogd – klogd • Automate tasks – cron – at – anacron LPI Topics: 1.111.3 Configure and use system log files to meet administrative and security needs This objective includes managing the type and level of information logged, manually scanning log files for notable activity, monitoring log files, arranging for automatic rotation and archiving of logs and tracking down problems noted in logs. 1.111.4 Automate system administration tasks by scheduling jobs to run in the future Candidate should be able to use cron or anacron to run jobs at regular intervals and to use at to run jobs at a specific time. Task include managing cron and at jobs and configuring user access to cron and at services. 33 Last updated: 26 December 2003 Introduction to System logging • One integral part of any UNIX system are the logging facilities. • The majority of logging in Linux is provided by two main programs: – syslogd : logging services to programs and applications. – klogd : logging capability to the Linux kernel. 44 Last updated: 26 December 2003 Introduction to System logging • klogd – Sends most messages to the syslogd facility – But will on occasion pop up messages at the console (i.e. kernel panics). • syslogd – Handles the task of processing most messages and sending them to the appropriate file or device. – Configuration file: /etc/syslog.conf By default most logging to files takes place in /var/log/ 55 Last updated: 26 December 2003 Rotating log files • A common way to keep logging information for a fixed period is “rotation”. • Example: rotation policy #!/bin/sh cd /var/log mv logfile.2 logfile.3 mv logfile.1 logfile.2 mv logfile logfile.1 cat /dev/null > logfile chmod 600 logfile You keep backup files that are one day old, two days old, and so on. Each day a script or utility program renames the files to push older data toward the end of the chain. One common problem is figuring out what to do with all of the log messages. If you do a lot of logging (particularly if everything is sent to a central server), you can fill up your filesystem faster than you think. The most obvious and direct solution is to remove them after a specific length of time or when they reach a particular size. As its name implies, the goal of the logrotate program is to "rotate" log files. This could be as simple as moving a log file to a different name and replacing the original with an empty file. On the example: every day logfile.7 is lost as logfile.6 overwrites it. 6Logrotate: manage log files: A logrotate configuration file consists of a series of specifications for groups of logfiles to be managed. # Example log rotation policy errors sa-book@admin.com rotate 5 weekly /var/log/messages{ postrotate /bin/kill –HUP ‘cat /var/run/syslogd.pid endscript } /var/log/samba/*.log{ notifempty copytruncate sharedscripts postrotate /bin/kill –HUP ‘cat /var/run/syslogd.pid endscript } 77 Last updated: 26 December 2003 Linux log files – Contains a record of users’ logins and logouts. Should be rotated . – Records only the time of last login for each user. No need to be rotated. /var/log/wtmp /var/log/lastlog For the most part, linux packages send their logging information to files in the /var/log directory. Some distribution logs are also stored in /var/adm Special log files /var/log/wtmp Contains a record of users’ logins and logouts, entries that indicate when the system was rebooted or shut down. Should be rotated. # who /var/log/wtmp /var/log/lastlog It records only the time of last login for each user. Is binary file, indexed by UID. No need to be rotated because its size stay constant unless new users log in. # lastlog checksecurity utility runs every day (from /etc/cron.daily/standard) to enumerate the systems complement of setuid programs( setuid.changes, setuid.today, setuid.yesterday). Download (debian): 88 Last updated: 26 December 2003 Configuring syslogd • The configuration file /etc/syslog.conf • Basic format is: mail.info /var/log/maillog • Within the selector – mail : the facility – info : the level of priority – /var/log/maillog : the action selector action 99 Last updated: 26 December 2003 Facilities • Supported facilities in Linux: News subsystemnews Mail subsystemmail Spooling subsystemlpr Linux kernelkern System server processesdaemon cron subsystemcron Login authentication authpriv Associated SubsystemSyslog Facility localN Locally-defined syslog facilities N runs from 0 to 7 10 10 Last updated: 26 December 2003 priorities Debugging messagesdebug7 Informational messagesinfo6 notifications, Normal but significant conditionsnotice5 Warning conditionswarning4 Error conditionserr3 Critical conditioncrit2 alerts, Immediate action requiredalert1 emergencies, System unusableemerg0 DescriptionKeywordLevel Unlike facilities, which have no relationship to each other, priorities are hierarchical. Possible priorities in Linux are (in increasing order of urgency): debug, info, notice, warning, err, crit, alert and emerg. As with facilities, the wildcards * and none. A priority may be preceded by either or both of the modifiers = and ! 11 11 Last updated: 26 December 2003 Example – All messages of severity "info" and above are logged, but none from the mail, cron or authentication. .info;mail.none;authpriv.none;cron.none /var/log/messages.info; ail.none;authpriv.none;cron.none /var/log/ essages Select all priorities except warning Mail.debug; mail.!=warning Select only prio. Info, notice and warningMail.info;mail.!err Select only messages at info priorityMail.=info Select mail-related mesg. Of info prio. And higherMail.info meaningselector 12 12 Last updated: 26 December 2003 action • In practice, most log messages are written to files. • You can send messages other places too. Writes the mesg. To all users who are logged in* Writes the mesg. To user’s screenuser1,user2, Writes the mesg. To the named pipe fifoname\fifoname Forward the mesg. To the host at ip address ipaddress@ipaddress Forward the msg. To syslogd on host name@hostname Writes the mesg. To file on the local machineFilename meaningAction In practice, most log messages are written to files. If you list the full path to a filename as a line's action in syslog.conf, messages that match that line will be appended to that file. (If the file doesn't exist, syslog will create it.) You can send messages other places too. An action can be a file, a named pipe, a device file, a remote host or a user's screen. 13 13 Last updated: 26 December 2003 Config file examples • Stand-alone machine on a small network. # emergencies: tell every one who is logged on *.emerge * # important messages *.warning; daemon, auth.info,user.non /var/log/messages # printer errors lpr.debug /var/log/lpd-errs The syslog config file can be customized for each host. Choose stable machine as your logging server, one that is well secured and does not have many logins. Some very large sites may want to add more levels to the logging hierarchy. Unfortunately syslog retains the name of the originating host for only one hop. If a host “client” sends some log entries to host “server”, which sends them on to host “master,” master will see the data coming from server, not from client. 14 14 Last updated: 26 December 2003 Config file examples • a client machine on a larger network # emergencies tell everyone who is logged on *.ernerg;user.none * # Forward important messages to the central logger *.warning; lpr,local.none @netloghost daemon,auth.info @netloghost #cardd logs through facility local1 – send to boulder local1.debug @boulder.colorado.edu # keeping printer errors local lpr.debug /var/log/lpd-errs # keeping kernel messages local kern.info /var/log/kern.log 15 Creating a central syslog server In this example, I will configure our Solaris server environment to send syslog information to a remote Red Hat Linux 8.0 server. Changes needed on the syslog server (Red Hat Linux 8.0): vi /etc/sysconfig/syslog Change: SYSLOGD_OPTIONS="-m 0" To: SYSLOGD_OPTIONS="-m 0 -r -x" This change to the syslog daemon enables logging from remote machines and disables DNS lookups on incoming syslog messages. Changes needed on the syslog clients (Sun Solaris): 1. vi /etc/syslog.conf Add the following lines: # Send a copy to remote loghost *.info @loghost auth.* @loghost Note: make sure that you do not have extra whitespace in the Solaris syslog.conf file. Separate the facility and severity from the location with either a single space or with tabs. 2. vi /etc/hosts Remove any reference to "loghost." By default, Solaris will configure each host to be its own loghost. 3. Send the syslogd process a SIGHUP signal (kill -HUP pid_of_syslogd). 16 16 Last updated: 26 December 2003 at Command – Execute commands at a specified time or run the commands on a batch queue. – Reads commands from stdin or file (with –f option) and executes them using user’shell. at [options] Example: Run ~/mysqcript at 11h:30’ # at 11:30 at> ~/myscript at> job 1 at 2005-11-04 11:40 # The ^D ( ctrl-d ) : sending the end-of-file character to terminate the at command. Ctrl+d 17 17 Last updated: 26 December 2003 Listing and Deleting at Jobs – List all jobs. – Removes job_id at –l atq at –d job_id atrm job_id Example # atq 14 2003-10-31 12:00 a root # atrm 14 # atq 18 18 Last updated: 26 December 2003 crontab • crontab is located in three places: /var/spool/cron • contains user's crontabs • based on username /etc/cron.d • typically used by software installations /etc/crontab • maintained by system administrator cron's uses –Remove junk files from the system. –Reload mail aliases –Reset / Rotate log files –Synchronize databases –Checking network resources 19 19 Last updated: 26 December 2003 how cron works • Cron reads all its config files into memory then sleeps. • Every minute cron wakes – checks for updates to its config files – reloads updated files – executes any tasks scheduled for that minute. • Output of cron is emailed to the owner of the crontab 20 20 Last updated: 26 December 2003 crontab fields – minute [0-59] – hour [0-23] – day [1-31] – month [1-12] – weekday [0-6 ] (0=Sunday) min hr day month wday [usr] cmd $ cat /etc/crontab # run-parts 01 * * * * root run-parts /etc/cron.hourly 02 4 * * * root run-parts /etc/cron.daily 22 4 * * 0 root run-parts /etc/cron.weekly 42 4 1 * * root run-parts /etc/cron.monthly 21 21 Last updated: 26 December 2003 crontab format • Comment lines start with # • Fields are separated by whitespace – whitespace is taken literally in the command field • The command should not be quoted 22 22 Last updated: 26 December 2003 crontab format Treats for any value between 9 and 17. So if placed in day of month this would be days 9 through 17. Or if put in hours it would be between 9 and 5. 9-17 Treated as an OR, so if placed in the hours, this could mean at 2, 4, or 6 o-clock. 2,4,6 Is treated as ever 5 minutes, hours, days, or months. Replacing the 5 with another numerical value will change this option. */5 Is treated as a wild card. Meaning any possible value. * ExplanationOptions Example: Each of the above columns can be in one of the following formats (these examples are for the minute column): 30 Run command at 30 minutes past the hour. 0-59/10 Run command once every 10 minutes, for the entire hour. 15-30 Run command once every minute, from 15 to 30 minutes past the hour. 0,10,50 Run command at 0 minutes past the hour, 10 minutes past the hour, and 50 minutes past the hour. * un command once every minute. 23 23 Last updated: 26 December 2003 crontab command • Maintain crontab files for individual users • Options – e : Edit the current cron table – l : lists the contents of the user's crontab – r : removes the user's crontab – u : specifies a username (root only) • Each user has a personal list of commands kept in the crontab file, stored in /var/spool/cron/ directory. 24 24 Last updated: 26 December 2003 Examples • To execute myprogram once per day at 6:15 a.m , use this crontab entry: 15 6 * * * myprogram • To execute at 6:15 and 18:15 on the 1st and 15th of the month, use: 15 6,18 1,15 * * myprogram 25 25 Last updated: 26 December 2003 System cron table crontab Users denied use of croncron.deny Users allowed to use croncron.allow Users denied use of at (only used if no at.allow) at.deny Users allowed to use at at.allow Administering at and crontab • Control and configuration files are kept in /etc 26 26 Last updated: 26 December 2003 Administering at and crontab • /var/spool/cron – All crontab are stored in the cron spool directory • /var/spool/at – All at jobs are stored in the cron spool directory • Do not edit the files in the spool directories. – Use the at and crontab utilities to make changes • Use tail or tail –f to read logfile. 27 27 Last updated: 26 December 2003 logrotate command – Rotates, compresses, and mails system logs. – Use /etc/logrotate.conf – After modify the logrotate.conf, run logrotate – f to take affect. logrotate [logrotate_config_file] logrotate is designed to ease administration of systems that generate large numbers of log files. It allows automatic rotation, compression, removal, and mailing of log files. Each log file may be handled daily, weekly, monthly, or when it grows too large. Normally, logrotate is run as a daily cron job. It will not modify a log multiple times in one day unless the criterion for that log is based on the log’s size and logrotate is being run multiple times each day, or unless the -f or -force option is used. Sample Contents of /etc/logrotate.conf # rotate log files weekly #weekly # rotate log files daily daily # keep 4 weeks worth of backlogs #rotate 4 # create new (empty) log files after rotating old ones create 28 28 Last updated: 26 December 2003 anacron • anacron is a task scheduler similar to cron; • except that it does not require the system to run continuously. – It can be used to run the daily, weekly, and monthly jobs usually run by cron. • To use the anacron service, you must have: – the anacron RPM package installed – the anacron service must be running. 29 29 Last updated: 26 December 2003 anacrontab format • Anacron tasks are listed in the configuration file /etc/anacrontab. – period frequency (in days) to execute the command – delay delay time in minutes – job-identifier description of the task. – command command to execute period delay job-identifier command 30 30 Last updated: 26 December 2003 How anacron works ? • Anacron executes the command specified in the command field after waiting the number of minutes specified in the delay field. • After the task is completed, Anacron records the date in a timestamp file in the /var/spool/anacron directory. For each tasks, Anacron determines if the task has been executed within the period specified in the period field of the configuration file. If it has not been executed within the given period, Anacron executes the command specified in the command field after waiting the number of minutes specified in the delay field. After the task is completed, Anacron records the date in a timestamp file in the /var/spool/anacron directory. Only the date is used (not the time), and the value of the job-identifier is used as the filename for the timestamp file. Environment variables such as SHELL and PATH can be defined at the top of /etc/anacrontab as with the cron configuration file. 31 31 Last updated: 26 December 2003 anacrontab Example $ cat /etc/anacrontab # /etc/anacrontab: configuration file for anacron # See anacron(8) and anacrontab(5) for details. SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/bin 1 65 cron.daily run-parts /etc/cron.daily 7 70 cron.weekly run-parts /etc/cron.weekly 30 75 cron.monthly run-parts /etc/cron.monthly 32 32 Last updated: 26 December 2003 Summary • syslogd can be configured for both local and remote logging. • In the syslog.conf file, every rule consists these two fields: – selector field – action field • The three major process scheduling utilities: – at: executes a process once at a specified time – cron: executes a process repeatedly at specified intervals – anacron: like cron, but can schedule processes with within smaller time intervals than what cron allows Key files, terms, and utilities include: /etc/syslog.conf /var/log/* /etc/anacrontab /etc/at.deny /etc/at.allow /etc/crontab /etc/cron.allow /etc/cron.deny /var/spool/cron/* at atq atrm crontab logrotate tail -f 1Linux Junior Level Administration - LPI 102 1 2004, SaigonCTT All rights reservedLast updated: 26 December 2003 Maintain System Chapter 07 22 Last updated: 26 December 2003 Objectives • Setting the system date and time • Setting the BIOS clock to the correct time in UTC • Configuring the correct timezone for the system • Configuring the system to correct clock drift to match NTP clock. • Dumping a raw device to a file or vice versa • Performing partial and manual backups LPI Topics: 1.111.5 Maintain an effective data backup strategy Tasks include dumping a raw device to a file or vice versa, performing partial and manual backups, verifying the integrity of backup files and partially or fully restoring backups. 1.111.6 Maintain system time Tasks include setting the system date and time, setting the BIOS clock to the correct time in UTC, configuring the correct timezone for the system and configuring the system to correct clock drift to match NTP clock. 33 Last updated: 26 December 2003 Time clocks under Linux • Linux uses two clocks: – Hardware Clock: • RTC, RealTimeClock, CMOS Clock, BIOS Clock. – Software Clock: • System Clock. Runs via the system timer interrupt. Hardware Clock: – Runs independent of the Operating System and runs even when the computer is turned OFF, as long as the CMOS battery lasts. Software Clock: –Counts the number of seconds since 1st. Jan. 1970. Is the main clock under Linux. At boot time it reads the hardware clock and continues alone from there. 44 Last updated: 26 December 2003 Clock control programs • Under Linux 2 main programs are used to control the 2 clocks. – Controls the Hardware Clock – Controls the System Clock hwclock date 55 Last updated: 26 December 2003 Time settings and zones • There are 2 standard ways to set the clock. – Local time • Time at this geographic location – UTC • Universal Co-ordinate Time. Normal way of setting the time from which a time zone offset is given to calculate the Local Time. UTC is Coordinated Universal Time, GMT is Greenwich Mean Time. Greenwich (pronounced 'grenn-itch' ) is a town, now part of the south eastern urban sprawl of London, on the south bank of the River Thames in the London Borough of Greenwich. 66 Last updated: 26 December 2003 Setting the time in Linux • The procedure is relatively simple: 1. Set the Hardware clock to UTC via the BIOS setup. 2. Set the environment variable TZ to the proper time zone: 3. To tell Linux that our Hardware clock and system clock are set to UTC run: tzselect hwclock --utc --hctosys Alternative step 2: Use the program tzconfig which will set a symbolic link in the form of: ln -s /usr/share/zoneinfo/Europe/Berlin /etc/localtime $ tzselect Please identify a location so that time zone rules can be set correctly. Please select a continent or ocean. 1) Africa 5) Asia #? 5 Please select a country. 15) Indonesia 32) Nepal 49) Vietnam #? 49 The following information has been given: Vietnam Therefore TZ='Asia/Saigon' will be used. Local time is now: Wed Sep 28 10:58:46 ICT 2005. Universal Time is now: Wed Sep 28 03:58:46 UTC 2005. Is the above information OK? 1) Yes 2) No #? 1 77 Last updated: 26 December 2003 hwclock – This program is used to display or set the Hardware clock. • Options --set • Set the Hardware Clock to the time given by the --date option. --systohc • Set the Hardware Clock to the current System Time. --utc • Indicates that the Hardware Clock is kept in Universal Coordinated Time. hwclock [option] Options: --show Read the Hardware Clock and print the time to Standard Output. The time shown is always in local time, even if you keep your Hardware Clock in Coordinated Universal Time (UTC). --hctosys Set the System Time from the Hardware Clock. Also set the kernel's timezone value to the local timezone as indicated by the TZ environment variable and/or /usr/share/zoneinfo. This is a good option to use in one of the system startup scripts. --adjust Add or subtract time from the Hardware Clock to account for systemic drift since the last time the clock was set or adjusted. --localtime Indicates that the Hardware Clock is kept in Local Time. It is your choice whether to keep your clock in UTC or local time, but nothing in the clock tells which you've chosen. So this option is how you give that information to hwclock. 88 Last updated: 26 December 2003 date – This program is used to show or set the System time. • Options: – +text_and_metacodes • Allows control of the display of the current time /and/or date. • Example: # date "+It is now %H Hours and %M Minutes" It is now 14 Hours and 33 Minutes date [options] Interpreted sequences are: day of year (001..366)%j hour (01..12)%I hour (00..23)%H same as %b%h the 4-digit year corresponding to the %V week number%G the 2-digit year corresponding to the %V week number%g same as %Y-%m-%d%F day of month, blank padded ( 1..31)%e date (mm/dd/yy)%D day of month (01..31)%d century (year divided by 100 and truncated to an integer) [00-99]%C locale's date and time (Sat Nov 04 12:02:33 EST 1989)%c locale's full month name, variable length (January..December)%B locale's abbreviated month name (Jan..Dec)%b locale's full weekday name, variable length (Sunday..Saturday)%A locale's abbreviated weekday name (Sun..Sat)%a a literal %%% 9By default, date pads numeric fields with zeroes. GNU date recognizes the following modifiers between `%' and a numeric directive. ‘-’ (hyphen) do not pad the field ‘_’ (underscore) pad the field with spaces Time Parameters MMDDhhmm Set the System time to a specific value MMDDhhmmYYYY.[ss] Set the System time to a specific extended value. Note: In the file /etc/adjtime the correction factor can be saved to keep the clock as accurate as possible. time zone (e.g., EDT), or nothing if no time zone is determinable%Z RFC-822 style numeric timezone (-0500) (a nonstandard extension)%z year (1970...)%Y last two digits of year (00..99)%y locale's time representation (%H:%M:%S)%X locale's date representation (mm/dd/yy)%x week number of year with Monday as first day of week (00..53)%W day of week (0..6), 0 represents Sunday%w week number of year with Monday as first day of week (01..53)%V week number of year with Sunday as first day of week (00..53)%U day of week (1..7) , 1 represents Monday%u time, 24-hour (hh:mm:ss)%T a horizontal tab%t second (00..60), the 60 is necessary to accommodate a leap second%S seconds since `00:00:00 1970-01-01 UTC' (a GNU extension)%s time, 24-hour (hh:mm)%R time, 12-hour (hh:mm:ss [AP]M)%r locale's lower case am or pm indicator (blank in many locales)%P locale's upper case AM or PM indicator (blank in many locales)%p nanoseconds (000000000..999999999)%N a newline%n minute (00..59)%M month (01..12)%m hour ( 1..12)%l hour ( 0..23)%k 10 10 Last updated: 26 December 2003 Network Time Service • This service is used to set the client clocks to a very precise clock. • The service compensates for the delay introduced by TCP. • Protocol: – NTP • Daemon – ntpd Methods: 1. Cron job queries the time server using the ntpdate program. 2. Local daemon (ntpd or xntpd) runs on client and polls the time server. Note: This solution transforms the client to a Time Server. 11 11 Last updated: 26 December 2003 ntpdate – This program connects with a Time Server and sets the System time. – Normally it is regularly called from a cron job. • Example: 10 * * * * root /usr/sbin/ntpdate ntp3.fau.de ntpdate TimeServerName Note: A list of time servers on the Internet is located at: 12 12 Last updated: 26 December 2003 ntpd or xntpd • These daemons poll one or more Time Server(s) every 5 minutes and sets the system time. • Configuration file: /etc/ntp.conf • Example contents: server ntp3.fau.de driftfile /etc/ntp.drift This driftfile will store the local Hardware Clock drift and will be used at boot time to set local System Clock to a more accurate time till a connection to a Time Server is achieved. Note1: If the local time has drifted off more than 1000 seconds then a syslog message is generated and the clock must be set manually. Note 2: It is also possible to use both methods: ntpd and ntpdate at the same time. 13 13 Last updated: 26 December 2003 Types of backups • Full Backup – Backs up all files • Differential Backup • Incremental Backup Full backup Differential Backup Incremental Incremental Incremental Backs up all files, regardless of whether they were previously backed up or not. This method uses the most media space. In this case it is recommended to use compression like gzip or other methods to reduce the media space needed. 14 14 Last updated: 26 December 2003 Differential Backup • Saves only files that have been modified or created since the last Full Backup. • Advantages: – Only the full backup and the last good differential backup are needed to restore the whole of the data. • Disadvantages: – Takes longer to make than incremental backups and needs larger media. Notes: Normally a Full backup is made and then regular differential Backups are performed. 15 15 Last updated: 26 December 2003 Incremental Backup • Each backup is an increment since the most recent backup (Full, Differential or previous Incremental). • Advantages: – Shorter to make than the differential backups and needs smaller media size. • Disadvantages: – All of the incremental backups, up to the last known good one, and the full backup are needed for restoring. – If one of the incremental backups has some media fault, the entire backup may be unreliable. 16 16 Last updated: 26 December 2003 Restoring data • With differential backups: 1. Read the full backup 2. Read last good differential backup. • With incremental backups: 1. Read the full Backup 2. Read sequentially each incremental backup up to the last good one. With differential backups: –The Full backup and the last good differential backup is needed. With incremental backups: –The Full backup and ALL of the incremental backup are needed. 17 17 Last updated: 26 December 2003 Backup media devices files May be an ATAPI Zip or other removable disk/dev/hdx First floppy disk drive/dev/fd0 First floppy-controller tape drive/dev/ft0 First SCSI Tape Drive/dev/st0 To create backups, external media devices are needed. On slide show some common ones used under Linux. 18 18 Last updated: 26 December 2003 Basic backup programs – Recursively creates archives of files and directories including file properties. • Basic Mode options – c Create a new archive. – t List the content of the archive – x Extract files from the archive. tar Basic mode options f ta

Các file đính kèm theo tài liệu này:

  • pdflpi102_student_guide_v2_0_8493.pdf
Tài liệu liên quan