0% found this document useful (0 votes)
24 views59 pages

IT601 Week 4

The document covers user and group management in Linux, emphasizing the importance of effective user account management for system security. It explains the roles of the root user, the use of sudo for privilege escalation, and the management of user profiles and password policies. Additionally, it introduces OpenSSH for secure remote administration, detailing installation and configuration processes.

Uploaded by

shahrozarshad157
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views59 pages

IT601 Week 4

The document covers user and group management in Linux, emphasizing the importance of effective user account management for system security. It explains the roles of the root user, the use of sudo for privilege escalation, and the management of user profiles and password policies. Additionally, it introduces OpenSSH for secure remote administration, detailing installation and configuration processes.

Uploaded by

shahrozarshad157
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

IT601 – System and Network Administration

User Management
Arif Husen

Department of Computer Science and Information Technology,


Virtual University of Pakistan
User Management
➢ User management is a critical part of maintaining a secure system. Ineffective user and privilege
management often lead many systems into being compromised.
➢ it is important to understand how you can protect your server through simple and effective user
account management techniques.

➢ Root User
▪ Root is the superuser account in Unix and
Linux. It is a user account for administrative sudoer rights No sudoer rights
purposes, and typically has the highest
access rights on the system.
root limuser
▪ Usually, the root user account is called root .
However, in Unix and Linux, any account • Highest Privileges • Lowest Privileges
with user id 0 is a root account, regardless of
the name. admin
• Middle Privileges
Root user in Ubuntu
▪ In ubuntu server, administrative root account is disabled by default.
❑ This does not mean that the root account has been deleted or that it may not be
accessed. It merely has been given a password which matches no possible encrypted
value, therefore may not log in directly by itself
❑ Instead, users are encouraged to make use of a tool by the name of sudo to carry out
system administrative duties.
▪ sudo allows an authorized user to temporarily elevate their privileges using their own
password instead of having to know the password belonging to the root account.
❑ This simple yet effective methodology provides accountability for all user actions, and
gives the administrator granular control over which actions a user can perform with said
privileges.
▪ By default, the initial user created by the installer is a member of the group "sudo" which
is added to the file /etc/sudoers as an authorized sudo user.
▪ To give any other account full root access through sudo, simply add them to the sudo
group.
Enabling/disabling root

▪ If for some reason you wish to enable the root account, simply give it a password:
sudo passwd
▪ sudo will prompt you for your password, and then ask you to supply a new
password for root.

▪ To disable the root account password, use the following passwd syntax:
sudo passwd -l root
▪ However, to disable the root account itself, use the following command:
usermod --expiredate 1
▪ You should read more on sudo by reading the man page:
man sudo
User Management Operations
The process for managing local users and groups is straightforward and differs very little
from most other GNU/Linux operating systems. Ubuntu and other Debian based
distributions encourage the use of the "adduser" package for account management.

Add/Remove User Lock/Unlock User


sudo adduser username
sudo passwd -l username
• follow the prompts to give the account a password
and identifiable characteristics

sudo deluser username sudo passwd -u username


• delete a user account and its primary group

➢ Deleting an account does not remove their respective home folder. It is up to you
whether or not you wish to delete the folder manually or keep it according to your
desired retention policies.
Remember, any user added later on with the same UID/GID as the previous owner will
now have access to this folder if you have not taken the necessary precautions.
User Group Management

➢ A user can be assigned to group(s) based on their department or activities.

➢ A group allows a user special admgroup


access to system resources, usersGroup fingroup
such as files, directories, or
processes (programs) that are
running on the system. hrgroup
enggroup

➢ This group membership can also be used to


prevent access to system resources because margroup
several security features in Linux make use of
groups to impose security restrictions.
User Group Management
➢ Every user is a member of at least one group. This first group is called the user’s primary group. Any
additional groups a user is a member of are called the user’s secondary groups.
➢ Group membership can be displayed by executing either the id or groups command:
student@onecoursesource:~$ id
uid=1002(student) gid=1002(student)
groups=1002(student),60(games),1001(ocs)
student@onecoursesource:~$ groups
student games ocs
➢ Both the id and groups commands display information about the current user by default. Both commands
also accept an argument of another user account name:
student@onecoursesource:~$ id root
uid=0(root) gid=0(root) groups=0(root)
student@onecoursesource:~$ groups root
root : root
➢ The most important difference between primary and secondary group membership relates to when a user
creates a new file. Each file is owned by a user ID and a group ID.
➢ When a user creates a file, the user’s primary group membership is used for the group ownership of the
file:
Group information
➢ Group information is stored in several files:
▪ The /etc/passwd file contains user account information, including the primary group membership for
each user.
▪ The /etc/group file stores information about each group, including the group name, group ID (GID) and
secondary user membership.
student@onecoursesource:~$ grep student /etc/passwd
student:x:1002:1002::/home/student:
▪ The /etc/gshadow file stores additional information for the group, including group
administrators and the group password.
student@onecoursesource:~$ head /etc/group
root:x:0:
daemon:x:1:
bin:x:2:
sys:x:3:
adm:x:4:syslog,bo
tty:x:5:
disk:x:6:
lp:x:7:
mail:x:8:
news:x:9:
Special Groups
➢ A typical Linux system will have many default group Group Description

