Monday, June 1, 2020

How to deny execution permission on your shell script for non-root users and sudo privileged users on Linux server.


When you do not want other users to run the script but only root user to run it, you can secure the script the in the below way.

This method will also deny the run permission for users with full sudo access as well.

ddd

 [root@kubernetesmaster]# cat only_root.sh
 #!/bin/bash

 if (( $(id -u) != 0 ))
 then
   echo "$0: This script must be run as root"
   exit 1
 fi

 if [ "$0" = "${SUDO_COMMAND%% *}" ]
 then
   echo "$0: This script should not be executed with sudo privileges"
   exit 1
 fi

 echo "Running the script as ROOT user."


 Running the script as root user will give you the results
 [root@kubernetesmaster]#./only_root.sh
 Running the script as ROOT user.

 To show the permission restriction for sudo privileged users, a testuser account is created with full sudo access.
 [root@kubernetesmaster]# grep -i testuser /etc/sudoers
 testuser ALL=(ALL) NOPASSWD:ALL

 When a testuser run the script it will show an error message.
 [testuser@kubernetesmaster]# ./tmp/only_root.sh
./tmp/only_root.sh: This script must be run as root

 Testuser tried to run the script with his sudo privileges but he is still not able to run the script.   Only root user can run the script and others are not allowed.
 [testuser@kubernetesmaster]#sudo /tmp/only_root.sh
 /tmp/only_root.sh: This script should not be executed with sudo privileges


Wednesday, June 27, 2018

Creating a file with server name and timestamp in python and shell script on Linux server.


Every time when we write a script to automate some task we create the log file to store the required output from the script.

Here I am showing you all how to create a log file with timestamp and server name with python and shell script on Linux servers.  So that you don't need to check in all the logs files when you look for a log of particular server.

Python Script:

root@linuxserver:/root> cat logfile_timestamp.py
#!/usr/bin/python

import os, time
logfile = "logfile_" + os.uname()[1] + "_" + str(time.strftime("%Y%m%d_%H%M%S")) + ".log"
f = open(logfile,'w')
f.close()

Run the script:
root@linuxserver:/root> python logfile_timestamp.py

Check if the log file created with server name and timestamp.
root@linuxserver:/root> ls -ltr logfile*
-rw-r--r-- 1 root root   0 Jun 27 02:45 logfile_linuxserver_20180627_024509.log


Shell Script:
root@linuxserver:/root>  cat create_logfile.sh
#/bin/bash

logfile=logfile_`uname -n`_`date +%Y%m%d_%H%M%S`.log
touch $logfile

Run the script:
root@linuxserver:/root> ./create_logfile.sh


Check if the log file created with server name and timestamp.
root@linuxserver:/root> ls -ltr logfile*
-rw-r--r-- 1 root root   0 Jun 27 02:41 logfile_linuxserver_20180627_024142.log

Thursday, April 26, 2018

List all the Filesystems which are more than 80% used in linux with awk command


Monitoring file system utilization on linux production server is a very important thing.  We can automate the file system utilization monitoring and schedule it in crontab.  So that script will run at the scheduled time and send out the alert messages.

It's always a good idea to have multiple threshold set for file system and we can make sure it won't reach 100% and the file system crashes on the server.

Below are the few examples of monitoring the file system threshold with powerful awk command.

[santhosh@localhost ~]# df -hP | tr -d "%" | sed 1d | awk '$5 >80'
/dev/mapper/vg00-mysql   30G   25G  3.7G  87 /u01
/dev/mapper/vg00-yumrepo  30G   24G  5.8G  81 /yumrepsitory


[santhosh@localhost ~]# df -hP | tr -d "%" | sed 1d | awk '{if($5>80) print}'
/dev/mapper/vg00-mysql   30G   25G  3.7G  87 /u01
/dev/mapper/vg00-yumrepo  30G   24G  5.8G  81 /yumrepsitory


