Sunteți pe pagina 1din 17

RHEL 7 – RHCSA Notes – Set enforcing and permissive modes for SELinux

SELinux modes
SELinux gives that extra layer of security to the resources in the system. It provides the MAC (mandatory access
control) as contrary to the DAC (Discretionary access control). Before we dive into setting the SELinux modes, let
us see what are the different SELinux modes of operation and how do they work. SELinux can operate in any of the
3 modes :
1. Enforced : Actions contrary to the policy are blocked and a corresponding event is logged in the audit log.
2. Permissive : Actions contrary to the policy are only logged in the audit log.
3. Disabled : The SELinux is disabled entirely.
Configuration file
SELinux configuration file /etc/selinux/config :
# cat /etc/selinux/config
SELINUX=disabled
SELINUXTYPE=targeted
Toggling SELinux modes (Temporarily)
To switch between the SELinux modes temporarily we can use the setenforce command as shown below :
# setenforce [ Enforcing | Permissive | 1 | 0 ]
0 –> Permissive
1 –> Enforcing
Verify the current mode of SELinux :
# getenforce
Enforcing
or we can also use the sestatus command to get a detailed status :
# sestatus
SELinux status: enabled
SELinuxfs mount: /selinux --> virtual FS similar to /proc
Current mode: enforcing --> current mode of operation
Mode from config file: permissive --> mode set in the /etc/sysconfig/selinux
file.
Policy version: 24
Policy from config file: targeted
Toggling SELinux modes (Permanently) [reboot require]
SELinux mode can be set permanently using either of below methods :
1. editing /etc/selinux/config file
2. editing kernel boot options
1. editing /etc/selinux/config file
to set SELinux to permissive, set the below line in the file /etc/selinux/config to :
vi /etc/selinux/config
....
SELINUX=permissive
...
Similarly the mode can be set to enforcing/disable by setting the mode in the same line.
2. editing kernel boot options
Edit the kernel boot line and append enforcing=0 to the kernel boot options. For example:
title Red Hat Enterprise Linux AS (2.6.9-42.ELsmp)
root (hd0,0)
kernel /vmlinuz-2.6.9-42.ELsmp ro root=LABEL=/ rhgb quiet enforcing=0
initrd /initrd-2.6.9-42.ELsmp.img

Reboot the server.


# shutdown -r now
Forcing reboot on changing mode
We can force a reboot on changing the selinux mode :
# setsebool secure_mode_policyload on
============================================================
How to know when a file has ACL attached to it
ls -l command would produce a output as show below. Note the + sign at the end of the permissions. This confirms
that the file has an ACL attached to it.
# ls -l
-rw-r--r-+ 1 root root 0 Sep 19 14:41 file
Viewing ACLs
To display details ACL information of a file use the getfacl command. If you see carefully, the users sam and john
have some extra permissions (shown highlighted). The default user/group permissions are specified using
“user::permission” and “group::
# getfacl /tmp/test
# file: test
# owner: root
# group: root
user::rw-
user:john:rw-
user:sam:rwx
group::r--
mask::rwx
other:---
In contrast, if you check the ACLs on a a file with “no ACLs” the additional “user:” lines and “mask” line will not
be shown and standard file permissions will be shown. :
# getfacl test
# file: test
# owner: root
# group: root
user::rw-
group::r--
other::r--
Creating and Managing FACLs
The setfacl command is used to set ACL on the given file. To give a rw access to user john on the file /tmp/test :
# setfacl -m u:john:rw /tmp/test
The -m option tells setfacl to modify ACLs on the file(s) mentioned in command line. Instead of user john we can
have a group to have a specific permission on the file :
# setfacl -m g:accounts:rw /tmp/test
FACLs for multiple user and groups can also be set with single command :
# setfacl -m u:john:rw,g:accounts:rwx /tmp/test
Default ACLs
By setting a default ACL, you’ll determine the permissions that will be set for all new items that are created in the
directory. But the permissions of existing files and subdirectories remains same.
To create a default FACL on a directory :
# setfacl -m default:u:john:rw /accounts
Notice the default permissions in the getfacl command :
# getfacl accounts/
# file: accounts/
# owner: root
# group: root
user::rwx
group::r-x
other::r-x
default:user::rwx
default:user:john:rw-
default:group::r-x
default:mask::rwx
default:other::r-x
Removing FACLs
To remove ACLs, use the setfacl command with -x option :
# setfacl -x u:john /tmp/test
The above command removes the ACL for the user john on the file /tmp/test. The ACLs for other user/groups if any
remains unaffected. To remove all ACLs associated to a file use the -b option with setfacl :
# setfacl -b /tmp/test
You can also create a backup of ACLs using getfacl, and restore ACLs using setfacl command. To create the backup,
use getfacl -R /dir > file.acls. To restore the settings from the backup file, use setfacl –restore=file.acl