accounts. These default group accounts typically have


This group account is reserved for the system administrator. Do not add
GID values under 1000, making it easy for an root a regular user to this group because it will provide the regular user with
elevated access to system files.
administrator to recognize these as special accounts.
Members of this group typically have access to files related to system
monitoring (such as log files). Being able to see the contents of these
adm
files can provide more information about the system than a regular user
➢ Additionally, if you add new software to the system, would typically have.

more groups may be added as software vendors make


This is one of many groups (including tty, mail, and cdrom) used by the
use of both user and group accounts to provide operating system to provide access to specific files. Typically, regular
lp
users are not added to these groups because they are used by
controlled access to files that are part of the software. background processes called daemons.

➢ Administrators who are focused on security should be sudo This group is used in conjunction with the sudo command.

aware of these special group accounts because these


accounts can provide either security features or pose staff
A default group that was traditionally used on Unix systems but is rarely
used in modern Linux distributions.
security threats.
users A default group that is rarely used in modern Linux distributions.

A group that was traditionally used on Unix systems for users who
operators required elevated privileges for specific system tasks. This group is
rarely used in modern Linux distributions.
Adding Removing Groups

➢ To add or delete a personalized group, use the following syntax, respectively:

sudo addgroup groupname


sudo delgroup groupname

➢ To add a user to a group, use the following syntax:


sudo adduser username groupname
IT601 – System and Network Administration

User Level Security


Arif Husen

Department of Computer Science and Information Technology,


Virtual University of Pakistan
User Profile Security
➢ When a new user is created, the adduser utility creates a new home directory named /home/username.
▪ The default profile is modeled according to contents of /etc/skel, which includes all profile basics.
▪ For multiuser environment, close attention is required to the user home directory permissions to ensure
confidentiality.
➢ By default, user home directories in Ubuntu are created with world read/execute permissions.
▪ This means that all users can browse and access the contents of other user’s home directories.
➢ To verify your current user home directory permissions, use the following syntax:
ls -ld /home/username
drwxr-xr-x 2 username username 4096 2007-10-02 20:03 username

Numeric 7 5 5
Binary 1 1 1 1 0 1 1 0 1

d r w x r - x r - x 2 userid groupid 4096 2023-1-1 20:03 username

Modified
Owner
User Other
Owner

Group
Group
No. of

name
Links
Type

User

Last
Size
File

File

File
User Profile Security

➢ To remove the world readable-permissions, following command can be used.


sudo chmod 0750 /home/username
➢ The efficient approach is to modify the adduser global default permissions when creating user home folders.
Simply edit the file /etc/adduser.conf and modify the DIR_MODE variable to something appropriate, so that all
new home directories will receive the correct permissions.

DIR_MODE=0750

ls -ld /home/username

drwxr-x--- 2 username username 4096 2007-10-02 20:03 username


Password Policy

➢ A strong password policy is one of the most important aspects of your security posture. Many successful
security breaches involve simple brute force and dictionary attacks against weak passwords.

➢ To offer any form of remote access involving your local password system, make sure you adequately
address

▪ Minimum password complexity requirements


▪ Maximum password lifetimes
▪ Frequent audits of your authentication systems
Password Expiry
➢ When creating user accounts, you should make it a policy to have a minimum and maximum password age
forcing users to change their passwords when they expire.

➢ To easily view the current status of a user account, use the following syntax:

sudo chage -l username


Last password change : Jan 20, 2015
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 set any of these values, simply use the following syntax, and follow the interactive prompts:

sudo chage username

➢ Example : Change the explicit expiration date (-E) to 01/31/2015, minimum password age (-m) of 5 days,
maximum password age (-M) of 90 days, inactivity period (-I) of 30 days after password expiration, and a
warning time period (-W) of 14 days before password expiration:

sudo chage -E 01/31/2015 -m 5 -M 90 -I 30 -W 14 username


