How to Search for an Exact String With GREP

GREP is one of those simple UNIX programs that you can’t live without if you do any kind of systems administration of an operating system based on UNIX such as Linux or Mac OS X. If you need to search for an exact string and NOT just a substring, all you have to do is specify the “-w” command line switch. For example, say you wanted to search for the string “username” in a text file named “login.php” that contains the following lines:

username = "foo";
groupusername = "myGroupUserName";
defaultusername = "defaultUser";

If you try the command:

grep “username” login.php

all of the lines in the file would be returned since they all contain the substring “username” somewhere in the line.

locahost ~: grep "username" login.php
username = "foo";
groupusername = "myGroupUserName";
defaultusername = "defaultUser";

However if you specify the “-w” command line switch, only the first line will be returned:

localhost ~: grep -w "username" login.php
username = "foo";

Terminal

How to Block an IP Range with IPTables

If you want to block a range of IP addresses from accessing your CentOS server you can issue the following IPTables firewall command:

/sbin/iptables -I INPUT -m iprange --src-range 192.168.1.1-192.168.1.2.100 -j DROP

Replace “192.168.1.1-192.168.1.2.100” with the IP range you want to block. This command only works with the IPTables firewall so if your operating system is using a different firewall then this command will not work.

Here is another example which uses CIDR notation to specify the IP range:

/sbin/iptables -I INPUT -s 192.168.1.1/25 -j DROP

If you restart your server, the drop command will be removed. If you want this command to persist through reboots, then you’ll need to add it to a startup script.

How to Recursively chmod Directories or Files

Command to recursively chmod only directories:

find . -type d -exec chmod 755 {} \;

How to recursively set the execute bit on every directory:

chmod -R a+X *

The +X flag sets the execute bit on directories only

How to recursively chmod only files:

find . -type f -exec chmod 644 {} \;

How to recursively chmod only PHP files (only for PHP files with the extension .php):

find . -type f -name '*.php' -exec chmod 644 {} \;

You can change the “.php” in the line above to whatever file extension that you want.

How to Determine What Program Is Listening on a Port in OS X or Linux

To determine what daemon or program is listening on a port in Linux or OS X you can use the lsof command. You need to run the command while logged in as root or if your operating system supports sudo like OS X, you can use that.

Command to run in Linux:

lsof -i -nP

Command to run in OS X:

sudo lsof -i -nP

Terminal