Change passwords and adjust password aging for local user accounts
password aging requires users to change their password periodically. Use the chage to configure password
expiration. The syntax is :
# chage [options] user_name
– When you fire the command chage, the currently set options are displayed as well.
# chage oracle
Changing the aging information for oracle
Enter the new value, or press ENTER for the default

Minimum Password Age [14]:


Maximum Password Age [30]:
Last Password Change (YYYY-MM-DD) [2016-08-23]:
Password Expiration Warning [7]:
Password Inactive [-1]:
Account Expiration Date (YYYY-MM-DD) [1969-12-31]:
Password expiration information is stored in /etc/shadow file.
# grep oracle /etc/shadow
oracle:$6$H28sLVDL$iNvp/AvbMeqqrslH2bfmTxJpE6.mO8UNzlIXGB3sp87jZP9dW1DxeoLf2QXR7hkLkomuXbtgO1
zPKUEYRY8YI1:15284:14:30:7:::
As shown above the oracle user has minimum password age of 14 and maximum password age of 30 – It means that
in 14 days the user will have 30 days to change the password. Also the user is warned to change the password 7 days
prior to password expiry date.
chage options
Number of options are available in chage command. To list aging information :
# chage -l geek
Last password change : Sep 18, 2016
Password expires : never
Password inactive : never
Account expires : never
Minimum number of days between password change : 0
Maximum number of days between password change : 99999
Number of days of warning before password expires : 7
To force a user to set a new password immediately (force immediate expiration), set the last password change value
to 0 :
# chage –d 0 geek
authconfig
The Linux user password hashing algorithm is also configurable. Use the authconfig command to determine the
current algorithm being used, or to set it to something different. To determine the current algorithm:
# authconfig --test | grep hashing
password hashing algorithm is sha512
To change the algorithm, use the –passalgo option with one of the following as a parameter: descrypt, bigcrypt, md5,
sha256, or sha512, followed by the –update option.
# authconfig --passalgo=md5 --update
/etc/login.defs file
/etc/login.defs file provides default user account settings. Default values include:
Location of user mailboxes
Password aging controls
Values for automatic UID selection
Values for automatic GID selection
User home directory creation options
umaskvalue
Encryption method used to encrypt passwords
Sample /etc/login.defs file :
# cat /etc/login.defs
.....
PASS_MAX_DAYS 99999
PASS_MIN_DAYS 0
PASS_MIN_LEN 5
PASS_WARN_AGE 7
......
GID_MIN 1000
GID_MAX 60000
.....
UID_MIN 1000
UID_MAX 60000

Create, delete, and modify local groups and group memberships.


– Use the groupadd command to add a new group :
# groupadd [options] group_name
– Use the groupmod command to modify an existing group :
# groupmod [options] group_name
– Use groupdel to delete the group. You can remove a group even if there are users in the group. But you can not
remove the primary group of an existing user. You must remove the user before removing the group.
# groupdel group_name
– Use the gpasswd command to administer the groups :
# gpasswd [options] group_name
For example : to add user test in group student –
# gpasswd -a test student
groups command
The groups command displays the group the user belongs to. For example the user oracle as shown below belongs to
multiple groups which can be displayed using the groups command :
# groups oracle
oracle : oinstall dba asm asmdba oper
# grep oracle /etc/group
oinstall:x:5004:oracle
dba:x:5005:oracle
asm:x:5006:oracle
asmdba:x:5007:oracle
oper:x:5008:oracle
newgrp command
The newgroup command executes a new shell and changes a user’s real group information. For example,
Before executing newgrp command
$ id
uid=5004(oracle) gid=5004(oinstall) groups=5004(oinstall),5005(dba) ...
$ ps
PID TTY TIME CMD
106591 pts/0 00:00:00 bash
106672 pts/0 00:00:00 ps
After executing newgrp command
$ newgrp dba
Note the gid for the user has changed to that of the student group :
$ id
uid=5004(oracle) gid=5005(dba) groups=5005(dba),5004(oinstall) ...
Also note that a new shell has been executed.
$ ps
PID TTY TIME CMD
106591 pts/0 00:00:00 bash
106231 pts/0 00:00:00 bash
106672 pts/0 00:00:00 ps

Create, delete, and modify local user accounts