Other Considerations
➢ Many applications use alternate authentication mechanisms that can be easily. It is important to understand
and control how users authenticate and gain access to services and applications on your server.
➢ SSH Access by Disabled Users
▪ Simply disabling/locking a user account will not prevent a user from logging into your server remotely if
they have previously set up RSA public key authentication.
▪ They will still be able to gain shell access to the server, without the need for any password.
▪ Remember to check the users home directory for files that will allow for this type of
authenticated SSH access, e.g. /home/username/.ssh/authorized_keys.
▪ Remove or rename the directory .ssh/ in the user's home folder to prevent further SSH
authentication capabilities.
▪ Be sure to check for any established SSH connections by the disabled user, as it is
possible they may have existing inbound or outbound connections. Kill any that are found.
who | grep username (to get the pts/# terminal)
sudo pkill -f pts/#
▪ Restrict SSH access to only required user accounts. You may create a group called "sshlogin" and add the
group name as the value associated with the AllowGroups variable located in the file /etc/ssh/sshd_config.
AllowGroups sshlogin
➢ External User Database Authentication
IT601 – System and Network Administration

< End>
Arif Husen

Department of Computer Science and Information Technology,


Virtual University of Pakistan
IT601 – System and Network Administration

Remote Administration
Arif Husen

Department of Computer Science and Information Technology,


Virtual University of Pakistan
OpenSSH

➢ This topic introduces a powerful collection of tools for the remote control of, and transfer of
data between, networked computers called OpenSSH.

➢ OpenSSH is a freely available version of the Secure Shell (SSH) protocol family of tools for remotely controlling, or
transferring files between, computers.

➢ Traditional tools used to accomplish these functions, such as telnet or rcp, are insecure and transmit the user's
password in cleartext when used.
➢ OpenSSH provides a server daemon and client tools to facilitate secure, encrypted remote control and file transfer
operations, effectively replacing the legacy tools.
OpenSSH

➢ The OpenSSH server component, sshd, listens continuously for client connections from any of the client tools.

➢ When a connection request occurs, sshd sets up the correct connection depending on the type of client
tool connecting.

▪ if the remote computer is connecting with the ssh client application, the OpenSSH server sets up a
remote control session after authentication.
▪ If a remote user connects to an OpenSSH server with scp, the OpenSSH server daemon initiates a secure
copy of files between the server and client after authentication.

➢ OpenSSH can use many authentication methods, including plain password, public key, and Kerberos tickets.
Install OpenSSH

➢ Installation of the OpenSSH client and server applications is simple.

▪ To install the OpenSSH client applications on your Ubuntu system, use this command at a terminal
prompt:
sudo apt install openssh-client

▪ To install the OpenSSH server application, and related support files, use this command at a terminal prompt:

sudo apt install openssh-server

➢ Configuring the OpenSSH

▪ You may configure the default behavior of the OpenSSH server application, sshd, by editing the file
/etc/ssh/sshd_config.

▪ For information about the configuration directives used in this file, you may view the appropriate
manual page with the following command, issued at a terminal prompt:

man sshd_config
Configuring the OpenSSH
➢ There are many directives in the sshd configuration file controlling such things as communication
settings, and authentication modes.
➢ Example configuration : Various directives that can be changed by editing the /etc/ssh/sshd_config file.

1. Copy the /etc/ssh/sshd_config file and protect it from writing sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.original
1 with the following commands, issued at a terminal prompt:
sudo chmod a-w /etc/ssh/sshd_config.original

1. To set your OpenSSH to listen on TCP port 2222 instead of Port 2222
2 the default TCP port 22, change the Port directive as such:

▪ To have sshd allow public key-based login credentials, PubkeyAuthentication yes


3 simply add or modify the line:

▪ To make your OpenSSH server display the contents of the Banner /etc/issue.net
4 /etc/issue.net file as a pre-login banner, simply add or
modify the line In the /etc/ssh/sshd_config file.

▪ After making changes to the /etc/ssh/sshd_config file, save sudo systemctl restart sshd.service
5 the file, and restart the sshd server application to effect the
changes using the following command at a terminal prompt:
SSH Keys
➢ SSH keys allow authentication between two hosts without the need of a password. SSH key authentication
uses two keys, a private key and a public key.

▪ To generate the keys, from a terminal prompt enter:


ssh-keygen -t rsa
This will generate the keys using the RSA Algorithm. During the process you will be prompted for a
password. Simply hit Enter when prompted to create the key.

▪ By default the public key is saved in the file ~/.ssh/id_rsa.pub, while ~/.ssh/id_rsa is the private key. Now copy
the id_rsa.pub file to the remote host and append it to ~/.ssh/authorized_keys by entering:
ssh-copy-id username@remotehost
▪ Finally, double check the permissions on the authorized_keys file, only the authenticated user should
have read and write permissions. If the permissions are not correct change them by:

chmod 600 .ssh/authorized_keys

▪ You should now be able to SSH to the host without being prompted for a password.
Puppet
➢ Puppet is a cross platform framework enabling system administrators to perform common tasks using code.
➢ The code can do a variety of tasks from installing new software, to checking file permissions, or updating
user accounts.
➢ Puppet is great not only during the initial installation of a system, but also throughout the system’s entire
life cycle. In most circumstances puppet will be used in a client/server configuration.
➢ Puppet uses a client-server approach and consists of
the following systems:

▪ The Puppet Master is a server with the Puppet Master daemon that manages
crucial system information for all nodes using manifests.

▪ The Puppet Agents are nodes with Puppet installed on them with the Puppet Agent
daemon running.
Puppet

➢ Puppet utilizes a client/server architecture consisting of the Puppet Master and Puppet Agents. Puppet
Agents uses pull mode to poll the master and retrieve node-specific and site-specific configuration info.

➢ The topology goes through the following steps:


1 - A node running a Puppet Agent daemon
gathers all the information (facts) about
itself, and the agent sends the facts to the
Puppet Master.

2 - The Puppet Master uses the data to


create a catalog on how the node should
be configured and sends it back to the
Puppet Agent.

3 - The Puppet Agent configures itself


based on the catalog and reports back to
the Puppet Master.
Installing and Configuring Puppet
➢ Prior to configuring puppet you may want to add a DNS CNAME record for puppet.example.com, where
example.com is your domain.
➢ By default Puppet clients check DNS for puppet.example.com as the puppet server name, or Puppet
Master.
➢ If you do not wish to use DNS, you can add entries to the server and client /etc/hosts file. For example, in
the Puppet server's /etc/hosts file add:

127.0.0.1 localhost.localdomain localhost puppet


192.168.1.17 puppetclient.example.com puppetclient

➢ On each Puppet client, add an entry for the server:

192.168.1.16 puppetmaster.example.com puppetmaster puppet

➢ To install Puppet, in a terminal on the server enter:


sudo apt install puppetmaster

➢ On the client machine, or machines, enter:


sudo apt install puppet
Installing and Configuring Puppet
➢ Create a folder path for the apache2 class:
sudo mkdir -p /etc/puppet/modules/apache2/manifests
➢ Now setup some resources for apache2. Create a file /etc/puppet/modules/apache2/manifests/init.pp
containing the following:

➢ Next, create a node file /etc/puppet/code/environments/production/manifests/site.pp with:

➢ The final step for this simple Puppet server is to restart the daemon:
sudo systemctl restart puppetmaster.service
Installing and Configuring Puppet
➢ Now everything is configured on the Puppet server, it is time to configure the client.
▪ First, configure the Puppet agent daemon to start. Edit /etc/default/puppet, changing START to yes:
START=yes
▪ Then start the service:
sudo systemctl start puppet.service
▪ View the client cert fingerprint
sudo puppet agent --fingerprint

▪ Back on the Puppet server, view pending certificate signing requests:


sudo puppet cert list
▪ On the Puppet server, verify the fingerprint of the client and sign puppetclient's cert:
sudo puppet cert sign puppetclient.example.com
▪ On the Puppet client, run the puppet agent manually in the foreground. This step isn't strictly
speaking necessary, but it is the best way to test and debug the puppet service.
sudo puppet agent --test
▪ Check /var/log/syslog on both hosts for any errors with the configuration. If all goes well the apache2
package and it's dependencies will be installed on the Puppet client.
Zentyal
➢ Zentyal is a Linux small business server that can be configured as a gateway, infrastructure manager,
unified threat manager, office server, unified communication server or a combination of them.

Integrated
▪ All network services managed by Zentyal are tightly integrated, automating most tasks.
• This saves time and helps to avoid errors in network configuration and administration.

Opensource
• Zentyal is open source, released under the GNU General Public License (GPL) and runs on top of Ubuntu GNU/Linux.
• Zentyal consists of a series of packages (usually one for each module) that provide a web interface to configure the
different servers or services.
• Zentyal publishes one major stable release once a year based on the latest Ubuntu LTS release.

Configuration
• The configuration is stored on a key-value Redis database, but users, groups, and domains-related configuration
is on OpenLDAP.
• When you configure any of the available parameters through the web interface, final configuration files are
overwritten using the configuration templates provided by the modules.

Advantage
• The main advantage of using Zentyal is a unified, graphical user interface to configure all network services and
high, out-of-the-box integration between them.
Installing and Configuring Zantyal

➢ Create a new user to access the Zentyal web interface, run:


sudo adduser username sudo

➢ Add the Zentyal repository to your repository list:


sudo add-apt-repository "deb http://archive.zentyal.org/zentyal 3.5 main extra"

➢ Import the public keys from Zentyal:


sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 10E239FF
wget -q http://keys.zentyal.org/zentyal-4.2-archive.asc -O- | sudo apt-key add -
➢ Update your packages and install Zentyal:
sudo apt update
sudo apt install zentyal

➢ During installation you will be asked to set a root MySQL password and confirm port 443.
Installing and Configuring Zantyal
➢ Any system account belonging to the sudo group is allowed to log into the Zentyal web interface. The
user created while installing Ubuntu Server will belong to the sudo group by default.

➢ To access the Zentyal web interface, point a browser to https://localhost/ or to the IP address of your
remote server.

➢ As Zentyal creates its own self-signed SSL certificate, you will have to accept a security exception on
your browser. Log in with the same username and password used to log in to your server.

➢ Once logged in you will see an overview of your server. Individual modules, such as Antivirus or Firewall,
can be installed by simply clicking them and then clicking Install. Selecting server roles like Gateway or
Infrastructure can be used to install multiple modules at once.
IT601 – System and Network Administration

Logging
Arif Husen

Department of Computer Science and Information Technology,


Virtual University of Pakistan
Logging
➢ Logging refers to record keeping of information about events that occur
in a computer system, such as problems, errors or just information on
current operations.

Kernel Space
▪ Different types of events may occur in the operating RAM
system or in other software.
Disk
➢ These log messages can then be used to monitor and understand
the operation of the system, to debug problems, or during an Ring Buffer
audit.

➢ Logging is particularly important in multi-user software, to have a Socket Communications System Calls
central overview of the operation of the system.

➢ On Linux, you have two types of logging mechanisms :


Processes

User Space
▪ Kernel logging: related to errors, warning or information entries files
that your kernel may write
▪ User logging: linked to the user space, those log entries are related Log Files
to processes or services that may run on the host machine.
Kernel Logging
➢ On the kernel space, logging is done via the Kernel Ring Buffer. The ring buffer is a circular buffer that is
the first datastructure storing log messages when the system boots up.
▪ When starting Linux machine, if log messages are displayed on the screen, those
messages are stored in the kernel ring buffer.
▪ The Kernel logging is started before user logging
▪ The kernel ring buffer, pretty much like any other log files on your system can be inspected.
▪ In order to open Kernel-related logs on your system, you have to use the “dmesg” command.
Example of events : Errors in mounting a disk, Driver Loading etc

syslog rsyslog Logging Tools


CLI dmesg
Reading/Writing reading

Systemd-journal /dev/kmsg
/proc/kmsg
Reading/Writing User space

Kernel space
Dumps data in
printk Ring Buffer
Log files locations
➢ There are many different log files that all serve different purposes. When trying to find a log about
something, you should start by identifying the most relevant file.

➢ System logs

Auth log Daemon Log Debug log Kernel log System log

/var/log/auth.log /var/log/daemon.log /var/log/debug /var/log/kern.log /var/log/syslog

➢ Application logs

Apache logs X11 server logs Print System Logs Rootkit Hunter Log SMB Logs
/var/log/apache2/ /var/log/Xorg.0.log /var/log/cups/error_log /var/log/rkhunter.log /var/log/samba

➢ Non-human-readable logs

Login failures log Last logins log Login records log


/var/log/faillog /var/log/lastlog /var/log/lastlog
Viewing and monitoring log files
➢ The most basic way to view files from the command line is using the cat command. You simply pass in the
filename, and it outputs the entire contents of the file: cat file.txt.
➢ Viewing the start or end of a file
▪ It is generally required to quickly view the first or last n number of lines of a file.
▪ the head and tail commands come in handy.
▪ These commands work much like cat, although you can specify how many lines from the start/end of the file you want to view.
▪ To view the first 15 lines of a file, run head -n 15 file.txt, and to view the last 15, run tail -n 15 file.txt.
▪ Due to the nature of log files being appended to at the bottom, the tail command will generally be more useful.

➢ Monitoring files
▪ To monitor a log file, you may pass the -f flag to tail. It will keep running, printing new additions to the file, until you stop it (Ctrl + C).
For example: tail -f file.txt.

➢ Searching files
▪ One way that we looked at to search files is to open the file in less and press /.
▪ A faster way to do this is to use the grep command.
▪ We specify what we want to search for in double quotes, along with the filename, and grep will print all the lines containing that
search term in the file. For example, to search for lines containing “test” in file.txt, you would run grep "test" file.txt.
▪ If the result of a grep search is too long, you may pipe it to less, allowing you to scroll and search through it: grep "test" file.txt | less.
System Logging Daemon (syslogd)
➢ The system logging daemon syslogd, also known as sysklogd, awaits logging messages from numerous
sources and routes the messages to the appropriate file or network destination.
▪ Messages logged to syslogd usually contain common elements like system hostnames and time-stamps
in addition to the specific log information.

➢ Configuration of syslogd
▪ The syslogd daemon's configuration file is /etc/syslog.conf.
▪ Each entry in this file consists of two fields, the selector and the action.
▪ The selector field specifies a facility to be logged, such as for example the auth facility which deals
with authorization, and a priority level to log such information at, such as info, or warning.
▪ The action field consists of a target for the log information, such as a standard log file (i.e.
/var/log/syslog), or the hostname of a remote computer to send the log information to.
Log Rotation
➢ When viewing directory listings in /var/log or any of its subdirectories, you may encounter log files with
names such as daemon.log.0, daemon.log.1.gz, and so on.
▪ What are these log files? They are 'rotated' log files. That is, they have automatically been renamed
after a predefined time-frame, and a new original log started. After even more time the log files are
compressed with the gzip utility as in the case of the example daemon.log.1.gz.

➢ The purpose of log rotation is to archive and compress old logs so that they consume less disk space, but
are still available for inspection as needed.
➢ Typically, logrotate is called from the system-wide cron script /etc/cron.daily/logrotate, and further defined by
the configuration file /etc/logrotate.conf. Individual configuration files can be added into /etc/logrotate.d
Log Rotation
➢ Log files that have zeroes appended at the end are rotated files. That means log file names have automatically
been changed within the system.
➢ logrotate handles systems that create significant amounts of log files. The command is used by the cron
scheduler and reads the logrotate configuration file /etc/logrotate.conf. It’s also used to read files in the
logrotate configuration directory.
var/log/log name here].log {
Missingok
Notifempty
Compress
Size 20k
Daily
Create 0600 root root
}

