How to block/deny SSH connection to server using /etc/hosts.deny file?

Secure Shell protocol is abbreviated as SSH. It is a secure and most commonly using protocol to access remote servers. This protocol uses encryption while transferring data between two hosts.

TCP Wrapper is a host-based networking ACL system, used to filter network access to Internet Protocol servers on (Unix-like) operating systems such as Linux or BSD.

It allows host or subnetwork IP addresses, names and/or ident query replies, to be used as tokens on which to filter for access control purposes.

30 plus SSH interview questions and answers – compiled

I am going to explain how TCP wrappers help to protect server by controlling external connections. We can control the SSH connection to a server by using the following files:

/etc/hosts.allow and /etc/hosts.deny

How to block an IP address from SSH connection?

Step 1 : SSH to server as root user.
Step 2 : Open /etc/hosts.deny file using your favorite text editor.

sshd : IP-Address

To block more than one IP addresses:

sshd : IP-Address1, IP-Address2, IP-Address3

To block IP ranges:

sshd : 33.*.*.*
sshd : 66.66.*.*

Block all IP addresses from SSH

sshd : ALL

Or

ALL : ALL

SSH connection result:

[root@localhost ~]# ssh localhost
ssh_exchange_identification: Connection closed by remote host

We can also control the same from /etc/hosts.allow file by adding the keyword “DENY.”

# vi /etc/hosts.allow

sshd : ALL : DENY

Related Links:

How to manage SSH permission for custom users under your server
How to create a banner/welcome-note for SSH server
How to disable SSH login as root user – PermitRootLogin
/etc/hosts.allow

Post navigation

Arunlal A

Senior System Developer at Zeta. Linux lover. Traveller. Let's connect! Whether you're a seasoned DevOps pro or just starting your journey, I'm always eager to engage with like-minded individuals. Follow my blog for regular updates, connect on social media, and let's embark on this DevOps adventure together! Happy coding and deploying!

3 thoughts on “How to block/deny SSH connection to server using /etc/hosts.deny file?

  1. [root@my-pc ~]# systemctl restart network
    Job for network.service failed. See ‘systemctl status network.service’ and ‘journalctl -xn’ for details.
    [root@my-pc ~]#

    Hi Arun,

    I’m getting the above error when i try to restart the network service.

    Could you please guide me to sort this out ?

    OS : Centos-7

Leave a Reply

Your email address will not be published. Required fields are marked *