Use the useradd command to add new user :
# useradd [options] [username]
The default settings for new user can viewed and modified using the -D option :
# useradd -D
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/bash
SKEL=/etc/skel
CREATE_MAIL_SPOOL=yes
For example, to change the default user shell for new user to /bin/ksh :
# useradd -D -s /bin/ksh
Examples
To simple add a user with all default options :
# useradd user01
To add user with uid 1099, comment “new user” and default shell as /bin/ksh :
# useradd -u 1099 -c "new user" -s /bin/ksh user01
Check new user’s entry in /etc/passwd file :
grep user01 /etc/passwd
user01:x:1099:1099:new user:/home/user01:/bin/ksh
To modify existing user (e.g. changing the comment) :
# usermod -c "modified user" user01
To assign the password to new user:
# passwd user01
Changing password for user user01.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
View the /etc/shadow file :
# grep user01 /etc/shadow
user01:$6$dox84xyJ$89DdMcxSlI9OHxUCyY1ryaFsmG6MSEwbmSbZXJoFY.tHgdEEeQQgQjDV0dD8jEiHusrUjj3p8g
tMTKR4sXXN5.:17058:0:45:7:::
To delete the user :
# userdel user01
nologin shell
You can create a user with nologin shell for running services such as SMTP, FTP etc. A user without a login shell
can not login to a system and therefore cannot run any command on the system interactively on the system.
Processes can run as that users however.
To add new user “test” with shell nologin :
# useradd -s /sbin/nologin test
Make sure the nologin shell is present in the /etc/shells file :
# cat /etc/shells
/bin/sh
/bin/bash
/sbin/nologin
/usr/bin/sh
/usr/bin/bash
/usr/sbin/nologin

Configure a system to use time services


