how to restrict ssh login to a specific ip or host

I must agree with dunxd, IPTables should not be discounted as a viable approach. You are in luck, however, since you can leverage tcpwrappers to the same functional end. Although more complex than on the surface, tcpwrappers essentially boils down to two files: /etc/hosts.allow and /etc/hosts.deny If these files do not yet exist, you can safely create them as empty files: sudo touch /etc/hosts.{allow,deny}.

Now it's time for things to get a little more complicated. The "best" approach to securing network access is to set your default, and only, hosts.deny entry to ALL:ALL, however, this may result in unintended access restrictions. For this reason, and the purposes of this question, it should be sufficient to enter sshd:ALL in /etc/hosts.deny which will disallow all ssh access to the host.

All entries in /etc/hosts.allow, as far as sshd is concerned, will now supersede the default deny rule: sshd: 172.168.0.21 will permit access to host 172.168.0.21 only and deny all others.

The tcpwrappers files accept a comma-separated list of entries, so you can append addresses to the first entry above. tcpwrappers also accept partial IP addresses as subnets, so you could allow the entire 172.168.0.0/24 as sshd: 172.168.0.

Please reference the man page for additional details. tcpwrappers is actually very feature-full and I recommend reading more than my brief examination above.


You could use the AllowUsers directive in /etc/ssh/sshd_config e.g.

AllowUsers [email protected]

If you make any changes in your sshd_config file don't forget to restart sshd.

from the sshd_config manpage

This keyword can be followed by a list of user name patterns,
separated by spaces.  If specified, login is allowed only for
user names that match one of the patterns.  ‘*’ and ‘?’ can be
used as wildcards in the patterns.  Only user names are valid; a
numerical user ID is not recognized.  By default, login is
allowed for all users.  If the pattern takes the form USER@HOST
then USER and HOST are separately checked, restricting logins to
particular users from particular hosts.