LPI-Learning-Material-102-500-en-244-374.pdf

Full Transcript

LPIC-1 (102) (Version 5.0) | Topic 107: Administrative Tasks $ cat /etc/timezone America/Sao_Paulo As stated by the output of tzselect, the environment variable TZ defines the time zone for the shell session, whatever the system’s default time zone is. Adding the line TZ='America/Sao_Paulo'; e...

LPIC-1 (102) (Version 5.0) | Topic 107: Administrative Tasks $ cat /etc/timezone America/Sao_Paulo As stated by the output of tzselect, the environment variable TZ defines the time zone for the shell session, whatever the system’s default time zone is. Adding the line TZ='America/Sao_Paulo'; export TZ to the file ~/.profile will make America/Sao_Paulo the time zone for the user’s future sessions. The TZ variable can also be temporarily modified during the current session, in order to display the time in a different time zone: $ env TZ='Africa/Cairo' date Mon Oct 21 15:45:21 EET 2019 In the example, command env will run the given command in a new sub-shell session with the same environment variables of the current session, except for the variable TZ, modified by the argument TZ='Africa/Cairo'. Daylight Savings Time Many regions adopt daylight savings time for part of the year — when clocks are typically adjusted by an hour — that could lead a misconfigured system to report the wrong time during that season of the year. The /etc/localtime file contains the data used by the operating system to adjust its clock accordingly. Standard Linux systems have files for all time zones in the directory /usr/share/zoneinfo/, so /etc/localtime is just a symbolic link to the actual data file inside that directory. The files in /usr/share/zoneinfo/ are organized by the name of the corresponding time zone, so the data file for the America/Sao_Paulo time zone will be /usr/share/zoneinfo/America/Sao_Paulo As the definitions for the daylight savings time may change, it is important to keep the files in /usr/share/zoneinfo/ up to date. The upgrade command of the package management tool provided by the distribution should update them every time a new version is available. Language and Character Encoding Linux systems can work with a wide variety of languages and non-western character encodings, definitions known as locales. The most basic locale configuration is the definition of the environment variable LANG, from which most shell programs identify the language to use. 234 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 107.3 Localisation and internationalisation The content of the LANG variable follows the format ab_CD, where ab is the language code and CD is the region code. The language code should follow the ISO-639 standard and the region code should follow the ISO-3166 standard. A system configured to use Brazilian Portuguese, for example, should have the LANG variable defined to pt_BR.UTF-8: $ echo $LANG pt_BR.UTF-8 As seen in the sample output, the LANG variable also holds the character encoding intended for the system. ASCII, short for American Standard Code for Information Interchange, was the first widely used character encoding standard for electronic communication. However, since ASCII has a very limited range of available numerical values and it was based on the English alphabet, it does not contain characters used by other languages or an extended set of non-alphabetical symbols. The UTF-8 encoding is a Unicode Standard for the ordinary western characters, plus many other non- conventional symbols. As stated by the Unicode Consortium, the maintainer of the Unicode Standard, it should be adopted by default to ensure compatibility between computer platforms: The Unicode Standard provides a unique number for every character, no matter what platform, device, application or language. It has been adopted by all modern software providers and now allows data to be transported through many different platforms, devices and applications without corruption. Support of Unicode forms the foundation for the representation of languages and symbols in all major operating systems, search engines, browsers, laptops, and smart phones — plus the Internet and World Wide Web (URLs, HTML, XML, CSS, JSON, etc.). (…) the Unicode Standard and the availability of tools supporting it are among the most significant recent global software technology trends. — The Unicode Consortium, What is Unicode? Some systems may still use ISO defined standards — like the ISO-8859-1 standard — for the encoding of non-ASCII characters. However, such character encoding standards should be deprecated in favor of Unicode encodings standards. Nevertheless, all major operating systems tend to adopt the Unicode standard by default. System wide locale settings are configured in the file /etc/locale.conf. Variable LANG and other locale related variables are assigned in this file like an ordinary shell variable, for example: $ cat /etc/locale.conf LANG=pt_BR.UTF-8 Users can use a custom locale configuration by redefining the LANG environment variable. It can Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 235 LPIC-1 (102) (Version 5.0) | Topic 107: Administrative Tasks be done for the current session only or for future sessions, by adding the new definition to the user’s Bash profile in ~/.bash_profile or ~/.profile. Until the user logs in, however, the default system locale will still be used by user independent programs, like the display manager’s login screen. The command localectl, available on systems employing systemd as the system TIP manager, can also be used to query and change the system locale. For example: localectl set-locale LANG=en_US.UTF-8. In addition to the LANG variable, other environment variables have an affect on specific locale aspects, like which currency symbol to use or the correct thousand separator for numbers: LC_COLLATE Sets the alphabetical ordering. One of its purposes is to define the order files and directories are listed. LC_CTYPE Sets how the system will treat certain sets of characters. It defines, for example, which characters to consider as uppercase or lowercase. LC_MESSAGES Sets the language to display program messages (mostly GNU programs). LC_MONETARY Sets the money unit and currency format. LC_NUMERIC Sets the numerical format for non-monetary values. Its main purpose is to define the thousand and decimal separators. LC_TIME Sets the time and date format. LC_PAPER Sets the standard paper size. LC_ALL Overrides all other variables, including LANG. The locale command will show all defined variables in the current locale configuration: 236 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 107.3 Localisation and internationalisation $ locale LANG=pt_BR.UTF-8 LC_CTYPE="pt_BR.UTF-8" LC_NUMERIC=pt_BR.UTF-8 LC_TIME=pt_BR.UTF-8 LC_COLLATE="pt_BR.UTF-8" LC_MONETARY=pt_BR.UTF-8 LC_MESSAGES="pt_BR.UTF-8" LC_PAPER=pt_BR.UTF-8 LC_NAME=pt_BR.UTF-8 LC_ADDRESS=pt_BR.UTF-8 LC_TELEPHONE=pt_BR.UTF-8 LC_MEASUREMENT=pt_BR.UTF-8 LC_IDENTIFICATION=pt_BR.UTF-8 LC_ALL= The only undefined variable is LC_ALL, which can be used to temporarily override all the other locale settings. The following example shows how the date command — running in a system configured to pt_BR.UTF-8 locale — will modify its output to comply with the new LC_ALL variable: $ date seg out 21 10:45:21 -03 2019 $ env LC_ALL=en_US.UTF-8 date Mon Oct 21 10:45:21 -03 2019 The modification of the LC_ALL variable made both abbreviations for the day of the week and month name to be shown in American English (en_US). It is not mandatory, however, to set the same locale for all variables. It is possible, for example, to have the language defined to pt_BR and the numerical format (LC_NUMERIC) set to the American standard. Some localisation settings change how programs deal with alphabetical ordering and number formats. Whilst conventional programs are usually prepared to correctly choose a common locale for such situations, scripts can behave unexpectedly when trying to correctly alphabetically order a list of items, for example. For this reason, it is recommended to set the environment variable LANG to the common C locale, as in LANG=C, so the script produces unambiguous results, regardless the localisation definitions used in the system where it is executed. The C locale only conducts a simple bytewise comparison, so it will also perform better than the others. Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 237 LPIC-1 (102) (Version 5.0) | Topic 107: Administrative Tasks Encoding Conversion Text may appear with unintelligible characters when displayed on a system with a character encoding configuration other than the system where the text was created. The command iconv can be used to solve this issue, by converting the file from its original character encoding to the desired one. For example, to convert a file named original.txt from the ISO-8859-1 encoding to the file named converted.txt using UTF-8 encoding, the following command can be used: $ iconv -f ISO-8859-1 -t UTF-8 original.txt > converted.txt The option -f ISO-8859-1 (or --from-code=ISO-8859-1) sets the encoding of the original file and option -t UTF-8 (or --to-code=UTF-8) sets the encoding for the converted file. All encoding supported by command iconv are listed with command iconv -l or iconv --list. Instead of using the output redirection, like in the example, option -o converted.txt or --output converted.txt could also be used. 238 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 107.3 Localisation and internationalisation Guided Exercises 1. Based on the following output of the command date, what is the time zone of the system in GMT notation? $ date Mon Oct 21 18:45:21 +05 2019 2. To what file should the symbolic link /etc/localtime point to in order to make Europe/Brussels the system’s default local time? 3. Characters in text files may not be rendered correctly in a system with a character encoding different from that used in the text document. How could iconv be used to convert the WINDOWS-1252 encoded file old.txt to the file new.txt using UTF-8 encoding? Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 239 LPIC-1 (102) (Version 5.0) | Topic 107: Administrative Tasks Explorational Exercises 1. What command will make Pacific/Auckland the default time zone for the current shell session? 2. Command uptime shows, among other things, the load average of the system in fractional numbers. It uses the current locale settings to decide if the decimal place separator should be a dot or a comma. If, for example, the current locale is set to de_DE.UTF-8 (the standard locale of Germany), uptime will use a comma as the separator. Knowing that in the American English language the dot is used as the separator, what command will make uptime display the fractions using a dot instead of a comma for the rest of the current session? 3. Command iconv will replace all characters outside the target character set with a question mark. If //TRANSLIT is appended to the target encoding, characters not represented in the target character set will be replaced (transliterated) by one or more similar looking characters. How could this method be used to convert a UTF-8 text file named readme.txt to a plain ASCII file named ascii.txt? 240 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 107.3 Localisation and internationalisation Summary This lesson covers how to set up a Linux system to work with custom languages and time settings. Character encoding concepts and settings are also covered, as they are very important to correctly render text content. The lesson goes through the following topics: How Linux systems select the language to display shell messages. Understanding how time zones affect the local time. How to identify the appropriate time zone and modify system settings accordingly. What character encodings are and how to convert between them. The commands and procedures addressed were: Locale and time related environment variables, such as LC_ALL, LANG and TZ. /etc/timezone /etc/localtime /usr/share/zoneinfo/ locale tzselect timedatectl date iconv Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 241 LPIC-1 (102) (Version 5.0) | Topic 107: Administrative Tasks Answers to Guided Exercises 1. Based on the following output of the command date, what is the time zone of the system in GMT notation? $ date Mon Oct 21 18:45:21 +05 2019 It’s the Etc/GMT+5 time zone. 2. To what file should the symbolic link /etc/localtime point to in order to make Europe/Brussels the system’s default local time? The link /etc/localtime should point to /usr/share/zoneinfo/Europe/Brussels. 3. Characters in text files may not be rendered correctly in a system with a character encoding different from that used in the text document. How could iconv be used to convert the WINDOWS-1252 encoded file old.txt to the file new.txt using UTF-8 encoding? Command iconv -f WINDOWS-1252 -t UTF-8 -o new.txt old.txt will perform the desired conversion. 242 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 107.3 Localisation and internationalisation Answers to Explorational Exercises 1. What command will make Pacific/Auckland the default time zone for the current shell session? export TZ=Pacific/Auckland 2. Command uptime shows, among other things, the load average of the system in fractional numbers. It uses the current locale settings to decide if the decimal place separator should be a dot or a comma. If, for example, the current locale is set to de_DE.UTF-8 (the standard locale of Germany), uptime will use a comma as the separator. Knowing that in the American English language the dot is used as the separator, what command will make uptime display the fractions using a dot instead of a comma for the rest of the current session? The command export LC_NUMERIC=en_US.UTF-8 or export LC_ALL=en_US.UTF-8. 3. Command iconv will replace all characters outside the target character set with a question mark. If //TRANSLIT is appended to the target encoding, characters not represented in the target character set will be replaced (transliterated) by one or more similar looking characters. How this method can be used to convert a UTF-8 text file named readme.txt to a plain ASCII file named ascii.txt? Command iconv -f UTF-8 -t ASCII//TRANSLIT -o ascii.txt readme.txt will perform the desired conversion. Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 243 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services Topic 108: Essential System Services 244 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time 108.1 Maintain system time Reference to LPI objectives LPIC-1 version 5.0, Exam 102, Objective 108.1 Weight 3 Key knowledge areas Set the system date and time. Set the hardware clock to the correct time in UTC. Configure the correct timezone. Basic NTP configuration using ntpd and chrony. Knowledge of using the pool.ntp.org service. Awareness of the ntpq command. Partial list of the used files, terms and utilities /usr/share/zoneinfo/ /etc/timezone /etc/localtime /etc/ntp.conf /etc/chrony.conf date hwclock timedatectl Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 245 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services ntpd ntpdate chronyc pool.ntp.org 246 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time 108.1 Lesson 1 Certificate: LPIC-1 (102) Version: 5.0 Topic: 108 Essential System Services Objective: 108.1 Maintain system time Lesson: 1 of 2 Introduction Accurate timekeeping is absolutely crucial for modern computing. The implementation of keeping time, however, is surprisingly complex. The practice of keeping time seems trivial to an end-user, but the system needs to be able to handle many idiosyncrasies and edge cases intelligently. Consider that time zones are not static, but may be changed by an administrative or political decision. A country may choose to stop observing Daylight Savings Time. Any program must be able to handle those changes logically. Fortunately for system administrators, the solutions for timekeeping on the Linux operating system are mature, robust and usually work without much interference. When a Linux computer boots up, it starts keeping time. We refer to this as a system clock, since it is updated by the operating system. In addition, modern computers will also have a hardware or real time clock. This hardware clock is often a feature of the motherboard and keeps time regardless if the computer is running or not. During boot, the system time is set from the hardware clock, but for the most part these two clocks run independently of each other. In this lesson we will be discussing methods of interacting with both the system and hardware clocks. On most modern Linux systems, system time and hardware time are synchronised to network Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 247 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services time, which is implemented by the Network Time Protocol (NTP). In the vast majority of cases, the only configuration a normal user will be required to do is to set their time zone and NTP will take care of the rest. However, we will cover some ways of working with time manually and the specifics of configuring network time will be covered in the next lesson. Local Versus Universal Time The system clock is set to Coordinated Universal Time (UTC), which is the local time at Greenwich, United Kingdom. Usually a user wants to know their local time. Local time is calculated by taking UTC time and applying an offset based on time zone and Daylight Savings. In this way, a lot of complexity can be avoided. The system clock can be set to either UTC time or local time, but it is recommended that it also be set to UTC time. Date date is a core utility which simply prints local time: $ date Sun Nov 17 12:55:06 EST 2019 Modifying the options of the date command will change the format of the output. For example, a user can use date -u to view the current UTC time. $ date -u Sun Nov 17 18:02:51 UTC 2019 Some other commonly-used options will return the local time in a format which adheres to an accepted RFC format: -I Date/time in ISO 8601 format. Appending date (-Idate) will limit the output to date only. Other formats are hours, minutes, seconds and ns for nanoseconds. -R Returns date and time in RFC 5322 format. 248 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time --rfc-3339 Returns date and time in RFC 3339 format. The format of date can be customized by the user with sequences specified in the man page. For example, the current time can be formatted as Unix time thusly: $ date +%s 1574014515 From date 's man page we can see that %s refers to Unix time. Unix time is used internally on most Unix-like systems. It stores UTC time as the number of seconds since Epoch, which has been defined as January 1st, 1970. The number of bits required to store Unix time at the present moment is 32 bits. There is a future issue when 32 bits will become insufficient to contain the current NOTE time in Unix format. This will cause serious issues for any 32-bit Linux systems. Fortunately, this will not occur until January 19, 2038. Using these sequences, we are able to format date and time in almost any format required by any application. Of course, in most cases it is far preferable to stick with an accepted standard. Additionally, date --date can be used to format a time that is not the current time. In this scenario, a user can specify the date to be applied to the system using Unix time for example: $ date --date='@1564013011' Wed Jul 24 20:03:31 EDT 2019 Using the --debug option can be very useful for ensuring that a date can be successfully parsed. Observe what happens when passing a valid date to the command: $ date --debug --date="Fri, 03 Jan 2020 14:00:17 -0500" date: parsed day part: Fri (day ordinal=0 number=5) date: parsed date part: (Y-M-D) 2020-01-03 date: parsed time part: 14:00:17 UTC-05 date: input timezone: parsed date/time string (-05) date: using specified time as starting value: '14:00:17' date: warning: day (Fri) ignored when explicit dates are given date: starting date/time: '(Y-M-D) 2020-01-03 14:00:17 TZ=-05' date: '(Y-M-D) 2020-01-03 14:00:17 TZ=-05' = 1578078017 epoch-seconds date: timezone: system default Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 249 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services date: final: 1578078017.000000000 (epoch-seconds) date: final: (Y-M-D) 2020-01-03 19:00:17 (UTC) date: final: (Y-M-D) 2020-01-03 14:00:17 (UTC-05) This can be a handy tool when troubleshooting an application that generates a date. Hardware Clock A user may run the hwclock command to view the time as maintained on the real-time clock. This command will require elevated privileges, so we will use sudo to call the command in this case: $ sudo hwclock 2019-11-20 11:31:29.217627-05:00 Using the option --verbose will return more output which might be useful for troubleshooting: $ sudo hwclock --verbose hwclock from util-linux 2.34 System Time: 1578079387.976029 Trying to open: /dev/rtc0 Using the rtc interface to the clock. Assuming hardware clock is kept in UTC time. Waiting for clock tick......got clock tick Time read from Hardware Clock: 2020/01/03 19:23:08 Hw clock time : 2020/01/03 19:23:08 = 1578079388 seconds since 1969 Time since last adjustment is 1578079388 seconds Calculated Hardware Clock drift is 0.000000 seconds 2020-01-03 14:23:07.948436-05:00 Note the Calculated Hardware Clock drift. This output can tell you if system time and hardware time are deviating from one another. timedatectl timedatectl is a command that can be used to check the general status of time and date, including whether or not network time has been synchronised (Network Time Protocol will be covered in the next lesson). By default timedatectl returns information similar to date, but with the addition of the RTC 250 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time (hardware) time as well as the status of the NTP service: $ timedatectl Local time: Thu 2019-12-05 11:08:05 EST Universal time: Thu 2019-12-05 16:08:05 UTC RTC time: Thu 2019-12-05 16:08:05 Time zone: America/Toronto (EST, -0500) System clock synchronized: yes NTP service: active RTC in local TZ: no Setting Time Using timedatectl If NTP is unavailable, it is recommended to use timedatectl rather than date or hwclock to set time: # timedatectl set-time '2011-11-25 14:00:00' The process is similar to that of date. The user can also set time independent of date using the format HH:MM:SS. Setting Timezone Using timedatectl timedatectl is the preferred way of setting the local time zone on systemd based Linux systems when no GUI exists. timedatectl will list possible time zones and then the time zone can be set using one of these as an argument. First we will list possible timezones: $ timedatectl list-timezones Africa/Abidjan Africa/Accra Africa/Algiers Africa/Bissau Africa/Cairo... The list of possible time zones is long, so the use of the grep command is recommended in this case. Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 251 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services Next we can set the timezone using one of the elements of the list that was returned: $ timedatectl set-timezone Africa/Cairo $ timedatectl Local time: Thu 2019-12-05 18:18:10 EET Universal time: Thu 2019-12-05 16:18:10 UTC RTC time: Thu 2019-12-05 16:18:10 Time zone: Africa/Cairo (EET, +0200) System clock synchronized: yes NTP service: active RTC in local TZ: no Keep in mind that the name of the time zone must be exact. Africa/Cairo for example will change the time zone, but cairo or africa/cairo will not. Disabling NTP Using timedatectl In some cases it might be necessary to disable NTP. This could be done using systemctl but we will demonstrate this using timedatectl: # timedatectl set-ntp no $ timedatectl Local time: Thu 2019-12-05 18:19:04 EET Universal time: Thu 2019-12-05 16:19:04 UTC RTC time: Thu 2019-12-05 16:19:04 Time zone: Africa/Cairo (EET, +0200) NTP enabled: no NTP synchronized: no RTC in local TZ: no DST active: n/a Setting Time Zone Without timedatectl Setting time zone information is a standard step when installing Linux on a new machine. If there is a graphical installation process, this will most likely be handled without any further user input. The /usr/share/zoneinfo directory contains information for the different time zones that are possible. In the zoneinfo directory, there are subdirectories that contain the names of continents as well as other symbolic links. It is recommended to find your region’s zoneinfo starting from your continent. 252 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time zoneinfo files contain rules required to calculate the local time offset in relation to UTC, and they also are important if your region observes Daylight Savings Time. The contents of /etc/localtime will be read when Linux needs to determine the local time zone. In order to set the time zone without the use of a GUI, the user should create a symbolic link for their location from /usr/share/zoneinfo to /etc/localtime. For example: $ ln -s /usr/share/zoneinfo/Canada/Eastern /etc/localtime After setting the correct time zone, it is often recommended to run: # hwclock --systohc This will set the hardware clock from the system clock (that is, the real-time clock will be set to the same time as date). Please note that this command is run with root privileges, in this case by being logged in as root. /etc/timezone is similar to /etc/localtime. It is a data representation of the local time zone, and as such it can be read using cat: $ cat /etc/timezone America/Toronto Note that this file is not used by all Linux distributions. Setting Date and Time Without timedatectl Most modern Linux systems use systemd for its configuration and services and as such it is not recommended that you use date or hwclock for setting time. NOTE systemd uses timedatectl for this. Nonetheless it is important to know these legacy commands in the event that you must administer an older system. Using date date has an option to set the system time. Use --set or -s to set the date and time. You may also choose to use --debug to verify the correct parsing of the command: # date --set="11 Nov 2011 11:11:11" Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 253 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services Note that root privileges are required to set the date here. We may also choose to change to time or date independently: # date +%Y%m%d -s "20111125" Here we must specify the sequences so that our string is parsed properly. For example %Y refers to the year, and so the first four digits 2011 will be interpreted as the year 2011. Similarly, %T is the sequence for time, and it is demonstrated here by setting time: # date +%T -s "13:11:00" After changing system time, it is recommended to also set the hardware clock so that both system and hardware clocks are synchronised: # hwclock --systohc systohc means “system clock to hardware clock”. Using hwclock Rather than setting the system clock and updating the hardware clock, you may choose to reverse the process. We will start by setting the hardware clock: # hwclock --set --date "4/12/2019 11:15:19" # hwclock Fri 12 Apr 2019 6:15:19 AM EST -0.562862 seconds Notice that by default hwclock is expecting UTC time, but returns the local time by default. After setting the hardware clock, we will need to update the system clock from it. hctosys can be understood to mean “hardware clock to system clock”. # hwclock --hctosys 254 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time Guided Exercise 1. Indicate whether the following commands are displaying or modifying system time or hardware time: Command(s) System Hardware Both date -u hwclock --set --date "12:00:00" timedatectl timedatectl | grep RTC hwclock --hctosys date +%T -s "08:00:00" timedatectl set- time 1980-01-10 2. Observe the following output, and then correct the format of the argument so that the command is successful: $ date --debug --date "20/20/12 0:10 -3" date: warning: value 20 has less than 4 digits. Assuming MM/DD/YY[YY] date: parsed date part: (Y-M-D) 0002-20-20 date: parsed time part: 00:10:00 UTC-03 date: input timezone: parsed date/time string (-03) date: using specified time as starting value: '00:10:00' date: error: invalid date/time value: date: user provided time: '(Y-M-D) 0002-20-20 00:10:00 TZ=-03' date: normalized time: '(Y-M-D) 0003-08-20 00:10:00 TZ=-03' date: ---- -- date: possible reasons: date: numeric values overflow; date: incorrect timezone date: invalid date ‘20/20/2 0:10 -3’ Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 255 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services 3. Use the date command and sequences so that the system’s month is set to February. Leave the rest of the date and time unchanged. 4. Assuming that the command above was successful, use hwclock to set the hardware clock from the system clock. 5. There is a location called eucla. What continent is it part of? Use the grep command to find out. 6. Set your current timezone to that of eucla. 256 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time Explorational Exercises 1. Which method of setting time is optimal? In what scenario might the preferred method be impossible? 2. Why do you think there are so many methods to accomplish the same thing, i.e. setting system time? 3. After January 19, 2038, Linux System Time will require a 64-bit number to store. However, it is possible that we could simply choose to set a “New Epoch”. For example, January 1st, 2038 at midnight could be set to a New Epoch Time of 0. Why do you think this has not become the preferred solution? Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 257 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services Summary In this lesson you learned: How to display the time in different formats from the command line. The difference between the system clock and the hardware clock in Linux. How to manually set the system clock. How to manually set the hardware clock. How to change the system’s time zone. Commands used in this lesson: date Display or the change the system clock. Other options: -u Display UTC time. +%s Use a sequence to display Epoch time. --date= Specify a specific time to display, as opposed to current time. --debug Display debug messages when parsing a user-inputted date. -s Set system clock manually. hwclock Display or change the hardware clock. --systohc Use system clock to set hardware clock. --hctosys Use hardware clock to set system clock. 258 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time --set --date Set hardware clock manually. timedatectl Display system and hardware clocks, as well as NTP configuration on systemd-based Linux systems. set-time Set the time manually. list-timezones List possible timezones. set-timezone Set timzone manually. set-ntp Enable/disable NTP. Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 259 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services Answers to Guided Exercises 1. Indicate whether the following commands are displaying or modifying system time or hardware time: Command(s) System Hardware Both date -u X hwclock --set X --date "12:00:00" timedatectl X timedatectl | grep X RTC hwclock --hctosys X date +%T -s X "08:00:00" timedatectl set- X time 1980-01-10 2. Observe the following output, and then correct the format of the argument so that the command is successful: $ date --debug --date "20/20/12 0:10 -3" date: warning: value 20 has less than 4 digits. Assuming MM/DD/YY[YY] date: parsed date part: (Y-M-D) 0002-20-20 date: parsed time part: 00:10:00 UTC-03 date: input timezone: parsed date/time string (-03) date: using specified time as starting value: '00:10:00' date: error: invalid date/time value: date: user provided time: '(Y-M-D) 0002-20-20 00:10:00 TZ=-03' date: normalized time: '(Y-M-D) 0003-08-20 00:10:00 TZ=-03' date: ---- -- date: possible reasons: date: numeric values overflow; date: incorrect timezone date: invalid date ‘20/20/2 0:10 -3’ date --debug --set "12/20/20 0:10 -3" 260 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time 3. Use the date command and sequences so that the system’s month is set to February. Leave the rest of the date and time unchanged. date +%m -s "2" 4. Assuming that the command above was successful, use hwclock to set the hardware clock from the system clock. hwclock -systohc 5. There is a location called eucla. What continent is it part of? Use the grep command to find out. Enter the complete command below: timedatectl list-timezones \| grep -i eucla OR grep -ri eucla /usr/share/zoneinfo 6. Set your current timezone to that of eucla. timedatectl set-timezone 'Australia/Eucla' or ln -s /usr/share/zoneinfo/Australia/Eucla /etc/localtime Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 261 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services Answers to Explorational Exercises 1. Which method of setting time is optimal? In what scenario might the preferred method be impossible? In most Linux distributions, NTP is enabled by default and should be left to set system time without interference. However, if there is a Linux system that isn’t connected to the internet, NTP will be inaccessible. For example, an embedded Linux system running on industrial equipment might not have network connectivity. 2. Why do you think there are so many methods to accomplish the same thing, i.e. setting system time? Since setting time has been a requirement of all *nix systems for decades, there are many legacy methods for setting time that are still maintained. 3. After January 19, 2038, Linux System Time will require a 64-bit number to store. However, it is possible that we could simply choose to set a “New Epoch”. For example, January 1st, 2038 at midnight could be set to a New Epoch Time of 0. Why do you think this has not become the preferred solution? By 2038 the vast majority of computers will already be running 64-bit CPUs, and using a 64-bit number won’t degrade performance in any significant way. However, it would be impossible to estimate the risks of “resetting” Epoch time in such a way. There is a lot of legacy software that might be impacted. Banks and large businesses, for example, often have a large amount of older programs that they rely on for internal use. So this scenario, like so many others, is a study in trade-offs. Any 32-bit systems still running in 2038 would be impacted by an Epoch Time overflow, but legacy software would be impacted by changing the value of Epoch. 262 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time 108.1 Lesson 2 Certificate: LPIC-1 (102) Version: 5.0 Topic: 108 Essential System Services Objective: 108.1 Maintain system time Lesson: 2 of 2 Introduction While personal computers are able to keep reasonably accurate time on their own, production computing and network environments requires that very precise time be kept. The most accurate time is measured by reference clocks, which are typically atomic clocks. The modern world has devised a system where all internet-connected computer systems can be synchronised to these reference clocks using what is known as the Network Time Protocol (NTP). A computer system with NTP will be able to synchronise their system clocks to the time provided by reference clocks. If system time and the time as measured on these servers are different, then the computer will speed up or slow down its internal system time incrementally until system time matches network time. NTP uses a hierarchical structure to disseminate time. Reference clocks are connected to servers at the top of the hierarchy. These servers are Stratum 1 machines and typically are not accessible to the public. Stratum 1 machines are however accessible to Stratum 2 machines, which are accessible to Stratum 3 machines and so on. Stratum 2 servers are accessible to the public, as are any machines lower in the hierarchy. When setting up NTP for a large network, it is good practice to have a small number of computers connect to Stratum 2+ servers, and then have those machines provide NTP to all other machines. In this way, demands on Stratum 2 machines can be Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 263 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services minimized. There are some important terms that come up when discussing NTP. Some of these terms are used in the commands we will use to track the status of NTP on our machines: Offset This refers to the absolute difference between system time and NTP time. For example, if the system clock reads 12:00:02 and NTP time reads 11:59:58, then the offset between the two clocks is four seconds. Step If the time offset between the NTP provider and a consumer is greater than 128ms, then NTP will perform a single significant change to system time, as opposed to slowing or speeding the system time. This is called stepping. Slew Slewing refers to the changes made to system time when the offset between system time and NTP is less than 128ms. If this is the case, then changes will be made gradually. This is referred to as slewing. Insane Time If the offset between system time and NTP time is greater than 17 minutes, then the system time is considered insane and the NTP daemon will not introduce any changes to system time. Special steps will have to be taken to bring system time within 17 minutes of proper time. Drift Drift refers to the phenomenon where two clocks become out of sync over time. Essentially if two clocks are initially synchronised but then become out of sync over time, then clock drift is occurring. Jitter Jitter refers to the amount of drift since the last time a clock was queried. So if the last NTP sync occurred 17 minutes ago, and the offset between the NTP provider and consumer is 3 milliseconds, then 3 milliseconds is the jitter. Now we will discuss some of the specific ways that Linux implements NTP. timedatectl If your Linux distribution uses timedatectl, then by default it implements an SNTP client rather than a full NTP implementation. This is a less complex implementation of network time and 264 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time means that your machine will not serve NTP to other connected computers. In this case, SNTP will not work unless the timesyncd service is running. As with all systemd services, we can verify that it is running with: $ systemctl status systemd-timesyncd systemd-timesyncd.service - Network Time Synchronization Loaded: loaded (/lib/systemd/system/systemd-timesyncd.service; enabled; vendor preset: enabled) Drop-In: /lib/systemd/system/systemd-timesyncd.service.d └─disable-with-time-daemon.conf Active: active (running) since Thu 2020-01-09 21:01:50 EST; 2 weeks 1 days ago Docs: man:systemd-timesyncd.service(8) Main PID: 1032 (systemd-timesyn) Status: "Synchronized to time server for the first time 91.189.89.198:123 (ntp.ubuntu.com)." Tasks: 2 (limit: 4915) Memory: 3.0M CGroup: /system.slice/systemd-timesyncd.service └─1032 /lib/systemd/systemd-timesyncd Jan 11 13:06:18 NeoMex systemd-timesyncd: Synchronized to time server for the first time 91.189.91.157:123 (ntp.ubuntu.com).... The status of timedatectl SNTP synchronisation can be verified using show-timesync: $ timedatectl show-timesync --all LinkNTPServers= SystemNTPServers= FallbackNTPServers=ntp.ubuntu.com ServerName=ntp.ubuntu.com ServerAddress=91.189.89.198 RootDistanceMaxUSec=5s PollIntervalMinUSec=32s PollIntervalMaxUSec=34min 8s PollIntervalUSec=34min 8s NTPMessage={ Leap=0, Version=4, Mode=4, Stratum=2, Precision=-23, RootDelay=8.270ms, RootDispersion=18.432ms, Reference=91EECB0E, OriginateTimestamp=Sat 2020-01-25 18:35:49 EST, ReceiveTimestamp=Sat 2020-01-25 18:35:49 EST, TransmitTimestamp=Sat 2020-01-25 18:35:49 EST, DestinationTimestamp=Sat 2020-01-25 18:35:49 EST, Ignored=no PacketCount=263, Jitter=2.751ms } Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 265 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services Frequency=-211336 This configuration might be adequate for most situations, but as noted before it will be insufficient if one is hoping to synchronise several clients in a network. In this case it is recommended to install a full NTP client. NTP Daemon The system time is compared to network time on a regular schedule. For this to work we must have a daemon running in the background. For many Linux systems, the name of this daemon is ntpd. ntpd will allow a machine to not only be a time consumer (that is, able to sync its own clock from an outside source), but also to provide time to other machines. Let us assume that our computer is systemd-based and it uses systemctl to control daemons. We will install ntp packages using the appropriate package manager and then ensure that our ntpd daemon is running by checking its status: $ systemctl status ntpd ntpd.service - Network Time Service Loaded: loaded (/usr/lib/systemd/system/ntpd.service; enabled; vendor preset: disabled) Active: active (running) since Fri 2019-12-06 03:27:21 EST; 7h ago Process: 856 ExecStart=/usr/sbin/ntpd -u ntp:ntp $OPTIONS (code=exited, status=0/SUCCESS) Main PID: 867 (ntpd) CGroup: /system.slice/ntpd.service `-867 /usr/sbin/ntpd -u ntp:ntp -g In some cases it might be required to both start and enable ntpd. On most Linux machines this is accomplished with: # systemctl enable ntpd && systemctl start ntpd NTP queries happen on TCP Port 123. If NTP fails, ensure that this port is open and listening. NTP Configuration NTP is able to poll several sources and to select the best candidates to use for setting system time. If a network connection is lost, NTP uses previous adjustments from its history to estimate future adjustments. 266 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time Depending on your distribution of Linux, the list of network time servers will be stored in different places. Let us assume that ntp is installed on your machine. The file /etc/ntp.conf contains configuration information about how your system synchronises with network time. This file can be read and modified using vi or nano. By default, the NTP servers used will be specified in a section like this: # Use public servers from the pool.ntp.org project. # Please consider joining the pool (http://www.pool.ntp.org/join.html). server 0.centos.pool.ntp.org iburst server 1.centos.pool.ntp.org iburst server 2.centos.pool.ntp.org iburst server 3.centos.pool.ntp.org iburst The syntax for adding NTP servers looks like this: server (IP Address) server server.url.localhost Server addresses can be IP addresses or URLs if DNS has been properly configured. In this case, the server will always be queried. A network administrator might also consider using (or setting up) a pool. In this case, we assume that there are several NTP providers, all running NTP daemons and with the same time. When a client queries a pool, a provider is selected at random. This helps to distribute network load among many machines so that no one machine in the pool is handling all NTP queries. Commonly, /etc/ntp.conf will be populated with a server pool called pool.ntp.org. So for example, server 0.centos.pool.ntp.org is a default NTP pool provided to CentOS machines. pool.ntp.org The NTP servers used by default are an open source project. More information can be found at ntppool.org. Consider if the NTP Pool is appropriate for your use. If business, organization or human life depends on having correct time or can be harmed by it being wrong, you shouldn’t “just get it off the internet”. The NTP Pool is generally very high quality, but it is a service run by volunteers in their spare time. Please talk to your equipment and service vendors about getting local and reliable service setup for you. See also our terms of service. We recommend Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 267 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services time servers from Meinberg, but you can also find time servers from End Run, Spectracom and many others. — ntppool.org ntpdate During initial setup, system time and NTP might be seriously de-synchronised. If the offset between system and NTP time is greater than 17 minutes, then the NTP daemon will not make changes to system time. In this scenario manual intervention will be required. Firstly, if ntpd is running it will be necessary to stop the service. Use systemctl stop ntpd to do so. Next, use ntpdate pool.ntp.org to perform an initial one-time synchronisation, where pool.ntp.org refers to the IP address or URL of an NTP server. More than one sync may be required. ntpq ntpq is a utility for monitoring the status of NTP. Once the NTP daemon has been started and configured, ntpq can be used to check on its status: $ ntpq -p remote refid st t when poll reach delay offset jitter ============================================================================== +37.44.185.42 91.189.94.4 3 u 86 128 377 126.509 -20.398 6.838 +ntp2.0x00.lv 193.204.114.233 2 u 82 128 377 143.885 -8.105 8.478 *inspektor-vlan1 121.131.112.137 2 u 17 128 377 112.878 -23.619 7.959 b1-66er.matrix. 18.26.4.105 2 u 484 128 10 34.907 -0.811 16.123 In this case -p is for print and it will print a summary of peers. Host addresses can also be returned as IP addresses using -n. remote hostname of the NTP provider. refid Reference ID of the NTP provider. 268 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time st Stratum of the provider. when Number of seconds since the last query. poll Number of seconds between queries. reach Status ID to indicate whether a server was reached. Successful connections will increase this number by 1. delay Time in ms between query and response by the server. offset Time in ms between system time and NTP time. jitter Offset in ms between system time and NTP in the last query. ntpq also has an interactive mode, which is accessed when it is run without options or argument. The ? option will return a list of commands that ntpq will recognize. chrony chrony is yet another way to implement NTP. It is installed by default on some Linux systems, but is available to download on all major distributions. chronyd is the chrony daemon, and chronyc is the command line interface. It may be required to start and enable chronyd before interacting with chronyc. If the chrony installation has a default configuration then using the command chronyc tracking will provide information about NTP and system time: $ chronyc tracking Reference ID : 3265FB3D (bras-vprn-toroon2638w-lp130-11-50-101-251-61.dsl.) Stratum : 3 Ref time (UTC) : Thu Jan 09 19:18:35 2020 System time : 0.000134029 seconds fast of NTP time Last offset : +0.000166506 seconds Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 269 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services RMS offset : 0.000470712 seconds Frequency : 919.818 ppm slow Residual freq : +0.078 ppm Skew : 0.555 ppm Root delay : 0.006151616 seconds Root dispersion : 0.010947504 seconds Update interval : 129.8 seconds Leap status : Normal This output contains a lot of information, more than what is available from other implementations. Reference ID The reference ID and name to which the computer is currently synced. Stratum Number of hops to a computer with an attached reference clock. Ref time This is the UTC time at which the last measurement from the reference source was made. System time Delay of system clock from synchronized server. Last offset Estimated offset of the last clock update. RMS offset Long term average of the offset value. Frequency This is the rate by which the system’s clock would be wrong if chronyd is not correcting it. It is provided in ppm (parts per million). Residual freq Residual frequency indicating the difference between the measurements from reference source and the frequency currently being used. Skew Estimated error bound of the frequency. 270 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time Root delay Total of the network path delays to the stratum computer, from which the computer is being synced. Leap status This is the leap status which can have one of the following values – normal, insert second, delete second or not synchronized. We can also look at detailed information about the last valid NTP update: # chrony ntpdata Remote address : 172.105.97.111 (AC69616F) Remote port : 123 Local address : 192.168.122.81 (C0A87A51) Leap status : Normal Version : 4 Mode : Server Stratum : 2 Poll interval : 6 (64 seconds) Precision : -25 (0.000000030 seconds) Root delay : 0.000381 seconds Root dispersion : 0.000092 seconds Reference ID : 61B7CE58 () Reference time : Mon Jan 13 21:50:03 2020 Offset : +0.000491960 seconds Peer delay : 0.004312567 seconds Peer dispersion : 0.000000068 seconds Response time : 0.000037078 seconds Jitter asymmetry: +0.00 NTP tests : 111 111 1111 Interleaved : No Authenticated : No TX timestamping : Daemon RX timestamping : Kernel Total TX : 15 Total RX : 15 Total valid RX : 15 Finally, chronyc sources will return information about the NTP servers that are used to synchronise time: $ chronyc sources Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 271 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services 210 Number of sources = 0 MS Name/IP address Stratum Poll Reach LastRx Last sample =============================================================================== At the moment, this machine has no sources configured. We can add sources from pool.ntp.org by opening the chrony configuration file. This will usually be located at /etc/chrony.conf. When we open this file, we should see that some servers are listed by default: 210 Number of sources = 0 MS Name/IP address Stratum Poll Reach LastRx Last sample =============================================================================== # Most computers using chrony will send measurement requests to one or # more 'NTP servers'. You will probably find that your Internet Service # Provider or company have one or more NTP servers that you can specify. # Failing that, there are a lot of public NTP servers. There is a list # you can access at http://support.ntp.org/bin/view/Servers/WebHome or # you can use servers from the 3.arch.pool.ntp.org project. ! server 0.arch.pool.ntp.org iburst iburst ! server 1.arch.pool.ntp.org iburst iburst ! server 2.arch.pool.ntp.org iburst iburst ! pool 3.arch.pool.ntp.org iburst These servers will also serve as a syntax guide when entering our own servers. However, in this case we will simply remove the ! s at the beginning of each line, thus uncommenting out these lines and using the default servers from the pool.ntp.org project. In addition, in this file we can choose to change the default configuration regarding skew and drift as well as the location of the driftfile and keyfile. On this machine, we need to make a large initial clock correction. We will choose to uncomment the following line: ! makestep 1.0 3 After making changes to the configuration file, restart the chronyd service and then use chronyc makestep to manually step the system clock: # chronyc makestep 272 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time 200 OK And then use chronyc tracking as before to verify that the changes have taken place. Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 273 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services Guided Exercise 1. Enter the appropriate term for each definition: Definition Term A computer that will share network time with you Distance from a reference clock, in hops or steps Difference between system time and network time Difference between system time and network time since the last NTP poll Group of servers that provide network time and share the load between them 2. Specify which of the commands you would use to output the following values: Value chronyc timedatectl ntpq -pn chrony chronyc tracking show- ntpdata sources timesync --all Jitter Drift Interval of Poll Offset Stratum IP Address of Provider Root Delay 3. You are setting up an enterprise network consisting of a Linux server and several Linux desktops. The server has a static IP address of 192.168.0.101. You decide that the server will connect to pool.ntp.org and then provide NTP time to the desktops. Describe the configuration of the server and of the desktops. 274 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time 4. A Linux machine has the incorrect time. Describe the steps you would take to troubleshoot NTP. Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 275 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services Explorational Exercise 1. Research the differences between SNTP and NTP. SNTP NTP 2. Why might a system administrator choose not to use pool.ntp.org? 3. How would a system administrator choose to join or otherwise contribute to the pool.ntp.org project? 276 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time Summary In this lesson you learned: What NTP is and why it is important. Configuring the NTP daemon from the pool.ntp.org project. Using ntpq to verify NTP configuration. Using chrony as an alternative NTP service. Commands used in this lesson: timedatectl show-timesync --all Display SNTP information if using timedatectl. ntpdate Perform a manual one-time NTP step update. ntpq -p Print a history of NTP recent polls. -n will replace URLs with IP addresses. chronyc tracking Displays NTP status if using chrony. chronyc ntpdata Displays NTP information about the last poll. chronyc sources Displays informations about NTP providers. chronyc makestep Perform a manual one-time NTP step update if using chrony. Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 277 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services Answers Guided Exercise 1. Enter the appropriate term for each definition: Definition Term A computer that will share network time with Provider you Distance from a reference clock, in hops or Stratum steps Difference between system time and network Offset time Difference between system time and network Jitter time since the last NTP poll Group of servers that provide network time Pool and share the load between them 2. Specify which of the commands you would use to output the following values: Value chronyc timedatectl ntpq -pn chrony chronyc tracking show- ntpdata sources timesync --all Jitter X X Drift Interval of Poll X X X (when X X column) Offset X X X Stratum X X X X X IP Address of X X X X Provider Root Delay X X 3. You are setting up an enterprise network consisting of a Linux server and several Linux desktops. The server has a static IP address of 192.168.0.101. You decide that the server will connect to pool.ntp.org and then provide NTP time to the desktops. Describe the 278 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.1 Maintain system time configuration of the server and of the desktops. Ensure that the server has an ntpd service running, rather than SNTP. Use pool.ntp.org pools in the /etc/ntp.conf or /etc/chrony.conf file. For each client, specify 192.168.0.101 in each /etc/ntp.conf or /etc/chrony.conf file. 4. A Linux machine has the incorrect time. Describe the steps you would take to troubleshoot NTP. First, ensure that the machine is connected to the Internet. Use ping for this. Check that an ntpd or SNTP service is running using systemctl status ntpd or systemctl status systemd-timesyncd. You may see error messages that provide useful information. Finally, use a command such as ntpq -p or chrony tracking to verify if any requests have been made. If the system time is drastically different from network time, it may be that system time is considered “insane” and will not be changed without manual intervention. In this case, use a command from the previous lesson or a command such as ntpdate pool.ntp.org to perform a one-time ntp synchronisation. Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 279 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services Answers to Explorational Exercises 1. Research the differences between SNTP and NTP. SNTP NTP less accurate more accurate requires fewer resources requires more resources cannot act as a time provider can act as a time provider steps time only steps or slews time requests time from a single source can monitor multiple NTP servers and use the optimal provider 2. Why might a system administrator choose not to use pool.ntp.org? From ntppool.org: If it is absolutely crucial to have correct time, you should consider an alternative. Similarly, if your Internet provider has a time server, it is recommended to use that instead. 3. How would a system administrator choose to join or otherwise contribute to the pool.ntp.org project? From www.ntppool.org: Your server must have a static IP address and a permanent internet connection. The static IP address must not change at all or at least less than once a year. Beyond that, the bandwidth requirements are modest: 384 - 512 Kbit bandwidth. Stratum 3 or 4 servers are welcome to join. 280 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.2 System logging 108.2 System logging Reference to LPI objectives LPIC-1 version 5.0, Exam 102, Objective 108.2 Weight 4 Key knowledge areas Basic configuration of rsyslog. Understanding of standard facilities, priorities and actions. Query the systemd journal. Filter systemd journal data by criteria such as date, service or priority Configure persistent systemd journal storage and journal size Delete old systemd journal data Retrieve systemd journal data from a rescue system or file system copy Understand interaction of rsyslog with systemd-journald Configuration of logrotate. Awareness of syslog and syslog-ng. Partial list of the used files, terms and utilities /etc/rsyslog.conf /var/log/ logger logrotate Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 281 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services /etc/logrotate.conf /etc/logrotate.d/ journalctl systemd-cat /etc/systemd/journald.conf /var/log/journal/ 282 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.2 System logging 108.2 Lesson 1 Certificate: LPIC-1 Version: 5.0 Topic: 108 Essential System Services Objective: 108.2 System logging Lesson: 1 of 2 Introduction Logs can be a system administrator’s best friend. Logs are files (usually text files) where all system and network events are chronologically registered from the moment your system is booted up. Thus, the range of information that can be found in logs includes virtually every aspect of the system: failed authentication attempts, program and service errors, hosts blocked by the firewall, etc. As you can imagine, logs make system administrators' lives a lot easier when it comes to troubleshooting, resource-checking, detection of anomalous behaviour of programs, and so on. In this lesson we will discuss one of the most common logging facilites currently found in GNU/Linux distributions: rsyslog. We will study the different types of logs that exist, where they are stored, what information they include and how that information can be obtained and filtered. We will also discuss how logs can be kept in centralized servers across IP networks, log rotation and the kernel ring buffer. System Logging The moment the kernel and the different processes in your system start running and communicating with one another, a lot of information is generated in the form of messages that Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 283 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services are — for the most part — sent to the logs. Without logging, searching for an event that happened on a server would give system administrators a headache, hence the importance of having a standardized and centralized way of keeping track of any system events. Logs are determinant and telling when it comes to troubleshooting and security and are reliable data sources for understanding system statistics and making trend predictions. Leaving aside systemd-journald (which we will discuss in the next lesson), logging has traditionally been handled by three main dedicated services: syslog, syslog-ng (syslog new generation) and rsyslog (“the rocket-fast system for log processing”). rsyslog brought along important improvements (such as RELP support) and has become the most popular choice nowadays. Each of these services collects messages from other services and programs and stores them in log files, typically under /var/log. However, some services take care of their own logs (take — for example — the Apache HTTPD web server or the CUPS printing system). Likewise, the Linux kernel uses an in-memory ring buffer for storing its log messages. RELP stands for Reliable Event Logging Protocol and extends the functionality of the NOTE syslog protocol to provide reliable delivery of messages. Since rsyslog has become the de facto standard logging facility in all major distros, we will focus on it for the present lesson. rsyslog uses a client-server model. The client and the server can live on the same host or in different machines. Messages are sent and received in a particular format and can be kept in centralized rsyslog servers across IP networks. rsyslog’s daemon — rsyslogd — works together with klogd (which manages kernel messages). In the next sections rsyslog and its logging infrastructure will be discussed. A daemon is a service that runs in the background. Note the final d in daemon NOTE names: klogd or rsyslogd. Log Types Because logs are variable data, they are normally found in /var/log. Roughly speaking, they can be classified into system logs and service or program logs. Let us see some system logs and the information they keep: /var/log/auth.log Activities related to authentication processes: logged users, sudo information, cron jobs, failed login attempts, etc. 284 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.2 System logging /var/log/syslog A centralized file for practically all of the logs captured by rsyslogd. Because it includes so much information, logs are distributed across other files according to the configuration supplied in /etc/rsyslog.conf. /var/log/debug Debug information from programs. /var/log/kern.log Kernel messages. /var/log/messages Informative messages which are not related to the kernel but to other services. It is also the default remote client log destination in a centralized log server implementation. /var/log/daemon.log Information related to daemons or services running in the background. /var/log/mail.log Information related to the email server, e.g. postfix. /var/log/Xorg.0.log Information related to the graphics card. /var/run/utmp and /var/log/wtmp Successful logins. /var/log/btmp Failed login attempts, e.g. brute force attack via ssh. /var/log/faillog Failed authentication attempts. /var/log/lastlog Date and time of recent user logins. Now let us see a few examples of service logs: /var/log/cups/ Directory for logs of the Common Unix Printing System. It commonly includes the following default log files: error_log, page_log and access_log. Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 285 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services /var/log/apache2/ or /var/log/httpd Directory for logs of the Apache Web Server. It commonly includes the following default log files: access.log, error_log, and other_vhosts_access.log. /var/log/mysql Directory for logs of the MySQL Relational Database Management System. It commonly includes the following default log files: error_log, mysql.log and mysql-slow.log. /var/log/samba/ Directory for logs of the Session Message Block (SMB) protocol. It commonly includes the following default log files: log., log.nmbd and log.smbd. The exact name and contents of log files may vary across Linux distributions. There are also logs particular to specific distributions such as /var/log/dpkg.log NOTE (containing information related to dpkg packages) in Debian GNU/Linux and its derivatives. Reading Logs To read log files, first ensure you are the root user or have reading permissions on the file. You can use a variety of utilities such as: less or more Pagers that allow viewing and scrolling one page at a time: root@debian:~# less /var/log/auth.log Sep 12 18:47:56 debian sshd: Received SIGHUP; restarting. Sep 12 18:47:56 debian sshd: Server listening on 0.0.0.0 port 22. Sep 12 18:47:56 debian sshd: Server listening on :: port 22. Sep 12 18:47:56 debian sshd: Received SIGHUP; restarting. Sep 12 18:47:56 debian sshd: Server listening on 0.0.0.0 port 22. Sep 12 18:47:56 debian sshd: Server listening on :: port 22. Sep 12 18:49:46 debian sshd: Accepted password for carol from 192.168.1.65 port 44296 ssh2 Sep 12 18:49:46 debian sshd: pam_unix(sshd:session): session opened for user carol by (uid=0) Sep 12 18:49:46 debian systemd-logind: New session 2 of user carol. Sep 12 18:49:46 debian systemd: pam_unix(systemd-user:session): session opened for user carol by (uid=0) (...) 286 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.2 System logging zless or zmore The same as less and more, but used for logs that are compressed with gzip (a common function of logrotate): root@debian:~# zless /var/log/auth.log.3.gz Aug 19 20:05:57 debian sudo: carol : TTY=pts/0 ; PWD=/home/carol ; USER=root ; COMMAND=/sbin/shutdown -h now Aug 19 20:05:57 debian sudo: pam_unix(sudo:session): session opened for user root by carol(uid=0) Aug 19 20:05:57 debian lightdm: pam_unix(lightdm-greeter:session): session closed for user lightdm Aug 19 23:50:49 debian systemd-logind: Watching system buttons on /dev/input/event2 (Power Button) Aug 19 23:50:49 debian systemd-logind: Watching system buttons on /dev/input/event3 (Sleep Button) Aug 19 23:50:49 debian systemd-logind: Watching system buttons on /dev/input/event4 (Video Bus) Aug 19 23:50:49 debian systemd-logind: New seat seat0. Aug 19 23:50:49 debian sshd: Server listening on 0.0.0.0 port 22. (...) tail View the last lines in a file (the default is 10 lines). The power of tail lies — to a great extent — in the -f switch, which will dynamically show new lines as they are appended: root@suse-server:~# tail -f /var/log/messages 2019-09-14T13:57:28.962780+02:00 suse-server sudo: pam_unix(sudo:session): session closed for user root 2019-09-14T13:57:38.038298+02:00 suse-server sudo: carol : TTY=pts/0 ; PWD=/home/carol ; USER=root ; COMMAND=/usr/bin/tail -f /var/log/messages 2019-09-14T13:57:38.039927+02:00 suse-server sudo: pam_unix(sudo:session): session opened for user root by carol(uid=0) 2019-09-14T14:07:22+02:00 debian carol: appending new message from client to remote server... head View the first lines in a file (the default is 10 lines): root@suse-server:~# head -5 /var/log/mail 2019-06-29T11:47:59.219806+02:00 suse-server postfix/postfix-script: the Postfix mail system is not running Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 287 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services 2019-06-29T11:48:01.355361+02:00 suse-server postfix/postfix-script: starting the Postfix mail system 2019-06-29T11:48:01.391128+02:00 suse-server postfix/master: daemon started -- version 3.3.1, configuration /etc/postfix 2019-06-29T11:55:39.247462+02:00 suse-server postfix/postfix-script: stopping the Postfix mail system 2019-06-29T11:55:39.249375+02:00 suse-server postfix/master: terminating on signal 15 grep Filtering utility which allows you to search for specific strings: root@debian:~# grep "dhclient" /var/log/syslog Sep 13 11:58:48 debian dhclient: DHCPREQUEST of 192.168.1.4 on enp0s3 to 192.168.1.1 port 67 Sep 13 11:58:49 debian dhclient: DHCPACK of 192.168.1.4 from 192.168.1.1 Sep 13 11:58:49 debian dhclient: bound to 192.168.1.4 -- renewal in 1368 seconds. (...) As you may have noticed, the output is printed in the following format: Timestamp Hostname from which the message originated Name of program/service that generated the message The PID of the program that generated the message Description of the action that took place There are a few examples in which logs are not text, but binary files and — consequently — you must use special commands to parse them: /var/log/wtmp Use who (or w): root@debian:~# who root pts/0 2020-09-14 13:05 (192.168.1.75) root pts/1 2020-09-14 13:43 (192.168.1.75) /var/log/btmp Use utmpdump or last -f: 288 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.2 System logging root@debian:~# utmpdump /var/log/btmp Utmp dump of /var/log/btmp [ ] [dave ] [ssh:notty ] [192.168.1.75 ] [192.168.1.75 ] [2019-09-07T19:33:32,000000+0000] /var/log/faillog Use faillog: root@debian:~# faillog -a | less Login Failures Maximum Latest On root 0 0 01/01/70 01:00:00 +0100 daemon 0 0 01/01/70 01:00:00 +0100 bin 0 0 01/01/70 01:00:00 +0100 sys 0 0 01/01/70 01:00:00 +0100 sync 0 0 01/01/70 01:00:00 +0100 games 0 0 01/01/70 01:00:00 +0100 man 0 0 01/01/70 01:00:00 +0100 lp 0 0 01/01/70 01:00:00 +0100 mail 0 0 01/01/70 01:00:00 +0100 (...) /var/log/lastlog Use lastlog: root@debian:~# lastlog | less Username Port From Latest root Never logged in daemon Never logged in bin Never logged in sys Never logged in (...) sync Never logged in avahi Never logged in colord Never logged in saned Never logged in hplip Never logged in carol pts/1 192.168.1.75 Sat Sep 14 13:43:06 +0200 2019 dave pts/3 192.168.1.75 Mon Sep 2 14:22:08 +0200 2019 Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 289 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services There are also graphical tools for reading log files, for example: gnome-logs and NOTE KSystemLog. How Messages are Turned into Logs The following process illustrates how a message is written to a log file: 1. Applications, services and the kernel write messages in special files (sockets and memory buffers), e.g. /dev/log or /dev/kmsg. 2. rsyslogd gets the information from the sockets or memory buffers. 3. Depending on the rules found in /etc/rsyslog.conf and/or the files in /etc/ryslog.d/, rsyslogd moves the information to the corresponding log file (typically found in /var/log). A socket is a special file used to transfer information between different processes. NOTE To list all sockets on your system, you can use the command systemctl list- sockets --all. Facilities, Priorities and Actions rsyslog configuration file is /etc/rsylog.conf (in some distributions you can also find configuration files in /etc/rsyslog.d/). It is normally divided into three sections: MODULES, GLOBAL DIRECTIVES and RULES. Let us have a look at them by exploring the rsyslog.conf file in our Debian GNU/Linux 10 (buster) host — you can use sudo less /etc/rsyslog.conf to do so. MODULES includes module support for logging, message capability, and UDP/TCP log reception: ################# #### MODULES #### ################# module(load="imuxsock") # provides support for local system logging module(load="imklog") # provides kernel logging support #module(load="immark") # provides --MARK-- message capability # provides UDP syslog reception #module(load="imudp") #input(type="imudp" port="514") # provides TCP syslog reception #module(load="imtcp") 290 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.2 System logging #input(type="imtcp" port="514") GLOBAL DIRECTIVES allow us to configure a number of things such as logs and log directory permissions: ########################### #### GLOBAL DIRECTIVES #### ########################### # # Use traditional timestamp format. # To enable high precision timestamps, comment out the following line. # $ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat # # Set the default permissions for all log files. # $FileOwner root $FileGroup adm $FileCreateMode 0640 $DirCreateMode 0755 $Umask 0022 # # Where to place spool and state files # $WorkDirectory /var/spool/rsyslog # # Include all config files in /etc/rsyslog.d/ # $IncludeConfig /etc/rsyslog.d/*.conf RULES is where facilities, priorities and actions come in. The settings in this section tell the logging daemon to filter messages according to certain rules and log them or send them where required. To understand these rules, we should first explain the concepts of rsyslog facilities and priorities. Each log message is given a facility number and keyword that are associated with the Linux internal subsystem that produces the message: Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 291 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services Number Keyword Description 0 kern Linux kernel messages 1 user User-level messages 2 mail Mail system 3 daemon System daemons 4 auth, authpriv Security/Authorization messages 5 syslog syslogd messages 6 lpr Line printer subsystem 7 news Network news subsystem 8 uucp UUCP (Unix-to-Unix Copy Protocol) subsystem 9 cron Clock daemon 10 auth, authpriv Security/Authorization messages 11 ftp FTP (File Transfer Protocol) daemon 12 ntp NTP (Network Time Protocol) daemon 13 security Log audit 14 console Log alert 15 cron Clock daemon 16 - 23 local0 through local7 Local use 0 - 7 Furthermore, each message is assigned a priority level: Code Severity Keyword Description 0 Emergency emerg, panic System is unusable 1 Alert alert Action must be taken immediately 2 Critical crit Critical conditions 3 Error err, error Error conditions 292 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.2 System logging Code Severity Keyword Description 4 Warning warn, warning Warning conditions 5 Notice notice Normal but significant condition 6 Informational info Informational messages 7 Debug debug Debug-level messages Here is an excerpt of rsyslog.conf from our Debian GNU/Linux 10 (buster) system which including some sample rules: ############### #### RULES #### ############### # First some standard log files. Log by facility. # auth,authpriv.* /var/log/auth.log *.*;auth,authpriv.none -/var/log/syslog #cron.* /var/log/cron.log daemon.* -/var/log/daemon.log kern.* -/var/log/kern.log lpr.* -/var/log/lpr.log mail.* -/var/log/mail.log user.* -/var/log/user.log # # Logging for the mail system. Split it up so that # it is easy to write scripts to parse these files. # mail.info -/var/log/mail.info mail.warn -/var/log/mail.warn mail.err /var/log/mail.err # # Some "catch-all" log files. # *.=debug;\ auth,authpriv.none;\ news.none;mail.none -/var/log/debug *.=info;*.=notice;*.=warn;\ Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 293 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services auth,authpriv.none;\ cron,daemon.none;\ mail,news.none -/var/log/messages The rule format is as follows:. The. selector filters messages to match. Priority levels are hierarchically inclusive, which means rsyslog will match messages of the specified priority and higher. The shows what action to take (where to send the log message). Here are a few examples for clarity: auth,authpriv.* /var/log/auth.log Regardless of their priority (*), all messages from the auth or authpriv facilities will be sent to /var/log/auth.log. *.*;auth,authpriv.none -/var/log/syslog All messages — irrespective of their priority (*) — from all facilities (*) — discarding those from auth or authpriv (hence the.none suffix) — will be written to /var/log/syslog (the minus sign (-) before the path prevents excessive disk writes). Note the semicolon (;) to split the selector and the comma (,) to concatenate two facilities in the same rule (auth,authpriv). mail.err /var/log/mail.err Messages from the mail facility with a priority level of error or higher (critical, alert or emergency) will be sent to /var/log/mail.err. *.=debug;\ auth,authpriv.none;\ news.none;mail.none -/var/log/debug Messages from all facilities with the debug priority and no other (=) will be written to /var/log/debug — excluding any messages coming from the auth, authpriv, news and mail facilities (note the syntax: ;\). 294 | learning.lpi.org | Licensed under CC BY-NC-ND 4.0. | Version: 2023-07-13 LPIC-1 (102) (Version 5.0) | 108.2 System logging Manual Entries into the System Log: logger The logger command comes in handy for shell scripting or for testing purposes. logger will append any message it receives to /var/log/syslog (or to /var/log/messages when logging to a remote central log server as you will see later in this lesson): carol@debian:~$ logger this comment goes into "/var/log/syslog" To print the last line in /var/log/syslog, use the tail command with the -1 option: root@debian:~# tail -1 /var/log/syslog Sep 17 17:55:33 debian carol: this comment goes into /var/log/syslog rsyslog as a Central Log Server To explain this topic we are going to add a new host to our setup. The layout is as follows: Role Hostname OS IP Address Central Log Server suse-server openSUSE Leap 15.1 192.168.1.6 Client debian Debian GNU/Linux 10 192.168.1.4 (buster) Let us start by configuring the server. First of all, we make sure that rsyslog is up and running: root@suse-server:~# systemctl status rsyslog rsyslog.service - System Logging Service Loaded: loaded (/usr/lib/systemd/system/rsyslog.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2019-09-17 18:45:58 CEST; 7min ago Docs: man:rsyslogd(8) http://www.rsyslog.com/doc/ Main PID: 832 (rsyslogd) Tasks: 5 (limit: 4915) CGroup: /system.slice/rsyslog.service └─832 /usr/sbin/rsyslogd -n -iNONE openSUSE ships with a dedicated configuration file for remote logging: /etc/rsyslog.d/remote.conf. Let us enable receiving messages from clients (remote hosts) via TCP. We must uncomment the lines which load the module and start the TCP server on port 514: Version: 2023-07-13 | Licensed under CC BY-NC-ND 4.0. | learning.lpi.org | 295 LPIC-1 (102) (Version 5.0) | Topic 108: Essential System Services # ######### Receiving Messages from Remote Hosts ########## # TCP Syslog Server: # provides TCP syslog reception and GSS-API (if compiled to support it) $ModLoad imtcp.so # load module ##$UDPServerAddress 10.10.0.1 # force to listen on this IP only $InputTCPServerRun 514 # Starts a TCP server on selected port # UDP Syslog Server: #$ModLoad imudp.so # provides UDP syslog reception ##$UDPServerAddress 10.10.0.1 # force to listen on this IP only #$UDPServerRun 514 # start a UDP syslog server at standard port 514 Once this is done, we must restart the rsyslog service and check that the server is listening on port 514: root@suse-server:~# systemctl restart rsyslog root@suse-server:

Use Quizgecko on...
Browser
Browser