RHEL 7 has 3 command-line utilities to configure the system date and time:
1. date
2. hwclock
3. timedatectl
date command
Use the date command to display or set the system date and time. Run the date command with no arguments to
display the current date and time:
# date
Mon Sep 12 19:41:40 IST 2016
The date command provides a variety of output formatting options. You can also time and date in future or past. Few
examples are given below.
1. Display day of the week :
# date +%A
Monday
2. Display date one year from now :
# date -d "1 year"
Mon Sep 12 19:47:49 IST 2017
3. Display 1 month past date :
# date -d "1 month ago"
Mon Aug 12 19:49:07 IST 2016
Use the following syntax to change the current date. Replace YYYY with a four-digit year, MM with a two-digit
month, and DD with a two-digit day of the month.
# date +%D -s [YYYY-MM-DD]
Use the following syntax to change the current time. Replace HH with a two-digit hour, MM with a two-digit
minute, and SS with a two-digit second. Include either AM or PM. Include the –u option if your system clock is set
to use UTC.
# date +%T%p -s [HH:MM:SS]AM|PM –u
hwclock command
Use the hwclock command to query and set the hardware clock, also known as the RTC (real-time clock). This clock
runs independently of any control program running in the CPU and even when the machine is powered off. The
hwclock command allows you to:
Display the current time
Set the hardware clock to a specified time
Set the system time from the hardware clock (hwclock –s)
Set the hardware clock to the current system time (hwclock –w)
timedatectl command
– The timedatectl utility is part of the systemd system and service manager.
– To display local, universal, and RTC time and time zone, NTP configuration, and DST information:
# timedatectl
Local time: Tue 2016-09-13 20:30:26 IST
Universal time: Tue 2016-09-13 15:00:26 UTC
RTC time: Tue 2016-09-13 15:00:26
Time zone: Asia/Kolkata (IST, +0530)
NTP enabled: yes
NTP synchronized: yes
RTC in local TZ: no
DST active: n/a
– Use the following syntax to change the date and time:
# timedatectl set-time [YYYY-MM-DD]
# timedatectl set-time [HH:MM:SS]
– Use the following syntax to change the time zone:
# timedatectl set-timezone [time_zone]
– To list available time zones :
# timedatectl list-timezones
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
– To enable clock synchronization over NTP:
# timedatectl set-ntp yes
Using NTP
NTP provides a method of verifying and correcting your computer’s time by synchronizing it with another system.
To install NTP :
# yum install ntp
By default, there are four public server entries in the NTP configuration file, /etc/ntp.conf, which are specified by the
server directive.
# grep server /etc/ntp.conf
server 0.rhel.pool.ntp.org
server 1.rhel.pool.ntp.org
server 2.rhel.pool.ntp.org
server 3.rhel.pool.ntp.org
Instead of using a predefined public server, you can specify a local reference server in the /etc/ntpd.conf file. For
example:
# vi /etc/ntpd.conf
server 192.0.2.1
Another directive in the configuration file is driftfile. The default setting is as follows:
driftfile /var/lib/ntp/drift
This drift file contains one value used to adjust the system clock frequency after every system or service start.
NTP daemon
The ntpd program is the user space daemon that synchronizes the system clock with remote NTP time servers or
local reference clocks. The daemon reads the configuration file at system start or when the service is restarted. You
also need to open UDP port 123 in the firewall for NTP packets. After editing the /etc/ntp.conf file, use the systemctl
command to start the NTP daemon:
# systemctl start ntpd
Use the following command to ensure the NTP daemon starts at boot time:
# systemctl enable ntpd
Other NTP utilities
Use the ntpq command to query the NTP daemon operations and to determine performance. Use the –p option (or
peers command) to display a list of peers known to the server as well as a summary of their state. For example:
# ntpq -p
remote refid st t when poll reach delay offset jitter
==============================================================================
*10.10.0.2 192.168.2.11 2 u 911 1024 377 1.274 0.147 0.355
+10.10.0.3 192.168.2.11 2 u 1026 1024 377 1.161 0.073 0.852
The * indicates your system is synchronized with the 10.10.0.2 server. Use the ntpstat command to show network
time synchronization status.
# ntpstat
synchronised to NTP server (10.10.0.2) at stratum 3
time correct to within 31 ms
polling server every 1024 s
Configuring NTP using chrony
Chrony is a suite of utilities that provides another implementation of NTP. Chrony is designed for mobile systems
and virtual machines that are often powered down or disconnected from the network. Systems that are not
permanently connected to a network take a relatively long time to adjust their system clocks with the NTP daemon,
ntpd.
Chrony consists of chronyd, a daemon that runs in user space, and chronyc, a command- line program for making
adjustments to chronyd. The chronyd daemon makes adjustments to the system clock that is running in the kernel. It
uses NTP to synchronize with another system when network access is available. When network access is not
available, chronyd uses the last calculated drift stored in the drift file to synchronize the system time.
For more information on chrony (installation, configuration, troubleshooting), refer the below posts :
Configuring NTP using chrony
– Chrony provides another implementation of NTP.
– Chrony is designed for systems that are often powered down or disconnected from the network.
– The main configuration file is /etc/chrony.conf.
– Parameters are similar to those in the /etc/ntp.conf file.
– chronyd is the daemon that runs in user space.
– chronyc is a command-line program that provides a command prompt and a number of commands. Examples:
tracking: Displays system time information
sources: Displays information about current sources.
Installing Chrony
Install the chrony package by using the following command:
# yum install chrony
Use the following commands to start chronyd and to ensure chronyd starts at boot time:
# systemctl start chronyd
# systemctl enable chronyd
Configuring Chrony
A sample configuration would look like below :
# cat /etc/chrony.conf
server a.b.c offline
server d.e.f offline
server g.h.i offline
keyfile /etc/chrony.keys generatecommandkey
driftfile /var/lib/chrony/drift makestep 10 3
The parameters are described as follows:
server: Identifies the NTP servers you want to use. The offline keyword indicates that the servers are not contacted
until chronyd receives notification that the link to the Internet is present.
keyfile: File containing administrator password. Password allows chronyc to log in to chronyd and notify chronyd of
the presence of the link to the Internet.
generatecommandkey: Generates a random password automatically on the first chronyd start.
driftfile: Location and name of file containing drift data.
makestep: Step (start anew) system clock if a large correction is needed. The parameters 10 and 3 would step the
system clock if the adjustment is larger than 10 seconds, but only in the first three clock updates.
Although, all these parameters are not required. For this post purpose I am using only below two lines in the
configuration file.
# cat /etc/chrony.conf
server 192.0.2.1
allow 192.0.2/24
Starting chrony
Use the systemctl command to start the chrony daemon, chronyd.
# systemctl start chronyd
Verify
To check if chrony is synchronized, use the tracking, sources, and sourcestats commands. Run the chronyc tracking
command to check chrony tracking. Alternatively you could run chronyc to display a chronyc> prompt, and then run
the tracking command from the chronyc> prompt.
# chronyc tracking
Reference ID : 192.0.2.1 (192.0.2.1)
Stratum : 12
Ref time (UTC) : Fri Aug 05 19:06:51 2016
System time : 0.000823375 seconds fast of NTP time
Last offset : 0.001989304 seconds
RMS offset : 0.060942811 seconds
Frequency : 1728.043 ppm slow
Residual freq : 1.100 ppm
Skew : 94.293 ppm
Root delay : 0.000207 seconds
Root dispersion : 0.016767 seconds
Update interval : 65.1 seconds
Leap status : Normal
Some of the important fields are :
Reference ID: This is the reference ID and name (or IP address) if available, of the server to which the computer is
currently synchronized.
Stratum: The stratum indicates how many hops away from a computer with an attached reference clock you are.
Ref time: This is the time (UT C) at which the last measurement from the reference source was processed.
Run the chronyc sources command to display information about the current time sources that chronyd is accessing.
# chronyc sources
210 Number of sources = 1
MS Name/IP address Stratum Poll Reach LastRx Last sample
=============================================================================
^* 192.0.2.1 11 6 377 63 +1827us[+6783us]...
Some of the fields are described:
M: The mode of the source. ^ means a server, = means a peer, and # indicates
a locally connected reference clock.
S: The state of the sources. “*” indicates the source to which chronyd is currently synchronized. “+” indicates
acceptable sources that are combined with the selected source. “-” indicates acceptable sources that are excluded by
the combining algorithm. “?” indicates sources to which connectivity has been lost or whose packets do not pass all
tests. “x” indicates a clock that chronyd thinks is a false ticker, that is, its time is inconsistent with a majority of other
sources. “~” indicates a source whose time appears to have too much variability. The “?” condition is also shown at
start-up, until at least three samples have been gathered from it.
Name/IP address: This shows the name or the IP address of the source, or reference ID for reference clocks.
Run the chronyc sourcestats command. This command displays information about the drift rate and offset estimation
process for each of the sources currently being examined by chronyd.
# chronyc sourcestats
210 Number of sources = 1
Name/IP Address NP NR Span Frequency Freq Skew Offset Std Dev
==================================================================================
192.0.2.1 5 4 259 -747.564 1623.869 -2873us 30ms
Stop chrony
Use the systemctl command to stop the chrony daemon, chronyd.
# systemctl stop chronyd
Run the chronyc tracking command and notice chronyc cannot talk to the chronyd daemon.
# chronyc tracking
506 Cannot talk to daemon

