Solution:: Reading Crontab File
Solution:: Reading Crontab File
An important service provided by any system is the ability to run a process on a predetermined
schedule without human intervention. The “automation” of tasks can reduce the workload of
the system administrator significantly. Unfortunately Linux currently offers not one service but
potentially three—cron, anacron, and systemd timer units.
In about a page compare and contrast all three systems. Illustrate your discussion by using the
system files /etc/anacron and /etc/crontab and by constructing equivalent systemd service and
timer files.
Solution:
Linux has three main timer units namely Cron, Anacron and Systemd. There is a distinct set of
features that all of these time schedulers in Linux are built with. However, it is a fact that all of
these three are merely timers and the application of their usage is quite different from each
other.
Cron is a time based task scheduler program in Linux. Cron is specifically used in the
environment where the system has to be scheduled to very specific times, generally precisely
to the minutes and seconds. Tasks can run on particular dates, or repeat at periods as little as
consistently. Cron likewise permits clients in extensive national systems to assign the time zone
under which their tasks fall, to guarantee fitting execution utilizing local times.
Anacron can be considered as ‘Cron’ for laptops and desktops, as it processes in the same way
as the Cron. However the main difference between the cron and anacron is that, cron is used
for servers which are up for almost all their lifetime. Any task scheduled at any specific time
will thereby be executed by the cron; in case of laptops and desktops which are not up for all
the time. In such a case anacron is used, which executes the scheduled task is the system is up,
and let the process pasby if the system is off for that period.
System on the contrary is a session and system manager for Linux. Basically it consist of two
types of files that is, timers and services. Timers here can be an alternative Cron and Anacron,
as they do exactly the same processes that these two timers too; secondly are the services which
corresponds to the timers. Files ending with ‘.timer’ are timers, while those ending with
‘.service’ are to control files and events.
Reading Crontab file:
Crontab file located at ‘/etc/crontab’ consist of following lines of code:
SHELL=/BIN/SH
PATH=/USR/LOCAL/SBIN:/USR/LOCAL/BIN:/SBIN:/BIN:/USR/SBIN:/USR/BIN
# M H DOM MON DOW USER COMMAND
17 * * * * ROOT CD / && RUN-PARTS --REPORT /ETC/CRON.HOURLY
25 6 * * * ROOT TEST -X /USR/SBIN/ANACRON || (CD / && RUN-PARTS --REPORT /ETC/CRON.DAILY )
47 6 * * 7 ROOT TEST -X /USR/SBIN/ANACRON || ( CD / && RUN-PARTS --REPORT /ETC/CRON.WEEKLY )
52 6 1 * * ROOT TEST -X /USR/SBIN/ANACRON || ( CD / && RUN-PARTS --REPORT /ETC/CRON.MONTHLY )
From the code snippet above, “17 * ***” is the timing syntax. On a deep insight the whole
structure can be classified in minutes, seconds, hours, days, weeks and months by following
conventions:
M = Minute (0-59)
H = Hours (0-23)
DOM = Days of Month (1-31)
MON = Month (1-12)
DOW = Days of week (1-7)
Considering first line of code as an example to understand the syntax, “17 * ***”. This code
implies to a hourly cron job, but will start at 17th minute of every hour, that is 00:17, 01:17,
02:17…
Second sequence is “25 6 ***”; here it is a daily cron job that will start at 6:25 daily.
Third sequence is “47 6 **7”, this code reflect that the code is on a weekly schedule and will
run on last day of the week on 6:47.
Fourth sequence “52 6 1**”. Here the job is scheduled monthly. The event will be trigerred on
1 day of every month at time 6:52.
There are two other parameters left in the command, that is USER and COMMAND. User will
be the current user who is authenticated, while command will contain all the command that
would run on the command line.
Implementing on terminal:
himanshu@ubuntu:~$ env editor=nano crontab -e
crontab: installing new crontab
himanshu@ubuntu:~$ crontab -l
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
17 * * * * himanshu CD/&&RUN-PARTS--REPORT/ETC/CRON.HOURLY
Reading Anacrontab File:
# /etc/anacrontab: configuration file for anacron
# See anacron(8) and anacrontab(5) for details.
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# These replace cron's entries
1 5 cron.daily nice run-parts --report /etc/cron.daily
7 10 cron.weekly nice run-parts --report /etc/cron.weekly
@monthly 15 cron.monthly nice run -parts --report /etc/cron.monthly
It can be clearly seen from the crontab file contents that it contains fewer timing fields as
compared to the crontab file contents.
The first column corresponds the frequency of the execution of the tasks in days. Second
column is a delay time for the command execution, this is generally done so as to make sure
that the processes do not run explicitly at the same time.
Third field denotes the name, that the task has been called for; this is done to know specific
task. Fourth colum consist of the code, which will be executed in the command line.
According to the systemd functioning, two files will be required i.e. timing file and service file.
1. Service File:
Considering the daily task of cron job located at /etc/cron/daily_cron. Creating a service file
naming daily_cron.service, saved at either at “/etc/systemd/system/” or
“/usr/lib/systemd/system”. File has following contents:
[Unit]
Description=daily_cron
[Service]
Type=simple
ExecStart= /etc/cron/daily_cron
Here type can be altered to oneshot if the task is to be executed only once.
2. Timer file:
Creating a timer file with name “daily_cron.timer” and saving the same directory where
“daily_cron.service” was stored. The file contained following codes:
[Unit]
Description=Runs daily_cron every day
[Timer]
# Time to wait after booting before we run first time
OnBootSec=10min
# Time between running each consecutive time
OnUnitActiveSec=1d
Unit=daily_cron.service
[Install]
WantedBy=multi-user.target
Similalrly, the hourly, weekly, monthly and even yearly task can be configured using the above
commands to run at a specific time.
Implementing Commands:
systemctl enable daily_cron.timer
#starting the commands
systemctl start daily_cron.timer
#checking if timer is enabled
systemctl is-enabled daily_cron.timer
#checking if timer is running
systemctl is-active daily_cron.timer
#running script at any time
systemctl start daily_cron
Question 2
The web administrator of your organisation needs to login remotely to the machine that is running the
organisation’s public web site. You tell her that the only way to login is via The Secure Shell—which
she knows nothing about! Assuming she is logging in via a Linux boxwrite a help document for her
containing the following—
a. (6 marks) A short introduction to SSH, explaining why it is the preferred way of logging into a
remote machine—this explanation will need to discuss symmetric and asymmetric key encryption.
Answer:
(a) Secure Shell is a project to log into another PC over a network, to execute commands in a
remote machine, and to transfer files from one computer to another. It gives solid verification
and secure interchanges over insecure channels. SSH permits a client to run commands on a
machine's command prompt without them being in person present close to the machine.
Common applications of SSH incorporate remote command line login and remote order
execution, yet any network administration can be secured with SSH.
Now as this process is all about logging into remote device, remaining secure while sending and
reciving data through network is of utmost importance. So the data sent needs to be encrypted. These
encryptions are carried out by namely two encryption techniques:
(i) Symmetric Key Encryption: This is the best known encryption technique which uses
simple concept of applying manipulations to data to be encrypted in a particular manner
so that the whole original data is modified. This can be shifted of letters and numbers in
the data or exchange of letters or a complex string multiplication. But the problem lies in
disclosure of this key used. As if someone undesired gets this key then he/she can decrypt
the data and hence anybody can easily sniff through the data.
(ii) Asymmetric Key encryption: The problem faced by symmetric key encryption can be
removed by using asymmetric key encryption. Asymmetric key encryption provides two
different keys in place of one common key. First key is the Public key which is made
public and second key is the private key, which is kept private. Data encrypted using
Public Key can only be decrypted by the use of Private Key. So know there is no need of
worries for key to be made public as they are already public.
SSH is preferred way of logging into remote machine as it uses the asymmetric key encryption
technique which protects data from sniffing attacks and is much more secure than other programs like
telnet which uses symmetric key encryption or no encryptions.
(b) The ~./ssh/known_hosts file contains keys for the known hosts or the hosts which already
connected in the past. Whenever a connection is made the key stored is matched with the key from
remote server and if they matches connection is made else error message is shown. Further new keys
can be added for new remote connection manually or automatically by the SSH.
Contents of ~./ssh/known_hosts file:
,...,192.0.2.53 1024 37 159...93
,192.0.2.10 ssh-rsa AAAA1234.....=
|1|JfKTdBh7rNbXkVAQCRp4OQoPfmI=|USECr3SWf1JUPsms5AqfD5QfxkM= ssh-rsa
AAAA1234.....
Population of ~./ssh/known_hosts: For adding keys or new hosts to known_hosts file various methods
can be used. For example:
The command: “ ssh -o StrictHostKeyChecking=no [email protected]” adds new host without stricktly
checking.
ssh-keygen -R [hostname]
ssh-keygen -R [ip_address]
ssh-keygen -R [hostname],[ip_address]
ssh-keyscan -H [hostname],[ip_address] >> ~/.ssh/known_hosts
ssh-keyscan -H [ip_address] >> ~/.ssh/known_hosts
ssh-keyscan -H [hostname] >> ~/.ssh/known_hosts
Usage of keys by SSH: as already stated whenever a SSH connection is attempted, the key sent from remote
server is matched against all of the keys present in this known_hosts file and if there is a match then the host is
the matching host entry which the key belongs to.
Man in the Middle attack: The name Man in the middle speaks for itself. I this attack a person sits in between
the information exchange of two users or machines. So whenever an unencrypted data is sent he/she can easily
access the personal data between the two. For encrypted data requiring public keys, the person can easily get
public keys of both users when they exchange the public keys and can manipulate the sent data.
The hostnames in the file are hashed due to security reasons, as if someone somehow comes to know the user
account details or have access to the machine, then he can open this known_hosts file and will easily find out
which all hosts are connected to that particular machine if the hostnames are not hashed.
Removing any old host name from the file known_hosts is very easy task and can be done with a simple
command line ssh-keygen command:
ssh-keygen -R hostname
We have to just specify the hostname and it would be removed from the known_hosts file.
(c) Configuring access so that no password is needed:
For this process first asymmetric keys are needed to be setup which will be done by following
command:
ssh-keygen -t rsa
This commands creates a pair of private and public key for the usage. As the name syntax suggests
it’s a kind of key generator.
After this there will be series of steps:
Enter file in which to save the key (/home/user/.ssh/id_rsa):
The text in command output is self-explanatory. We need to specify the file in which we need to save
the generated key.
The next step is making your key passphrase protected.
Enter passphrase (empty for no passphrase):
Passphrasing enables enhanced security to the key. If someone hacked into your key he/she will still
be unable to use it as it is passphrase protected. I.e. it will ask for passphrase each time and unable to
do so will result in no access.
Output for key Generation process:
ssh-keygen -t rsa
4a:dd:0a:c6:35:4e:3f:ed:27:38:8c:74:44:4d:93:67 user@a
| .oo. |
| . o.E |
| +. o |
| .==. |
| =S=. |
| o+=+ |
| .o+o. |
| .o |
| |
+-----------------+
Next step is to copy this generated public key to ~./ssh/authorized_keys
cat ~/.ssh/id_rsa.pub | ssh [email protected] "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
The authorized key file contains the list of public keys which are used each time process is carried
out.
Example of authorized_keys file:
ssh-rsa AAAAB3Nza...Link== [email protected]
from="*.user2.example.com,!pc.user2.example.com" ssh-rsa
AAAAB2...19Q== [email protected]
command="dump /home",no-pty,no-port-forwarding ssh-dss
AAAAC3...51R== example.com
permitopen="192.0.2.1:80",permitopen="192.0.2.2:25" ssh-dss
AAAAB5...21S==
tunnel="0",command="sh /etc/netstart tun0" ssh-rsa AAAA...==
[email protected]
ssh-agent: Holds the private key from the generated private and public key pair. For every session
login private key from this ssh-agent is used to decrypt the data encrypted by the public key.
ssh-add: Adds RSA identities to the authentications agent. If passphrase is required it will ask for the
passphrase and will add files accordingly.
Question 3
A user comes to you requesting that you create and implement a backup policy for his desktop
machine. What he wants, is to be able to place a blank DVD in his Single-Sided DVD-burner
at the end of the working day on a Friday and have all the files he has been working on for the
week backed up automatically that evening to the DVD!
Solution:
Comprehensively, we can recognize two sorts of backup; the system backup, which is a
backup of the working system and applications (the things just the sysadmin can change), and
the user backup, which is a backup of the users' documents (I don't know whether any other
individual uses these terms, yet they'll accomplish for the reasons of this article). As we
should see, system backups and user backups ought to be dealt with in an unexpected way.
System Backups:
The purpose behind making system backups is to minimize the exertion presupposed, after an
accident, to get the system up and running as it was before fiasco struck. Notwithstanding,
you would prefer not to spend a large portion of your life moving down your circle; nobody
said it was enjoyable! The way to going down adequately is to go down just that which is
completely important to empower rapid recuperation when calamity strikes.
User Backups:
User backups are unique in relation to system backups, in that a user's records are at risk to
change much of the time. It will probably be incomprehensible for you to have up-to-the-
moment backups of a given user's document space, and you shouldn't even attempt. In
moving up user records, you are putting forth your users a virtual wellbeing net—sensibly
late duplicates of their documents they can fall back on the off chance that they do something
senseless (like rm * bak rather than rm *.bak—it does happen!), or if the hard circle falls.
Implementation:
The implementation involves following steps:
Firstly, the files and the directories which needs to be backuped are identified and the
whole tree is taken for backup.
Now, the directory or the files to be backedup are archived in TAR format and stored
locally before writing onto the optical disk.
As per the given condition the backup needs to be active enough and needs to trace
out the alterations made by the user, prior to the backup. For this specific
scripts/commands needs to be inherited.
Final step concludes of using ‘systemd’ timer for automatically backing up the
archives to the optical drives.
Suppose a lot of software have been installed in the directory ‘usr/local’, now the backup of
the whole tree needs to be done. Command for this would be:
$ tar –cWMF /dev/fd0 /usr/local
Here c means create an archive, W to verify the archive, M for managing the disks and F for
specifiying the directory for backup. In this case it is a DVD drive. Thus after creating the
backup the archives will be needed to be burned onto the optical disk.
An alternative approach can also be followed as:
$ find /home -cnewer /etc/last_backup \
-type f i-print > back_these_up
$ tar -cf /dev/ftape -T back_these_up
$ touch /etc/last_backup
The above command will automatically backup files everytime any file is altered. Here the
location of the backup can be changed, although it is for now a temporary location as the files
needs to be written on to optical disk.
Now as per the given condition, all the backups needs to be made on a weekly basis on every
Friday. Here we can make use system times and service files configuration.
Service File:
Creating a service file naming weeklyBackup.service, saved at either at
“/etc/systemd/system/” or “/usr/lib/systemd/system”. File has following contents:
[Unit]
Description=weeklyBackup
[Service]
Type=simple
ExecStart= /usr/bin/sh -c 'for i in $(grep btrfs /proc/mounts | cut -f2 -d" "); do echo
scrubbing $i; btrfs scrub start -Bd $i; done'
IOSchedulingClass=idle
CPUSchedulingPolicy=idle
Timer File:
Creating a timer file with name “weeklyBackup.timer” and saving the same directory where
“weeklyBackup.service” was stored. The file contained following codes
[Unit]
Description=Runs weeklyBackup every week on friday
[Timer]
# Time to wait after booting before we run first time
OnBootSec=10min
# for running the backup at every Friday on 00:01
OnCalendar=Fri, 00:01
Unit=daily_cron.service
[Install]
WantedBy=multi-user.target
References:
Http://www.digitaliocean.com/community/tutorials/how-to-set-up-ssh-keys--2
Http://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys--2
https://www.digitalocean.com/community/tutorials/understanding-the-ssh-encryption-and-
connection-process
https://wiki.archlinux.org/index.php/System_maintenance
https://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys--2
http://jason.the-graham.com/2013/03/06/how-to-use-systemd-timers/
http://linuxconfig.org/linux-cron-guide
http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800
http://www.thesitewizard.com/general/set-cron-job.shtml
http://www.logikdev.com/2010/05/25/using-the-date-command-in-your-crontab/
http://www.computerhope.com/unix/udate.htm
https://wiki.ubuntu.com/systemd