[santhosh@localhost ~]# df -hP | tr -d "%" | sed 1d | awk 'int($5) > 80 { print $0 }'
/dev/mapper/vg00-mysql   30G   25G  3.7G  87 /u01
/dev/mapper/vg00-yumrepo  30G   24G  5.8G  81 /yumrepsitory

Monday, April 16, 2018

How to convert string to Uppercase and Lower case in Linux using awk and tr commands.



Lowercase to Uppercase:

Using awk command.
root@linuxserver:/root> echo santhosh | awk '{ print toupper($0)}'
SANTHOSH

Using tr command.
root@linuxserver:/root> echo santhosh | tr '[a-z]' '[A-Z]'
SANTHOSH


Uppercase to Lowercase:

Using awk command.
root@linuxserver:/root> echo SANTHOSH | awk '{ print tolower($0)}'
santhosh

Using tr command.
root@linuxserver:/root> echo SANTHOSH | tr '[A-Z]' '[a-z]'
santhosh

Monday, January 8, 2018

Bash shell script to list Ethernet interfaces names and IPaddress on linux server.


If there are multiple IP addresses public, private, backup, etc are in use on linux server it takes a bit more of time to scroll down through the output of 'ifconfig' command and find the IP address assigned to it.

I have created a shell script nic.sh which list all the Ethernet interfaces and IP address assigned to them on Linux server.

#!/bin/bash