Tips on Troubleshooting NTP / chrony Issues


The chrony service does not change the time
The often misconception is that the chrony service is setting the time to the one given by the NTP server. This is
incorrect – what actually happens is that based on the answer from the NTP server, chrony just tells the system clock
to go faster or slower. For this reason, sometimes even though the time is wrong and the NTP server is working, the
time does not get corrected immediately.
Only time when chrony sets time
When the chrony service starts, there are some settings in the /etc/chrony/chrony.conf file that tells it to actually set
the time if specific conditions occur:
# Force system clock correction at boot time.
makestep 1000 10
which means that if chrony detects during the first 10 measurements after its start that the time is off by more than
1000 seconds it will set the clock.
Some useful commands
Below are some useful commands which can be used for the troubleshooting of chrony related issues.
# chronyc tracking
# chronyc sources
# chronyc sourcestats
# systemctl status chronyd
# chronyc activity
# timedatectl
Check chronyd status
To check the status of the chronyd daemon :
# systemctl status -l chronyd
● chronyd.service - NTP client/server
Loaded: loaded (/usr/lib/systemd/system/chronyd.service; enabled; vendor preset: enabled)
Active: active (running) since Fri 2016-08-12 13:22:22 IST; 1s ago
Process: 33263 ExecStartPost=/usr/libexec/chrony-helper update-daemon (code=exited,
status=0/SUCCESS)
Process: 33259 ExecStart=/usr/sbin/chronyd $OPTIONS (code=exited, status=0/SUCCESS)
Main PID: 33261 (chronyd)
CGroup: /system.slice/chronyd.service
└─33261 /usr/sbin/chronyd

Aug 12 13:22:22 NVMBD1S11BKPMED03 systemd[1]: Starting NTP client/server...


Aug 12 13:22:22 NVMBD1S11BKPMED03 chronyd[33261]: chronyd version 2.1.1 starting (+CMDMON
+NTP +REFCLOCK +RTC +PRIVDROP +DEBUG +ASYNCDNS +IPV6 +SECHASH)
Aug 12 13:22:22 NVMBD1S11BKPMED03 chronyd[33261]: Frequency 0.000 +/- 1000000.000 ppm read
from /var/lib/chrony/drift
Aug 12 13:22:22 NVMBD1S11BKPMED03 systemd[1]: Started NTP client/server.
The chronyc sources command
Running chronyc sources -v shows the current state of the NTP server/s configured in the system. Here is an
example output, in which ntp.example.com shows as a valid server which is online:
# chronyc sources -v
210 Number of sources = 1

