DenyHosts: Remove / Delete an IP address

last updated in Categories , , , , , , , ,

I‘ve followed your guide and installed denyhosts to protect on my RedHat 5.3 OpenSSH based server. However, I’ve been accidentally blocked out from my home ADSL IP address. I tried removing my blocked IP from /etc/hosts.deny, but it did blocked it again quickly. It appears that DenyHosts keeps track of the attempts somewhere on disk or memory. How do I remove my own home IP address from DenyHosts?

Simply removing your IP from /etc/hosts.deny does not work since DenyHosts keeps track of the attempts in the /usr/share/denyhosts/data directory. In order to remove your IP address you will need to do the following.

Step # 1: Stop DenyHosts

# /etc/init.d/denyhosts stop

Step # 2: Remove Your IP From /etc/hosts.deny

# vi /etc/hosts.deny
Delete your IP address. Save and close the file.

Step # 3: Remove Your IP From /usr/share/denyhosts/data Directory

Cd to /usr/share/denyhosts/data
# cd /usr/share/denyhosts/data
You need to edit the following files using vi and remove the lines containing the IP address. Save the file.

  1. hosts
  2. hosts-restricted
  3. hosts-root
  4. hosts-valid
  5. users-hosts

If you’ve static IP address add to allowed-hosts file. Any IP address that appears in this file will not be blocked by default (consider this as a whilelist):
# echo '1.2.3.4' >> allowed-hosts

Step # 4: Start DenyHosts

# /etc/init.d/denyhosts start

Recommend Readings:

  1. Debian Linux Stop SSH User Hacking / Cracking Attacks with DenyHosts Software
  2. Top 20 OpenSSH Server Best Security Practices
  3. Denyhosts project

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