nic=$(ifconfig | cut -d" " -f1 | sed '/^$/d' | awk -vORS=',' '{ print $1}' | sed -e s/,$//g)

OFS=IFS
IFS=','
read -ra i <<< "$nic"
for i in "${i[@]}"; do
echo "$i ---> $(ifconfig | grep -A 1 -i $i | sed -n '2p' | awk -F" " '{ print $2 }' | cut -d":" -f2)"
done


root@localhost:/root>./nic.sh
eth0 ---> 192.168.1.19
lo ---> 127.0.0.1

Saturday, January 6, 2018

How to set a default tray for a printer in Linux?


When there are multiple trays available in the printer and we want the printer to pick papers from a specific tray we can use the below command.

Syntax:
# lpoptions -p <printer name> -o InputSlot=<TrayN>

Example:
# lpoptions -p billing -o InputSlot=Tray2

Here the printer billing will use Tray2 as the default tray.

You can check it to make sure if the printer billing is using the Tray2.
# lpoptions -p billing -l | grep  InputSlot
  InputSlot/Media Source: Auto Tray1 *Tray2 Tray3 Tray4

Note that the asterisk (*) in front of the Tray2.

Tuesday, July 5, 2011

How to check server configuration details in Linux

Here i am showing some basic commands using them you can gather the system/server information.

To check what version of Operating System is installed on the server you can use the following commands:-
 =================================================================
1.cat /etc/issue
[root@localhost ~]# cat /etc/issue
Red Hat Enterprise Linux Server release 5.5 (Tikanga)
Kernel \r on an \m

2.cat /etc/redhat-release
[root@localhost ~]# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 5.5 (Tikanga)


3.lsb_release -a
[root@localhost ~]# lsb_release -a
LSB Version:    :core-3.1-ia32:core-3.1-noarch:graphics-3.1-ia32:graphics-3.1-noarch
Distributor ID: RedHatEnterpriseServer
Description:    Red Hat Enterprise Linux Server release 5.5 (Tikanga)
Release:        5.5
Codename:       Tikanga



To check whether the operating system is 32 or 64bit:-
================================
# uname -i
[root@localhost ~]# uname -i
i386
(i386 represents that server is having 32bit operating system)

[root@localhost ~]# uname -i
x86_64
(x86_64 represents that server is having 64bit operating system)

To see the processor/CPU information:-
=============================
# cat /proc/cpuinfo
[root@localhost ~] cat /proc/cpuinfo
processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 15
model name      : Intel(R) Xeon(R) CPU            5130  @ 2.00GHz
stepping        : 6
cpu MHz         : 1995.087
cache size      : 4096 KB
physical id     : 0
siblings        : 2
core id         : 0
cpu cores       : 2
apicid          : 0
fdiv_bug        : no
hlt_bug         : no
f00f_bug        : no
coma_bug        : no
fpu             : yes
fpu_exception   : yes
cpuid level     : 10
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx lm constant_tsc pni monitor ds_cpl vmx tm2 ssse3 cx16 xtpr lahf_lm
bogomips        : 3990.17
(Here processor number 0 indicates that the system is having one process(processor number starts with zero))




To check memory information:-
===========================
# free -m
[root@localhost ~]# free -m
             total       used       free     shared    buffers     cached
Mem:          5066       3513       1552          0        612       2319
-/+ buffers/cache:        582       4484
Swap:         1983          0       1983



# cat /proc/meminfo
[root@localhost ~]# cat /proc/meminfo
MemTotal:      5187752 kB
MemFree:       1639300 kB
Buffers:        627024 kB
Cached:        2374944 kB
SwapCached:          0 kB
Active:        2458788 kB
Inactive:       920964 kB
HighTotal:     4325164 kB
HighFree:      1561936 kB
LowTotal:       862588 kB
LowFree:         77364 kB
SwapTotal:     2031608 kB
SwapFree:      2031608 kB
Dirty:             704 kB
Writeback:           0 kB
AnonPages:      377892 kB
Mapped:          35328 kB
Slab:           153036 kB
PageTables:       6316 kB
NFS_Unstable:        0 kB
Bounce:              0 kB
CommitLimit:   4625484 kB
Committed_AS:   977132 kB
VmallocTotal:   116728 kB
VmallocUsed:      4492 kB
VmallocChunk:   112124 kB
HugePages_Total:     0
HugePages_Free:      0
HugePages_Rsvd:      0
Hugepagesize:     2048 kB


To check the model and serial name of the server:-
=======================================
[root@localhost ~]#  dmidecode | egrep -i "product name|Serial number"
Product Name: PowerEdge R710
Serial Number: AB8CDE1
       

To check the host name:-
=====================
[root@localhost ~]# uname -n
localhost

[root@localhost ~]# hostname
localhost

To check the kernel version:-
========================
[root@localhost ~]# uname -r
2.6.18-238.9.1.el5PAE

Monday, May 23, 2011

Commands to check errors in configuration files

In Linux, Once the service configuration has been done we can check the configuration files for errors.

Check Samba configuration file for errors with "testparm" command.
# testparm

Check HTTP(apache) configuration file for errors with the following commands
# apchectl configtest
# httpd -t
# service httpd configtest
(You can use any of the above commands to check the errors for apache)

Check SSH configuration file for errors
# sshd -t

Check  DNS configuration file for errors
# named-checkconf  /var/named/chroot/etc/named.conf
The above command will check the configuration file for errors

If you want to check the DNS zone file for errors , use the following command
Syntax: named-checkzone <domain name>  <path to zone file>
Ex: # named-checkzone  www.example.com  /var/named/chroot/var/named/zone.example.com

If the commands display the result as "OK" then the service is properly configured and you can restart the services or if you get any errors fix them.






Wednesday, May 18, 2011

Backup and Restore the Subversion Repository

It is a good practice backup Subversion repository to avoid any loss of data and sometimes you may need to move the svn repository from one server to another server.You can move your repository to another server with the following method.

1. Backup your repository( Create dump)
# svnadmin dump /path to /repository   >  repositoryname.dump

2. Copy the dump file to the new server
# scp -r repositoryname.dump   username@ipaddress:/destination path
Here destination path is location on the target server where the dump file has to be copied.

3. Create a new Repository on the target server
# svnadmin create <repositoryname>
Ex: #svnadmin create /var/www/testrepo

4.Import the dump file to the new repository.
# svnadmin load  /path to repository  <  repositoryname.dump

Wednesday, April 27, 2011

How to rename multple files at once in Linux

Suppose you have many html files which needs be backed up. In this case you can use the "rename" command.

# rename .html .html.bak  *.html

The above command will rename all the files which have extension .html to .html.bak in the current directory.

Friday, January 28, 2011

Creating an empty file having a specific size using dd command

Using the most popular dd command in Linux/Unix you can create a file having a
specific size. It can be Created for Testing purpose. Example when you are configuring disk quota.

dd if=/dev/zero of=example.txt  bs=1M count=1024
It will create an empty file of size 1GB

Here  if = input file , of = output file (it could be any name which you want), bs= block size, here I have mentioned M, it specifies MB(mega byte), if you want to create a file in KB(kilo byte) you need to specify bs with k( bs=10k).

Sunday, November 21, 2010

Impotant Port Numbers

To configure network services/servers, administrator must have a Knowledge of  Port numbers,. So you can  easily find out whether service/daemon is running or not. It will be very helpful when you are configuring iptables/firewall. Ex: You can block unwanted port numbers, it will reduce the risk of hack to the servers.
Here i am listing very common ports which we will use in everyday tasks.


Services                             Portnumber
FTP                                      20 and 21
SSH                                     22
TELNET                               23
SMTP                                  25
DNS                                    53
DHCP                                  67 and 68
TFTP                                   69
HTTP                                   80
NTP                                    123
POP3                                  110
IMAP                                  143
HTTPS                                443
IMAPS                                993
POP3S                                995
SWAT                                 901
SQUID                                3128
MYSQL                              3306
X-WINDOW                        6000
WEBMIN                           10000

Tuesday, November 9, 2010

Backup and Restore Mysql database

It is very important to backup databases to prevent any  loss of data. The easiest way backup the database is Mysqldump and we can restore it with mysql command...

Backup Syntax:
 #mysqldump -u [username] -p [databasename]  > dumpfilename.sql

Ex: you assume that you want to backup a database called users and with username root, then the command would be....
#mysqldump -u root -p users > users.sql
In the above example "-p" will prompt for password, and  if your mysql doesnot have any password then no need to use "-p".

Restore Syntax:
Mysqldump file can easily be restored by using the following command
#mysql -u root -p [databasename] < [mysqldumpfile.sql]

EX: #mysql -u root -p users < users.sql


























 

Sunday, October 24, 2010

List users or groups with IDs of 500 or greater

Listing all the users created by System administrator can be done with the powerful "awk" command...

#awk -F: '($3>=500)  && ($3!=65534)' /etc/passwd

Here the "awk" command will check the 3rd filed(uid) in the /etc/passwd file
and it will list uids which are equal and greater than 500. And here we are
mentioning not to list uid 65534, because this is nfs account account created
by system when we have installed nfs pakage.....


  
 

Tuesday, September 28, 2010

Check Date and Time in mysql

Sometimes we may need to check the time when we are working with mysql.
To do this login to mysql and use the following command

mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2010-09-28 14:49:57 |
+---------------------+
1 row in set (0.06 sec)

How to create SVN repository

Creating SVN repository on linux machine is  easy......
1. Install the subversion
        yum install subversion ( RHEL , Fedora, Centos)
        apt-get install subversion (ubuntu,debian)

2. Install open-ssh for secure connection (If repositoy on remote system)
# yum install openssh-server openssh-client (RHEL, Fedora, Centos)
# apt-get install openssh-server openssh-client (ubuntu, debian)

3. use svnadmin command to create the repositorty.....
# svnadmin create <path to repo>
ex:  svnadmin create /var/www/repo

4. Now change the directory to /var/www/repo
# cd /var/www/repo

5. Edit the configuration file
# vi /var/www/repo/conf/svnserve.conf
uncomment the following lines
anon-access = none
auth-access = write
password-db = passwd

6.create the users
# useradd -s /sbin/nologin user1

7.set the password for user1
# passwd user1
 
8.Now edit the passwd file
# vi /var/www/repo/conf/passwd

add the following line and save the file
user1 = password
 
9. Import your Project to repository
# svn import <path of project data> <path to repo>
ex: # svn import /home/sourcecode/project1 file:///var/www/repo/project1

10.Check out the data to your system
# svn co svn+ssh://user1@192.168.1.10/var/www/repo/project1