.-- Source mode '^' = server, '=' = peer, '#' = local clock.
/ .- Source state '*' = current synced, '+' = OK for sync, '?' = unreachable,
| / 'x' = time may be in error, '~' = time is too variable.
|| .- xxxx [ yyyy ] +/- zzzz
|| / xxxx = adjusted offset,
|| Log2(Polling interval) -. | yyyy = measured offset,
|| | zzzz = estimated error.
|| | |
MS Name/IP address Stratum Poll LastRx Last sample
============================================================================
^* ntp.example.com 3 6 40 +31us[ -98us] +/- 118ms
Note that a Source state different than ‘*’ usually indicates a problem with the NTP server.
Source state ‘~’ means that the time is too variable
If the Source state is ‘~‘, it probably means that the server is accessible but the time is too variable. This can happen
if the server responds too slow or responds sometimes slower and sometimes faster. You could check the response
time of the pings to the server to see if they are slow or variable. This state has also been noticed when the server is
running on virtual machines which are too slow causing timing issues.
Chrony check and restart every hour
Once an hour, the chrony service checks the output of the chronyc sources -v command, by running
script /usr/sbin/palladion_chrony_healthcheck which runs /usr/sbin/palladion_check_chrony and checks its output:
if /usr/sbin/palladion_check_chrony returns 1 – it means there was no online source (no source with Source state = ‘*’) ,
so chrony restarts in an attempt to re-initialize the server status
if /usr/sbin/palladion_check_chrony returns 0 – this means everything is ok, chrony does not need to be restarted
because it already has a valid online source
# cat /etc/cron.d/chrony
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
#
# Check chrony every hour and restart if necessary.
#
16 * * * * root /usr/sbin/palladion_chrony_healthcheck
Chrony logs
There are several chrony logs that can be used to troubleshoot. Most of them are located in /var/log/chrony/. Note that
the latest file is not always the *.log one. Sometimes it happens that even the *.log.2 or *.log.3 file are the ones that are
more recent. Here is an example of listing the files with sorting by the most recent:
# ls -lisaht /var/log/chrony/
total 1.5M
3801115 580K -rw-r--r-- 1 root root 574K Oct 21 14:56 measurements.log.3
3801131 544K -rw-r--r-- 1 root root 540K Oct 21 14:56 statistics.log.3
3801166 356K -rw-r--r-- 1 root root 350K Oct 21 14:56 tracking.log.3
3801089 4.0K drwxr-xr-x 16 root root 4.0K Oct 21 00:01 ..
3801114 4.0K drwxr-xr-x 2 root root 4.0K Oct 21 00:01 .
3801128 0 -rw-r--r-- 1 root root 0 Oct 21 00:01 tracking.log
3801110 0 -rw-r--r-- 1 root root 0 Oct 21 00:01 measurements.log
3801120 0 -rw-r--r-- 1 root root 0 Oct 21 00:01 statistics.log
3801167 0 -rw-r--r-- 1 root root 0 Oct 20 00:01 tracking.log.1
3801165 0 -rw-r--r-- 1 root root 0 Oct 20 00:01 statistics.log.1
3801159 0 -rw-r--r-- 1 root root 0 Oct 20 00:01 measurements.log.1
............
Try setting only one NTP server by entering its IP address
If until now you have been using two or more NTP servers (either because they were set or because you entered an
FQDN that resolves in different IP addresses), try to set one single NTP server by entering only one IP address. This may
solve your NTP related issue.
Tracing the communication with the NTP server
To double check if the NTP server is answering or not, it is possible to trace the traffic between chrony and the NTP
server for a period of time while monitoring the server:
1. Start a pcap trace with tcpdump on the NTP port 123 and leave it running until the issue appears (run it in ‘screen’ or
with ‘nohup’ to avoid it from being stopped if you disconnect from the shell command)
2. As soon as the issue re-appears, get a System Diagnostics covering the entire history since you have set the server to
DNS name until the gap reoccurred. If this produces a file that is too big, just get the System Diagnostics for Current data
and in addition copy all the files from /var/log/chrony/, and all files called /var/log/syslog* . Remember to stop the trace
you started at step 1
Schedule tasks using at and cron
– Linux can run tasks automatically, and comes with automated tasks utilities: cron, anacron, at, batch.
– cron jobs can run as often as every minute.
– A scheduled cron job is skipped if the system is down.
– anacron can run a job only once a day.
– Scheduled jobs are remembered and run the next time that the system is up.
– crond daemon searches multiple files and directories for scheduled jobs:
1. /var/spool/cron/
2. /etc/anacrontab
3. /etc/cron.d
Configuring cron jobs
cron jobs are defined in /etc/crontab.
The crontab entries are of the form:
Minutes Hours Date Month Day-of-Week command
where:
Minutes = [0 to 59]
Hours = [0 to 23]
Date = [1 to 31]
Month = [1 to 12]
Day-of-Week = [0 to 6] 0=Sunday - 6=Saturday
command = a script file or a shell command.
Other special characters can be used:
- An asterisk (*) can be used to specify all valid values.
- A hyphen (-) between integers specifies a range of integers.
- A list of values separated by commas (,) specifies a list.
- A forward slash (/) can be used to specify step values.
Other cron Directories and Files
/etc/cron.d
– Contains files with same syntax as the /etc/crontab – accessible by root privileges only
– Other cron directories in /etc: –
cron.hourly
cron.daily
cron.weekly
cron.monthly
– Scripts in these directories run hourly, daily, weekly, or monthly, depending on the name of the directory.
– The /etc/cron.allow and /etc/cron.deny files restrict user access to cron. If neither file exists, only root can use cron.
Crontab utility
– Users other that root can also configure cron using the crontab utility.
– user defined crontabs are stored in /var/spool/cron/[username].
– To create or edit a crontab entry :
# crontab -e
– To list the entries in the user defined crontab :
# crontab -l
Configuring anacron jobs
– anacron jobs are defined in /etc/anacrontab.
– Jobs are defined by :
Period in days : frequency of execution in days
Delay in minutes - Minutes to wait before executing the job
job-identifier - A unique name used in logfiles
command : a shell script or command to execute
example anacron file :
SHELL=/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# the maximal random delay added to the base delay of the jobs
RANDOM_DELAY=45
# the jobs will be started during the following hours only
START_HOURS_RANGE=3-22