➢ The commands perform the actions as follows:


▪ missingok – Tells logrotate not to output an error if a log file is missing
▪ notifempty – Does not rotate the log file if it is empty. It reduces the size of the log file with gzip
▪ size – Ensures that the log file does not exceed the specified dimension and rotates it otherwise
▪ daily – Rotates the log files on a daily schedule. This can also be done on a weekly or monthly schedule
▪ create – Instantiates a log file where the owner and group are a root user
Logging related commands
1) dmesg . the dmesg kernel ring buffer utility

2) faillog, the faillog command (and also the faillog configuration file via man 5 faillog)

3) grep , the grep pattern searching utility

4) head , the head utility

5) klogd, the kernel log daemon (klogd)

6) last , the last command which shows last logged in users

7) less , the less paging utility

8) logger , the logger command-line interface to syslog utility

9) logrotate , the the logrotate utility

10) savelog , the savelog log file saving utility

11) syslogd , the system log daemon (syslogd)

12) syslog.conf , the syslogd configuration file

13) Tail , the tail utility


IT601 – System and Network Administration

< End>
Arif Husen

Department of Computer Science and Information Technology,


Virtual University of Pakistan
IT601 – System and Network Administration

Shell Scripts
Arif Husen

Department of Computer Science and Information Technology,


