Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to allow only machines with allowed ip(s) to login to my system via ssh.

For example, userA can use only ip xx.xx.xx.xx or yy.yy.yy.yy to login via ssh, and no other ip can login as the userA. And userB can use only ip zz.zz.zz.zz to login via ssh, no ip other than zz.zz.zz.zz can login as userB.

How should I set up my Linux to achieve this?

share|improve this question

In /etc/ssh/sshd_config add the following:

AllowUsers remoteUserA@xx.xx.xx.xx remoteUserA@yy.yy.yy.yy userA
AllowUsers remoteUserB@zz.zz.zz.zz userB

Then restart the SSH daemon.

You can use wildcards as described in Patterns section of the ssh_config manual.

share|improve this answer
What if I'm not sure the username of the remoteUser? I want anybody via zz.zz.zz.zz to be able to login as userB. Your method seems that require explicitly specify the username of the remoteUser. – Marcus Thornton Feb 15 at 7:36
Use a wildcard *@xx.xx.xx.xx – techraf Feb 15 at 7:49
@MarcusThornton: *@yy.yy.yy.yy should work, according to man sshd_config (see: AllowUsers) and man ssh_config (see: Patterns) – Ulrich Schwarz Feb 15 at 7:50

You can do that via iptables.

All connections from address to SSH (port 22):

iptables -A INPUT -p tcp -m state --state NEW --source --dport 22 -j ACCEPT

Deny all other SSH connections:

iptables -A INPUT -p tcp --dport 22 -j DROP
share|improve this answer
Iptables will not enough by it self. The best result if will add into /etc/ssh/sshd_config AllowUsers A B and no passwords, only ssh keys. – user6780 Feb 15 at 7:17
Please familiarize yourself with the basic markup used on this site. Using headerlines like you did and not formatting code as such leads to horribly formatted, ugly, posts. (click on the "edited ..." link to see how things changed. – Anthon Feb 15 at 7:25
@user6780 you should edit your answer instead of commenting. – guntbert Feb 15 at 17:03

One approach (if you're using PAM for authentication) is to specifiy pam_rhosts as a required module in /etc/pam.d/ssh. This allows each user to specify in their own .rhosts file where they are permitted to connect from.

Note that the authentication modules in the pam.d file will not be consulted for pubkey logins (e.g. I have auth required pam_deny.so to prevent password logins on my machines). Other modules (account, session and so on) are still used.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.