#period in days delay in minutes job-identifier command


1 5 cron.daily nice run-parts /etc/cron.daily
7 25 cron.weekly nice run-parts /etc/cron.weekly
@monthly 45 cron.monthly nice run-parts /etc/cron.monthly
at and batch
– at and batch utilities are used for scheduling one-time tasks.
– the at command executes a task at a specific time.
– the batch command executes a task when system load average is below 0.8.
– the atd service must be running to run at or batch jobs
– at command syntax :
# at time
– The time argument accept multiple formats :
HH:MM
MMDDYY,MM/DD/YY or MM.DD.YY
month-name day year
midnight: At 12:00 AM
teatime: At 4:00 PM
now + time -- here time can be minutes, hours, days or weeks
– batch command syntax :
# batch (at> promp is displayed)
– The /etc/at.allow and /etc/at.deny files restrict user access to at. If neither file exists, only root can use cron.

Start, stop, and check the status of network services.


systemd service units
– Previous versions of Oracle Linux use scripts in the /etc/rc.d/init.d directory to control services.
– In Oracle Linux 7, these scripts have been replaced by systemd service units.
– Use the systemctl command to list information about service units.
To list all loaded service units:
# systemctl list-units --type service --all
To see which service units are enabled:
# systemctl list-unit-files --type service
Displaying the Status of Services
– systemd service units correspond to system services.
– To display detailed information about the httpd service:
# systemctl status httpd
– To check whether a service is running (active) or not running (inactive):
# systemctl is-active sshd
active
– To check whether a service is enabled:
# systemctl is-enabled sshd
enabled
Starting and stopping services
service Utility systemctl Utility Description

service name start systemctl start name Starts a service

service name stop systemctl stop name Stops a service


service name restart systemctl restart name Restarts a service

service name condrestart systemctl try- restart name Restarts a service only if it is running

service name reload systemctl reload name Reloads a configuration

service name status systemctl status name Checks whether a service is running

service –status- all systemctl list-units –type service –all Displays the status of all services
Enabling and disabling services
chkconfig Utility systemctl Utility Description

chkconfig name on systemctl enable name Enables a service

chkconfig name off systemctl disable name Disables a service

chkconfig –list systemctl status name, systemctl is-enabled Checks whether a service is enabled
name name

chkconfig –list systemctl list-unit-files –type service Lists all services and checks whether they are enabled

Create hard and soft links.