Virtual University of Pakistan
Writing and Editing Files

➢ Vim is an acronym for Vi IMproved. It is a free and open-source cross-platform text editor. It was first
released by Bram Moolenaar in 1991 for UNIX variants.

➢ Vim is based on the original Vi editor, which was created by Bill Joy in 1976. In the 90’s, it started
becoming clear that Vi was lacking in some features when compared with the Emacs editor.

➢ VIM includes all the missing features of VI.

➢ VIM is generally preinstalled with many linux distributions, if not it can be installed as below

sudo apt-get update


sudo apt-get install vim
Vim Modes

➢ Everything in Vim is considered a mode. You can achieve whatever you want if you understand modes in
Vim.

➢ There are many modes in Vim. But, we'll be looking at the 4 most important modes.

Command Mode Insert Mode Command-Line Mode Visual Mode

▪ Default mode, also called


Normal mode. ▪ to edit the contents of the file. ▪ To execute commands ▪ to visually select some text
and run commands over that
▪ You can switch to insert mode section of code
▪ To switch from one mode to by pressing i from command ▪ the commands in this mode
another, you have to come to mode. are prefixed with a colon (:)
Command Mode
▪ switch to this mode by
▪ You can use the Esc key to pressing v from the command
switch back to command mode. ▪ Switch to this mode by mode.
pressing : (colon) in
▪ The commands that you run command mode
without any prefix (colon)
indicate that you're running the
command in command mode.
VIM Commands