15 comment

  1. BTW, /etc/init.d/denyhosts does not seem to exist in CentOS 5.3 Not sure why, even though this post is for RH already.

  2. @vivek,

    Moreover, I’ve always counted on IPtables & CSF for blocking hosts, guess they are less hassle than hostsallow/deny in a way.

  3. Nice. I use a custom script for this though.

    It is actually really simple..
    HOST=192.x.x.x
    service denyhosts stop
    mv /etc/hosts.deny /tmp
    cd /var/lib/denyhosts
    for i in `ls`; do mv $i $i.old; grep -v “$HOST” $i.old >> $i; done
    grep -v $HOST /tmp/hosts.deny >> /etc/hosts.deny
    service denyhosts start

  4. Nice. I use a custom script for this though.

    It is actually really simple..
    HOST=192.x.x.x
    service denyhosts stop
    mv /etc/hosts.deny /tmp
    cd /var/lib/denyhosts
    for i in `ls`; do mv $i $i.old; grep -v “$HOST” $i.old >> $i; done
    grep -v $HOST /tmp/hosts.deny >> /etc/hosts.deny
    mv *.old
    service denyhosts start

    1. the above script has some errors.
      1. instead of mv *.old should be rm *.old
      2. take care of the quotation marks “” in copy and paste

      the problem is in “$HOST” –> “$HOST”

  5. here is the script to allow the ip, it’s based on the above article and should work on centos/redhat.

    set -o nounset
    if [ $# -ne 1 ]; then
    	echo "please input an allowed ip address"
    	exit 1
    fi
    alloweHost=$1
    echo "stop denyhosts"
    service denyhosts stop
    currentTime=$(date +%Y-%m-%d-%H%M)
    echo "delete existing entries in blacklist"
    if [ -n "$(grep $allowedHost /etc/hosts.deny)" ]; then
      mv /etc/hosts.deny /etc/hosts.deny.bak.${currentTime}
      grep -v ${allowedHost} /etc/hosts.deny.bak.${currentTime} > /etc/hosts.deny
    fi
    cd /usr/share/denyhosts/data
    for f in `ls hosts* users-hosts`; do
      if [ -n "$(grep $allowedHost $f)" ]; then
    	mv ${f} ${f}.bak.${currentTime}
    	grep -v ${allowedHost} ${f}.bak.${currentTime} > ${f}
      fi
    done
    echo "add allowed ip in whitelist"
    if [ -z "$(grep $allowedHost /etc/hosts.allow)" ]; then
      echo "sshd: ${allowedHost}" >>/etc/hosts.allow
    fi
    if [ -z "$(grep $allowedHost allowed-hosts)" ]; then
      echo "${allowedHost}"  >>allowed-hosts
    fi
    service denyhosts start
    exit 0
    
  6. There is a typo in the script: alloweHost which misses a letter d. The rest variables are correct. Thus it should be allowedHost

    corrected script

    #!/bin/bash
    set -o nounset
    if [ $# -ne 1 ]; then
    	echo "please input an allowed ip address"
    	exit 1
    fi
    allowedHost=$1
    echo "stop denyhosts"
    service denyhosts stop
    currentTime=$(date +%Y-%m-%d-%H%M)
    echo "delete existing entries in blacklist"
    if [[ -n "$(grep ${allowedHost} /etc/hosts.deny)" ]]; then
      mv /etc/hosts.deny /etc/hosts.deny.bak.${currentTime}
      grep -v ${allowedHost} /etc/hosts.deny.bak.${currentTime} > /etc/hosts.deny
    fi
    cd /var/lib/denyhosts/
    for f in `ls hosts* users-hosts`; do
      if [ -n "$(grep ${allowedHost} $f)" ]; then
    	mv ${f} ${f}.bak.${currentTime}
    	grep -v ${allowedHost} ${f}.bak.${currentTime} > ${f}
      fi
    done
    echo "add allowed ip in whitelist"
    if [[ -z "$(grep ${allowedHost} /etc/hosts.allow)" ]]; then
      echo "sshd: ${allowedHost}" >>/etc/hosts.allow
    fi
    if [[ -z "$(grep ${allowedHost} allowed-hosts)" ]]; then
      echo "${allowedHost}"  >> allowed-hosts
    fi
    service denyhosts start
    exit 0
    
    
  7. Bismillah,

    Please see below for a more complete script. I have corrected some errors and modified a version to work with FreeBSD (original credits to Cyber Tinus http://www.cybertinus.nl/).

    For Linux:

    #!/bin/bash
    
    #################
    # CONFIGURATION #
    #################
    # The $WORK_DIR as set in /etc/denyhosts.conf. You can let this script find the
    # setting automatically, or you can set it yourself.
    DENYHOSTS_WORK_DIR=$(grep 'WORK_DIR' /etc/denyhosts.conf | grep -v '#' | cut -d '=' -f 2 | sed 's/ //')
    #DENYHOSTS_WORK_DIR="/var/lib/denyhosts"
    
    # All the files that contain the blocked IP address and hostname
    DENYHOSTS_FILES=(\
        '/etc/hosts.deny' \
        "${DENYHOSTS_WORK_DIR}/hosts" \
        "${DENYHOSTS_WORK_DIR}/hosts-restricted" \
        "${DENYHOSTS_WORK_DIR}/hosts-root" \
        "${DENYHOSTS_WORK_DIR}/hosts-valid" \
        "${DENYHOSTS_WORK_DIR}/users-hosts" \
    )
    # The file containing the IP addresses and hostnames that can't be blocked
    DENYHOSTS_ALLOWED_FILE="${DENYHOSTS_WORK_DIR}/allowed-hosts"
    # The command needed to start denyhosts after the IP and/or hostname is unbanned
    START_COMMAND='/etc/init.d/denyhosts start'
    # The command needed to stop denyhosts before the IP and/or hostname is unbanned
    STOP_COMMAND='/etc/init.d/denyhosts stop'
    
    #############################################
    # ACTUAL SCRIPT do not edit below this line #
    #############################################
    # set some default values to a few vars used in the script
    # Don't remove an IP address (N=remove, Y=don't remove)
    NO_IP='N'
    # Don't remove an hostname (N=remove, Y=don't remove)
    NO_HOST='N'
    # Add the IP address and/or hostname to the allowed list
    ADD_ALLOW='N'
    # The IP address that has to be removed
    IP=''
    # The hostname that has to be removed
    HOST=''
    
    function show_help()
    {
        echo $0
        echo "a small script to unblock an IP address and/or hostname from denyhosts.
    -h  | --host    | --hostname     : Specify the hostname to unblock (required, unless -nh is added).
    -i  | --ip      | --ipaddress    : Specify the IP address to unblock (required, unless -ni is added).
    -nh | --no-host | --no-hostname  : Don't require a hostname to start unblocking things.
    -ni | --no-ip   | --no-ipaddress : Don't require an IP address to start unblocking things.
    -a  | --add     | --add-allow    : Add the specified IP address and/or hostname to the unblock file, thus preventing that the specified IP address and/or hostname get blocked again.
    -H  | --help                     : show this help."
    }
    
    # Handle the commandline options
    while [ -n "$(echo $1 | grep -- '-')" -a $# -gt 0 ]; do
        case $1 in
            -h  | --host | --hostname) HOST=$2; shift 2;;
            -i  | --ip | --ipaddress) IP=$2; shift 2;;
            -nh | --no-host | --no-hostname) NO_HOST='Y'; shift;;
            -ni | --no-ip | --no-ipaddress) NO_IP='Y'; shift;;
            -a  | --add | --add-allow) ADD_ALLOW='Y'; shift;;
            *)
                echo "Unknown argument $1" 1>&2
                echo ''
                show_help $0
                exit 1
            ;;
        esac
    done
    
    # Checks to see if the required IP address and/or hostname are given
    if [ "${NO_IP}" == 'N' -a "${IP}" == '' ]; then
        echo 'No IP address given, exiting now' 1>&2
        exit 1
    fi
    if [ "${NO_HOST}" == 'N' -a "${HOST}" == '' ]; then
        echo 'No hostname given, exiting now' 1>&2
        exit 2
    fi
    
    # Show warnings if removing of an IP address and/or hostname is disabled
    if [ "${NO_IP}" == 'Y' ]; then
        echo 'WARNING: You disabled removing an IP address. Most bans consist of both an IP address and a hostname. Please double check if you want this. Continuing now.' 1>&2
    fi
    if [ "${NO_HOST}" == 'Y' ]; then
        echo 'WARNING: You disabled removing a hostname. Most bans consist of both an IP address and a hostname. Please double check if you want this. Continuing now.' 1>&2
    fi
    
    # Stopping denyhosts
    ${STOP_COMMAND}
    
    # Loop through all the denyhost files, to remove the IP address and/or hostname
    for FILE in ${DENYHOSTS_FILES[@]}; do
        # Check to see if the current denyhosts file exists, is a normal file, is
        # readable and is writable
        if [ -f "${FILE}" -a -r "${FILE}" -a -w "${FILE}" ] ; then
            # Check to see if there is an IP address to remove
            if [ "${NO_IP}" = 'N' ] ; then
                # Check that the IP address exists in the current denyhosts file
                if grep -q "${IP}" "${FILE}" ; then
                    # Remove the IP address from the current denyhosts file
                    sed -i "/${IP}/d" "${FILE}"
                    echo "Removed ip address ${IP} from ${FILE}"
                else
                    # The IP address doesn't exists in the current denyhosts file,
                    # notify user
                    echo "The ip address ${IP} wasn't in ${FILE}"
                fi
            fi
    
            # Check to see if there is a hostname to remove
            if [ "${NO_HOST}" = 'N' ] ; then
                # Check that the hostname exists in the current denyhosts file
                if grep -q "${HOST}" "${FILE}" ; then
                    # Remove the hostname from the current denyhosts file
                    sed -i "/${HOST}/d" "${FILE}"
                    echo "Removed hostname ${HOST} from ${FILE}"
                else
                    # The hostname doesn't exists in the current denyhosts file,
                    # notify user
                    echo "The hostname ${HOST} wasn't in ${FILE}"
                fi
            fi
        fi
    done
    
    # Check to see if the IP address and/or hostname needs to be added to the
    # allowed-hosts file
    if [ ${ADD_ALLOW} = 'Y' ] ; then
        # Check to see if there is an IP address to add
        if [ "${NO_IP}" = 'N' ] ; then
            echo "${IP}" >> "${DENYHOSTS_ALLOWED_FILE}"
        fi
    
        # Check to see if there is a hostname to add
        if [ "${NO_HOST}" = 'N' ] ; then
            echo "${HOST}" >> "${DENYHOSTS_ALLOWED_FILE}"
        fi
    fi
    
    # Start denyhosts again
    ${START_COMMAND}
    

    For BSD (sed command slightly different):

    #!/bin/bash
    
    #################
    # CONFIGURATION #
    #################
    # The $WORK_DIR as set in /etc/denyhosts.conf. You can let this script find the
    # setting automatically, or you can set it yourself.
    DENYHOSTS_WORK_DIR=$(grep 'WORK_DIR' /usr/local/etc/denyhosts.conf | grep -v '#' | cut -d '=' -f 2 | sed 's/ //')
    #DENYHOSTS_WORK_DIR="/var/lib/denyhosts"
    
    # All the files that contain the blocked IP address and hostname
    DENYHOSTS_FILES=(\
        '/etc/hosts.deniedssh' \
        "${DENYHOSTS_WORK_DIR}/hosts" \
        "${DENYHOSTS_WORK_DIR}/hosts-restricted" \
        "${DENYHOSTS_WORK_DIR}/hosts-root" \
        "${DENYHOSTS_WORK_DIR}/hosts-valid" \
        "${DENYHOSTS_WORK_DIR}/users-hosts" \
    )
    # The file containing the IP addresses and hostnames that can't be blocked
    DENYHOSTS_ALLOWED_FILE="${DENYHOSTS_WORK_DIR}/allowed-hosts"
    # The command needed to start denyhosts after the IP and/or hostname is unbanned
    START_COMMAND='/usr/local/etc/rc.d/denyhosts start'
    # The command needed to stop denyhosts before the IP and/or hostname is unbanned
    STOP_COMMAND='/usr/local/etc/rc.d/denyhosts stop'
    
    #############################################
    # ACTUAL SCRIPT do not edit below this line #
    #############################################
    # set some default values to a few vars used in the script
    # Don't remove an IP address (N=remove, Y=don't remove)
    NO_IP='N'
    # Don't remove an hostname (N=remove, Y=don't remove)
    NO_HOST='N'
    # Add the IP address and/or hostname to the allowed list
    ADD_ALLOW='N'
    # The IP address that has to be removed
    IP=''
    # The hostname that has to be removed
    HOST=''
    
    function show_help()
    {
        echo $0
        echo "a small script to unblock an IP address and/or hostname from denyhosts.
    -h  | --host    | --hostname     : Specify the hostname to unblock (required, unless -nh is added).
    -i  | --ip      | --ipaddress    : Specify the IP address to unblock (required, unless -ni is added).
    -nh | --no-host | --no-hostname  : Don't require a hostname to start unblocking things.
    -ni | --no-ip   | --no-ipaddress : Don't require an IP address to start unblocking things.
    -a  | --add     | --add-allow    : Add the specified IP address and/or hostname to the unblock file, thus preventing that the specified IP address and/or hostname get blocked again.
    -H  | --help                     : show this help."
    }
    
    # Handle the commandline options
    while [ -n "$(echo $1 | grep -- '-')" -a $# -gt 0 ]; do
        case $1 in
            -h  | --host | --hostname) HOST=$2; shift 2;;
            -i  | --ip | --ipaddress) IP=$2; shift 2;;
            -nh | --no-host | --no-hostname) NO_HOST='Y'; shift;;
            -ni | --no-ip | --no-ipaddress) NO_IP='Y'; shift;;
            -a  | --add | --add-allow) ADD_ALLOW='Y'; shift;;
            *)
                echo "Unknown argument $1" 1>&2
                echo ''
                show_help $0
                exit 1
            ;;
        esac
    done
    
    # Checks to see if the required IP address and/or hostname are given
    if [ "${NO_IP}" == 'N' -a "${IP}" == '' ]; then
        echo 'No IP address given, exiting now' 1>&2
        exit 1
    fi
    if [ "${NO_HOST}" == 'N' -a "${HOST}" == '' ]; then
        echo 'No hostname given, exiting now' 1>&2
        exit 2
    fi
    
    # Show warnings if removing of an IP address and/or hostname is disabled
    if [ "${NO_IP}" == 'Y' ]; then
        echo 'WARNING: You disabled removing an IP address. Most bans consist of both an IP address and a hostname. Please double check if you want this. Continuing now.' 1>&2
    fi
    if [ "${NO_HOST}" == 'Y' ]; then
        echo 'WARNING: You disabled removing a hostname. Most bans consist of both an IP address and a hostname. Please double check if you want this. Continuing now.' 1>&2
    fi
    
    # Stopping denyhosts
    ${STOP_COMMAND}
    
    # Loop through all the denyhost files, to remove the IP address and/or hostname
    for FILE in ${DENYHOSTS_FILES[@]}; do
        # Check to see if the current denyhosts file exists, is a normal file, is
        # readable and is writable
        if [ -f "${FILE}" -a -r "${FILE}" -a -w "${FILE}" ] ; then
            # Check to see if there is an IP address to remove
            if [ "${NO_IP}" = 'N' ] ; then
                # Check that the IP address exists in the current denyhosts file
                if grep -q "${IP}" "${FILE}" ; then
                    # Remove the IP address from the current denyhosts file
                    sed -i '' -e "/${IP}/d" "${FILE}"
                    echo "Removed ip address ${IP} from ${FILE}"
                else
                    # The IP address doesn't exists in the current denyhosts file,
                    # notify user
                    echo "The ip address ${IP} wasn't in ${FILE}"
                fi
            fi
    
            # Check to see if there is a hostname to remove
            if [ "${NO_HOST}" = 'N' ] ; then
                # Check that the hostname exists in the current denyhosts file
                if grep -q "${HOST}" "${FILE}" ; then
                    # Remove the hostname from the current denyhosts file
                    sed -i '' -e "/${HOST}/d" "${FILE}"
                    echo "Removed hostname ${HOST} from ${FILE}"
                else
                    # The hostname doesn't exists in the current denyhosts file,
                    # notify user
                    echo "The hostname ${HOST} wasn't in ${FILE}"
                fi
            fi
        fi
    done
    
    # Check to see if the IP address and/or hostname needs to be added to the
    # allowed-hosts file
    if [ ${ADD_ALLOW} = 'Y' ] ; then
        # Check to see if there is an IP address to add
        if [ "${NO_IP}" = 'N' ] ; then
            echo "${IP}" >> "${DENYHOSTS_ALLOWED_FILE}"
        fi
    
        # Check to see if there is a hostname to add
        if [ "${NO_HOST}" = 'N' ] ; then
            echo "${HOST}" >> "${DENYHOSTS_ALLOWED_FILE}"
        fi
    fi
    
    # Start denyhosts again
    ${START_COMMAND}
    

    I hope someone finds this useful.

    Assalamu Alaikum

    1. That is VERY useful, Thank you Assalamu,
      I’ve already learned several new things that will come in handy for a shell script I’m writing, Thanks again for the examples! and to the original poster for this thread, A win win for me today, two birds with one stone!

  8. Debian ships a utility script for this very purpose, you can use it as follows :

    # /usr/share/denyhosts/DenyHosts/dh_reenable

    Have a question? Post it on our forum!