Soft links
As shown in the diagram soft links or symbolic links simply points to another file. It only contains the pathname of the
file to which it is pointing
1. Creation method
# touch file
# ln -s file link
# ls -l
-rw-r--r-- 1 root root 0 Sep 19 14:41 link
lrwxrwxrwx 1 root root 5 Sep 19 15:41 link -> file
The “l” in the “ls -l” command output above indicates that the file is a soft link.
2. The size of the soft link created in the example above is the no of characters in the pathname (file), which is 5 (it can
be absolute or relative).
3. If you delete the original file (file) the soft link render as useless.
4. Soft links can reside on different file systems.
5. You can create soft links to directories also.
Hard links
Every file uses atleast one hard link. So when you create a new file a new directory entry is created which is called link
count. So when you create a new hard link to this file the link count increaments by 1.

1. creation method
# touch file1
# ls -l
-rw-r--r-- 1 root root 0 Sep 23 13:19 file1
# ln file1 file2
# ls -l
-rw-r--r-- 2 root root 0 Sep 23 13:19 file1
-rw-r--r-- 2 root root 0 Sep 23 13:19 file2
# ls -li
1282 -rw-r--r-- 2 root 0 root 0 Sep 23 13:19 file1
1282 -rw-r--r-- 2 root 0 root 0 Sep 23 13:19 file2
# find . -inum 1282
./file1
./file2
2. The link count increases by one, everytime you create a new hard link to the file as shown above.
3. Even if you delete any one of the file, it has no effect on the other file. Only the link count decrements
4. Hard links can not cross the file system.
5. You can not create hard links to directories.

input / output redirection


Three standard file descriptors :
1. stdin 0 - Standard input to the program.
2. stdout 1 - Standard output from the program.
3. stderr 2 - Standard error output from the program.
Purpose Command

redirect std output to filename > filename or 1> filename

append std out to filename >> filename

append std out and std err to filename >> filename 2>&1 or 1>> filename 2>&1

take input from filename < filename or 0 < filename

redirect std error to filename 2> filename

redirect std out and std error to filename 1> filename 2>&1 or > filename 2>&1
Some examples of using I/O redirection
# cat goodfile badfile 1> output 2> errors
This command redirects the normal output (contents of goodfile) to the file output and sends any errors (about badfile
not existing, for example) to the file errors.
# mail user_id < textfile 2> errors
This command redirects the input for the mail command to come from file textfile and any errors are redirected to the
file errors.
# find / -name xyz -print 1> abc 2>&1
This command redirects the normal output to the file abc. The construct “2>&1” says “send error output to the same
place we directed normal output”.
Note that the order is important; command 2>&1 1>file does not do the same as command 1>file 2>&1. This is because
the 2>&1 construction means redirect standard error to the place where standard output currently goes. The
construction command 2>&1 1>file will first redirect standard error to where standard output goes (probably the
terminal, which is where standard error goes by default anyway) then will redirect standard output to file. This is
probably not what was intended.
# ( grep Bob filex > out ) 2> err
– any output of the grep command is sent to the file out and any errors are sent to the file err.
# find . -name xyz -print 2>/dev/null
This runs the find command, but sends any error output (due to inaccessible directories, for example), to /dev/null. Use
with care, unless error output really is of no interest.

#vi/vim editor
Inserting text
Command Action
i Insert text before current cursor position

a Append text after current cursor position

A Append text at the end of the current line

o Open new line below the current line

O Open new line above the current line


Navigating in vi
Command Action

left arrow / h move left 1 character

right arrow / l more right 1 character

up arrow / k move up 1 line

down arrow / j move down 1 line

$ move to the end of current line

0 move to beginning of current line


Deleting text
Command Action

x delete character at current cursor position

dw delete word or part of word to the right of cursor

dd delete current line

D Delete current line starting from the current cursor position


Undoing and repeating
Command Action

u undo the last command

. (dot) repeat the last command


Search and replace text
Command Action

/[string] Search forward for string

?[search] Search backward for string

n Find next occurrence of string

N find previous occurrence of string


:%s/old/new Search and replace first occurrence of string old with string new

:%s/old/new/g Search and replace all occurrence of string old with string new

cw Change the word staring from current cursor position

r Replace character at current cursor position

R Replace/overwrite text on current line


Copying and Pasting text
Command Action

yw Yank the current word in buffer

yy Yank the current line in buffer

p Paste the yanked data below the current line

P Paste the yanked data above the current line


Saving and quiting
Command Action

:w Write change into the file without quitting

:w! write change into the file even if you are not owner of the file

:wq write change into the file and quit

:wq! write change into the file and quit even if you are not owner of the file

:q quits when no changes are made

:q! quits without saving the changes made

S-ar putea să vă placă și