➢ Insert mode commands


▪ a Append text following current cursor position
▪ A Append text to the end of current line
▪ i Insert text before the current cursor position
▪ I Insert text at the beginning of the cursor line
▪ o Open up a new line following the current line and add text there
▪ O Open up a new line in front of the current line and add text there

➢ Command mode commands


▪ Ctrl + e - 1 line up
▪ Ctrl + d - 1/2 page up
▪ Ctrl + f - 1 page up
▪ Ctrl + y - 1 line down
▪ Ctrl + u - 1/2 page down
▪ Ctrl + b - 1 page down
▪ % - use with '{','}','(',')' to jump with the matching one.
▪ 0 - first column of the line
▪ $ - jump to the last character of the line
VIM Commands
➢ Editing Commands
▪ d …delete the characters from the cursor position up the position given by the next command
▪ c …change the character from the cursor position up to the position indicated by the next command.
▪ y …copy the characters from the current cursor position up to the position indicated by the next command.
▪ p …paste previous deleted or yanked (copied) text after the current cursor position.
Note: Doubling d, c or y operates on the whole line, for example yy copies the whole line.

➢ Undo and Redo


▪ u - you can undo almost anything using u in the command mode.
▪ Ctrl+r - undo is undoable using Ctrl-r.
➢ Searching and Replacing
▪ :s/old/new/gc
▪ :s/old/new/g
➢ Save the file
▪ :wq , Save file and exit
▪ :q! , Exit file without saving the changes
First Script

