Check SUID/SGID program Audit rules

Here's an interesting BASH script that checks that all SUID/SGID files have a corresponding audit rule. Useful if you work in an environment where you are required to periodically perform this check, and like all good (lazy) sysadmins, wish you had a script to automate this task...

#!/bin/bash

for i in `lsblk --output MOUNTPOINT | grep /`
do 
 for j in `find ${i} -xdev -type f \( -perm -4000 -o -perm -2000 \)`
 do
   if [ "$(grep -c ${j} /etc/audit/audit.rules)" -ge 1 ]; then
    # If there is a rule...do nothing?
    echo "" > /dev/null
   else
    echo "suid/sgid program ${j} - NO audit rule!"
   fi
 done
done

exit 0

 

Display the contents of a config file without commented out or blank lines

"Hi Pete! Is there a way that I can easily display the contents of a Linux config file, without showing all the commented out lines, and all the blank lines?"

This is easy to do with sed. Keep this one-line-command in your notes:


sed -e '/^ *#/d' -e '/^$/d' /etc/httpd/conf/httpd.conf
 
We're telling the sed command to display a file to STDOUT after performing
two edits (-e) on the output stream. The first one deletes all lines that
start with a pound sign (#), and the second edit deletes all blank lines. 
These deletes are not changes to the file itself! All that is changed is
the data sent to STDOUT. 
 

Installed RPM inventory

"I need a list of all installed RPMs on my CentOS server. But I want it as a CSV file (comma separated values). How can I do this in BASH?"

Here's the command  (all on one line) that will produce the output that you want:

rpm -qa --qf "\"$(uname -n)\",\"%{name}\",\"%{version}-%{release}\",\"%{vendor}\",\"%{license}\",\"%{summary}\"\n" > /tmp/software-list.csv

Now you can scp the file to your laptop, then open the file using MS-Excel (or your favorite spreadsheet program). It's been my experience that the vast majority of corporate laptop images are a version of Microsoft Windows. The only company I have ever worked for where this was not the case was Red Hat Inc. 

A script to update a CentOS7 YUM Repository

Here's a BASH script to use to update a CentOS7 YUM Repository:

#!/bin/bash
# A script to update a CentOS7 Yum Repository

REPOS=(base updates extras)

for REPO in ${REPOS[@]}
do
    echo "Updating repository: ${REPO} "
    /usr/bin/reposync --repoid=${REPO} --download_path=/repo -g -n -l -m

    if [ -e /repo/${REPO}/comps.xml ]; then
        /usr/bin/createrepo -v -g /repo/${REPO}/comps.xml /repo/${REPO}/
    else
        /usr/bin/createrepo -v /repo/${REPO}/
    fi
done

chown -R apache:apache /repo/*
restorecon -Rv /repo/*

exit 0

Generating a public/private keypair the right way

From the command line:

# ssh-keygen -t rsa -b 4096 -o -a 100

-a rounds
When saving a new-format private key (i.e. an
ed25519 key or any SSH protocol 2 key when the
-o flag is set), this option specifies the number
of KDF (key derivation function) rounds used.
Higher numbers result in slower passphrase
verification and increased resistance to brute-force
password cracking (should the keys be stolen).

-b bits
Specifies the number of bits in the key to create.
For RSA keys, the minimum size is 1024 bits and the
default is 2048 bits. Generally, 2048 bits is considered
sufficient. DSA keys must be exactly 1024 bits as
specified by FIPS 186-2.
-o Causes ssh-keygen to save private keys
using the new OpenSSH format rather than the
more compatible PEM format. The new format
has increased resistance to brute-force
password cracking but is not supported by
versions of OpenSSH prior to 6.5. Ed25519
keys always use the new private key format.

-t dsa | ecdsa | ed25519 | rsa | rsa1
Specifies the type of key to create. The possible
values are “rsa1” for protocol version 1 and “dsa”,
“ecdsa”, “ed25519”, or “rsa” for protocol version 2.

A customer recently asked me, "Is there a way to look at a configuration file, without all the comments and excess blank lines?"

Yes, there is! You can use the sed utility to display the contents of a file, omitting any blank lines, and omitting any lines that start with the "#" character (which denotes that the line is a comment), like this: 

sed -e '/^ *#/d' -e '/^$/d' /etc/httpd/conf/httpd.conf

In this example, I am using the sed command to display the content of the httpd.conf file. The -e option allows me to apply an edit to the stream of output. The first edit ('/^ *#/d') instructs sed to search the output for any lines starting with "#" and delete them. The second edit instructs sed to look for blank lines and delete them. It helps to understand basic Regular Expressions, which is an entire other discussion. 
Given a list of hostnames (one per line) in a file named hosts-list, ssh into each server in turn, sudo to root, and execute a command with sudo permissions, You will need to type in the password twice, unless you use an utility like Keepass, that allows you to copy/paste your password. This method makes it very quick and convenient to go thru a long list of servers, to perform a simple admin task. 


for name in $(cat hosts-list); do (ssh -t -o StrictHostKeyChecking=no my.username@${name} 'sudo su - -c "uname -a ; yum clean all"' 2> /dev/null) ; done

A BASH script to monitor disk usage in Linux

Someone asked me if disk space usage can be monitored via a bash script. Yes, it can. The following script can be copied to the host to be monitored, then executed periodically (once an hour?) via a crontab. Keep in mind there are bigger better ways out there to do this, but this isn't bad for a small simple solution. It's also a good exercise for you if you are learning Linux!

#!/bin/bash
# A script to keep an eye on disk use. Mutt must be installed
# and the host must be able to send SMTP mail.

# Alert Recipient 
ADMIN="linux-admin@example.com" 

# Alert Threshhold
ALERT=85  

df -h -P | grep -vE '^Filesystem|tmpfs|cdrom|iso|nfs|140.139' | awk '{ print $5 " " $1 }' | while read OUTPUT;
do
        USAGE=$(echo $OUTPUT | awk '{ print $1 }' | cut -d'%' -f1 )
        PARTITION=$(echo $OUTPUT | awk '{ print $2 }')

        if [ $USAGE -ge $ALERT ] ; then
                echo -e "WARNING: Filesystem on \"$PARTITION\" is ${USAGE}% full.\n Threshold is 85% \n HOST: $HOSTNAME\nDATE: $(date)\nThis message generated by /admin-scripts/SpaceWatch on $HOSTNAME" | \
                mutt -s "Alert: Disk space warning on $HOSTNAME" ${ADMIN}
        fi

done

exit 0

2018 University of Nebraska Cornhuskers Football Schedule


What D&D character am I?

I Am A: True Neutral Human Ranger (7th Level)

Ability Scores:
Strength-12
Dexterity-11
Constitution-12
Intelligence-12
Wisdom-11
Charisma-12

Alignment:
True Neutral A true neutral character does what seems to be a good idea. He doesn't feel strongly one way or the other when it comes to good vs. evil or law vs. chaos. Most true neutral characters exhibit a lack of conviction or bias rather than a commitment to neutrality. Such a character thinks of good as better than evil after all, he would rather have good neighbors and rulers than evil ones. Still, he's not personally committed to upholding good in any abstract or universal way. Some true neutral characters, on the other hand, commit themselves philosophically to neutrality. They see good, evil, law, and chaos as prejudices and dangerous extremes. They advocate the middle way of neutrality as the best, most balanced road in the long run. True neutral is the best alignment you can be because it means you act naturally, without prejudice or compulsion. However, true neutral can be a dangerous alignment when it represents apathy, indifference, and a lack of conviction.

Race:
Humans are the most adaptable of the common races. Short generations and a penchant for migration and conquest have made them physically diverse as well. Humans are often unorthodox in their dress, sporting unusual hairstyles, fanciful clothes, tattoos, and the like.

Class:
Rangers are skilled stalkers and hunters who make their home in the woods. Their martial skill is nearly the equal of the fighter, but they lack the latter's dedication to the craft of fighting. Instead, the ranger focuses his skills and training on a specific enemy a type of creature he bears a vengeful grudge against and hunts above all others. Rangers often accept the role of protector, aiding those who live in or travel through the woods. His skills allow him to move quietly and stick to the shadows, especially in natural settings, and he also has special knowledge of certain types of creatures. Finally, an experienced ranger has such a tie to nature that he can actually draw on natural power to cast divine spells, much as a druid does, and like a druid he is often accompanied by animal companions. A ranger's Wisdom score should be high, as this determines the maximum spell level that he can cast.

Find out What Kind of Dungeons and Dragons Character Would You Be?, courtesy of Easydamus (e-mail)

CentOS7: HOWTO show running services

[root@tony ~]# systemctl --no-page -t service -a --state running --no-legend
auditd.service           loaded active running Security Auditing Service
crond.service            loaded active running Command Scheduler
dbus.service             loaded active running D-Bus System Message Bus
dovecot.service          loaded active running Dovecot IMAP/POP3 email server
getty@tty1.service       loaded active running Getty on tty1
gssproxy.service         loaded active running GSSAPI Proxy Daemon
lvm2-lvmetad.service     loaded active running LVM2 metadata daemon
NetworkManager.service   loaded active running Network Manager
ntpd.service             loaded active running Network Time Service
polkit.service           loaded active running Authorization Manager
postfix.service          loaded active running Postfix Mail Transport Agent
rsyslog.service          loaded active running System Logging Service
sshd.service             loaded active running OpenSSH server daemon
systemd-journald.service loaded active running Journal Service
systemd-logind.service   loaded active running Login Service
systemd-udevd.service    loaded active running udev Kernel Device Manager
tuned.service            loaded active running Dynamic System Tuning Daemon
vmtoolsd.service         loaded active running Service for virtual machines hosted on VMware
wpa_supplicant.service   loaded active running WPA Supplicant daemon
[root@tony ~]#

Here's a fun little script using the Google Maps Geocoding API:


[pete@server1 ~]# cat latlong.sh
#!/bin/bash

if [[ -z $@ ]]; then 
  echo "Works better with an address..."
  exit 1
fi
if [[ ! -x /usr/bin/curl ]]; then 
  echo "ERROR: Can't work without /usr/bin/curl"
  exit 1
fi
if [ ! -x /usr/bin/xml2 ]; then 
  echo "ERROR: Please install package xml2 from the EPEL repo first."
  exit 1
fi

address="$(echo $@ | sed 's/ /+/g')"

curl -s "http://maps.googleapis.com/maps/api/geocode/xml?address=${address}" \
     -o /tmp/file.xml

eval $(xml2 < /tmp/file.xml | tr '/, ' '___' | grep =)

if [[ $_GeocodeResponse_status == "OK" ]]; then
  echo "Address: $(echo $address | sed 's/+/ /g')"
  echo "Lattitude: $_GeocodeResponse_result_geometry_location_lat"
  echo "Longitude: $_GeocodeResponse_result_geometry_location_lng"
else
  echo "No results"
fi

exit 0

[pete@server1 ~]# ./latlong.sh 1600 Pennsylvania Ave, Washington, DC
Address: 1600 Pennsylvania Ave, Washington, DC
Lattitude: 38.8791981
Longitude: -76.9818437
[pete@server1 ~]#


Awesome!

How to download all the RHEL7 docs

You can easily download all of the available Red Hat Enterprise Linux 7 Documentation (in PDF format) from a BASH prompt, by using the following command line:

curl -s https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/ | grep -o '[^"]*Linux/7/pdf[^"]*' | xargs -I{} wget https://access.redhat.com{}

This is very handy when you are studying for RHEL 7 Certification (RHCSA/RHCE). All the answers to the test are in these docs...  :-)

Official RHEL7 Information

Here's a list of links to Official Red Hat Enterprise Linux information:

RHEL 7 Reference Cards

Red Hat provides these quick reference PDF files for their Red Hat Enterprise Linux products:

How to delete blank rows in MS Excel

How to quickly and easily delete all blank rows from an Excel Spreadsheet:

​http://www.howtogeek.com/206696/how-to-quickly-and-easily-delete-blank-rows-and-columns-in-excel-2013/