➢ Create a new script file with name : myfirstScript.sh


Vi myfirstScript.sh

➢ Write the following content


#!/bin/sh

# Author : IT601
# Copyright (c) Virtual University of Pakistan

echo “Hello Virtual University Student, What is your student iD”

read VUID

echo “WELCOME !, $VUID"


➢ Make the script executable
Chmod 777 myfirstScript.sh
➢ Run script
./myfirstScript.sh
Variables
➢ Variable Names
The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the underscore character
( _). By convention, Unix shell variables will have their names in UPPERCASE.

➢ Defining Variables
VAR_NAME=variable_value
➢ Accessing Values
echo $VAR_NAME
➢ Read-only Variables
readonly VAR_NAME
➢ Unsetting Variables
unset VAR_NAME
➢ Variable Types
▪ Local Variables
▪ Environment Variables
▪ Shell Variables
Special variables
➢ $0 - The filename of the current script.

➢ $n - These variables correspond to the arguments with which a script was invoked. Here n is a positive
decimal number corresponding to the position of an argument.

➢ $# - The number of arguments supplied to a script.

➢ $* - All the arguments are double quoted. If a script receives two arguments, $* is equivalent to $1 $2.

➢ $@ - All arguments are individually double quoted. If script receives two arguments, $@ is equivalent to $1 $2.

➢ $? - The exit status of the last command executed.

➢ $$ - The process number of the current shell. This is the process ID under which they are executing.

➢ $! - The process number of the last background command.


Defining Array Values
➢ Basic Syntax
array_name[index]=value
➢ For the ksh shell, here is the syntax of array initialization
set -A array_name value1 value2 ... valuen

➢ For the bash shell, here is the syntax of array initialization

array_name=(value1 ... valuen)

➢ Accessing Array Values

${array_name[index]}
Operators
➢ Arithmetic Operators
+ (Addition) Adds values on either side of the operator `expr $a + $b` will give 30
- (Subtraction) Subtracts right hand operand from left hand operand `expr $a - $b` will give -10
* (Multiplication) Multiplies values on either side of the operator `expr $a \* $b` will give 200
/ (Division) Divides left hand operand by right hand operand `expr $b / $a` will give 2
Divides left hand operand by right hand operand and returns
% (Modulus) `expr $b % $a` will give 0
remainder
= (Assignment) Assigns right operand in left operand a = $b would assign value of b into a
== (Equality) Compares two numbers, if both are same then returns true. [ $a == $b ] would return false.
!= (Not Equality) Compares two numbers, if both are different then returns true. [ $a != $b ] would return true.

➢ Relational Operators
-eq Checks if the value of two operands are equal or not; if yes, then the condition becomes true. [ $a -eq $b ] is not true.
Checks if the value of two operands are equal or not; if values are not equal, then the condition becomes
-ne [ $a -ne $b ] is true.
true.
Checks if the value of left operand is greater than the value of right operand; if yes, then the condition
-gt [ $a -gt $b ] is not true.
becomes true.
Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes
-lt [ $a -lt $b ] is true.
true.
Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then the
-ge [ $a -ge $b ] is not true.
condition becomes true.
Checks if the value of left operand is less than or equal to the value of right operand; if yes, then the
-le [ $a -le $b ] is true.
condition becomes true.
Operators

➢ Boolean Operators
This is logical negation. This inverts a true condition into false
! [ ! false ] is true.
and vice versa.
This is logical OR. If one of the operands is true, then the
-o [ $a -lt 20 -o $b -gt 100 ] is true.
condition becomes true.
This is logical AND. If both the operands are true, then the
-a [ $a -lt 20 -a $b -gt 100 ] is false.
condition becomes true otherwise false.

➢ String Operators

= Checks if the value of two operands are equal or not; if yes, then the condition becomes true. [ $a = $b ] is not true.
Checks if the value of two operands are equal or not; if values are not equal then the condition
!= [ $a != $b ] is true.
becomes true.
-z Checks if the given string operand size is zero; if it is zero length, then it returns true. [ -z $a ] is not true.

-n Checks if the given string operand size is non-zero; if it is nonzero length, then it returns true. [ -n $a ] is not false.
str Checks if str is not the empty string; if it is empty, then it returns false. [ $a ] is not false.
Operators

➢ File Test Operators


-b file Checks if file is a block special file; if yes, then the condition becomes true. [ -b $file ] is false.
-c file Checks if file is a character special file; if yes, then the condition becomes true. [ -c $file ] is false.
-d file Checks if file is a directory; if yes, then the condition becomes true. [ -d $file ] is not true.
Checks if file is an ordinary file as opposed to a directory or special file; if yes, then the condition becomes
-f file [ -f $file ] is true.
true.
-g file Checks if file has its set group ID (SGID) bit set; if yes, then the condition becomes true. [ -g $file ] is false.
-k file Checks if file has its sticky bit set; if yes, then the condition becomes true. [ -k $file ] is false.
-p file Checks if file is a named pipe; if yes, then the condition becomes true. [ -p $file ] is false.
-t file Checks if file descriptor is open and associated with a terminal; if yes, then the condition becomes true. [ -t $file ] is false.

-u file Checks if file has its Set User ID (SUID) bit set; if yes, then the condition becomes true. [ -u $file ] is false.
-r file Checks if file is readable; if yes, then the condition becomes true. [ -r $file ] is true.
-w file Checks if file is writable; if yes, then the condition becomes true. [ -w $file ] is true.
-x file Checks if file is executable; if yes, then the condition becomes true. [ -x $file ] is true.
-s file Checks if file has size greater than 0; if yes, then condition becomes true. [ -s $file ] is true.
-e file Checks if file exists; is true even if file is a directory but exists. [ -e $file ] is true.
Control Statements
➢ The if...else statements
if...else...fi statement a=10
if...fi statement a=10
b=20
b=20 if [ expression ] if [ $a == $b ]
if [ expression ] if [ $a == $b ] then then
then then Statement(s) if true echo "a is equal to b"
Statement(s) if true echo "a is equal to b" else else
fi fi Statement(s) if not echo "a is not equal to b"
true fi
fi

if...elif...else...fi statement a=10


b=20
if [ expression 1 ] if [ $a == $b ]
then then
Statement(s) to be executed if expression 1 is true echo "a is equal to b"
elif [ expression 2 ] elif [ $a -gt $b ]
then then
Statement(s) to be executed if expression 2 is true echo "a is greater than b"
elif [ expression 3 ] elif [ $a -lt $b ]
then then
Statement(s) to be executed if expression 3 is true echo "a is less than b"
else else
Statement(s) to be executed if no expression is true echo "None of the condition met"
fi fi
Control Statements

The case...esac Statement FRUIT="kiwi"

case "$FRUIT" in
case word in "apple") echo "Apple pie is quite tasty."
pattern1) ;;
Statement(s) to be executed if pattern1 matches "banana") echo "I like banana nut bread."
;; ;;
pattern2) "kiwi") echo "New Zealand is famous for kiwi."
Statement(s) to be executed if pattern2 matches ;;
;; esac
pattern3)
Statement(s) to be executed if pattern3 matches
;;
*)
Default condition to be executed
;;
esac
Loops
➢ The while loop a=0
➢ The for loop for var in 0 1 2 3 4 5 6 7 8 9
while [ $a -lt 10 ] do
while command do for var in word1 word2 ... wordN echo $var
do echo $a do done
Statement(s) to be executed if command a=`expr $a + 1` Statement(s) to be executed
is true done for every word.
done done

➢ The until loop a=0 ➢ The select loop select K in tea cofee water juice appe all none
do
until command until [ ! $a -lt 10 ] select var in word1 word2 ... wordN case $K in
do do do tea|cofee|water|all)
Statement(s) to be executed echo $a Statement(s) to be executed for echo "Go to canteen"
until command is true a=`expr $a + 1` every word. ;;
done done done juice|appe)
echo "Available at home"
;;
none)
break
;;
*) echo "ERROR: Invalid selection"
;;
esac
done
Nesting while Loops

while command1 ; # this is loop1, the outer loop a=0


do while [ "$a" -lt 10 ] # this is loop1
Statement(s) to be executed if command1 is true do
b="$a"
while command2 ; # this is loop2, the inner loop while [ "$b" -ge 0 ] # this is loop2
do do
Statement(s) to be executed if command2 is true echo -n "$b "
done b=`expr $b - 1`
done
Statement(s) to be executed if command1 is true echo
done a=`expr $a + 1`
done

➢ Escape Sequences
➢ The break Statement
\\ backslash
➢ The continue statement \a alert (BEL)
\b backspace
\c suppress trailing newline
➢ Substitution
\f form feed
a=10 \n new line
echo -e "Value of a is $a \n" \r carriage return
\t horizontal tab
\v vertical tab
Creating Functions
Syntax Simple Function Passing Parameters Returning Data
function_name () { # Define your function here # Define your function here # Define your function here
list of commands Hello () { Hello () { Hello () {
} echo "Hello World" echo "Hello World $1 $2" echo "Hello World $1 $2"
} } return 10
}
# Invoke your function
# Invoke your function
Hello test1 test 2
Hello # Invoke your function
Hello Zara Ali

# Capture value returnd by last command


ret=$?

echo "Return value is $ret"


IT601 – System and Network Administration

< End>
Arif Husen

Department of Computer Science and Information Technology,


Virtual University of Pakistan

You might also like