【场景】公司采用ADSL拨号上网,即上网获得是动态IP。
服务器安全策略升级,只允许公司内可以访问服务器。
实现过程:
服务器指定固定IP可以访问服务器,其实很容易,一般有以下三下方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
方法一:
在
/etc/hosts
.allow中添加允许
ssh
登陆的ip或者网段
sshd:192.168.1.2:allow 或者
sshd:192.168.1.0
/24
:allow
在
/etc/hosts
.deny添加不允许
ssh
登陆的IP
sshd:ALL
#ALL表示除了上面允许的,其他的ip 都拒绝登陆ssh
方法二:
使用iptables。
iptables -A INPUT -p tcp -s 192.168.1.2 --destination-port 22 -j ACCEPT
iptables -A INPUT -p tcp --destination-port 22 -j DROP
方法三:
修改
ssh
配置文件
vi
/etc/ssh/sshd_config
添加一行:
allowusers xxx@192.168.1.2
注:xxx为你用来登入服务器的用户名。
|
我以方法一实现,限制ADSL动态IP进行登录,
方法简单:通过花生壳或者到kmdns注册账户,这样就会得到一个域名,我们在公司内网登录这个账户,
在服务器上解析得到IP就可以了。
我用的是TPLINK的路由器本身支持动态域名账户登录,好了,拿来直接用了。
在服务器用脚本实现
先配置hosts.allow文件,按以下格式配置
1
|
sshd:13.18.4.36:allow
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
root@Web:
/var/scripts
# vi /etc/hosts.allow
# /etc/hosts.allow: list of hosts that are allowed to access the system.
# See the manual pages hosts_access(5) and hosts_options(5).
#
# Example: ALL: LOCAL @some_netgroup
# ALL: .foobar.edu EXCEPT terminalserver.foobar.edu
#
# If you're going to protect the portmapper use the name "portmap" for the
# daemon name. Remember that you can only use the keyword "ALL" and IP
# addresses (NOT host or domain names) for the portmapper, as well as for
# rpc.mountd (the NFS mount daemon). See portmap(8) and rpc.mountd(8)
# for further information.
#
sshd:13.18.4.36:allow
|
编写获得动态域名IP并替换allow文件中内容脚本,
dig +short直接解析域名得到IP很简单
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
root@Web:
/var/scripts
# vi getip.sh
#!/bin/bash
#解析得到myku.kmdns.net动态域名IP
getip=`
dig
+short myku.kmdns.net`
#得到原来allow文件中的IP
oldip=`
cat
/etc/hosts
.allow|
grep
sshd |
awk
-F
':'
'{print $2}'
|
head
-n1`
if
[ $getip != $oldip ]
then
sed
-i
"s/$oldip/$getip/g"
/etc/hosts
.allow
else
exit
fi
root@Web:
/var/scripts
# chmod 777getip.sh
|
然后加入到自动任务中,每分钟检测一次
1
2
3
4
5
6
7
|
#allow myku ip to login server
*
/1
* * * *
/var/scripts/getip
.sh >
/dev/null
2>&1
别忘了
/etc/hosts
.deny添加不允许
ssh
登陆的IP
sshd:ALL
#ALL表示除了上面允许的,其他的ip 都拒绝登陆ssh
|
这样子就实现了hosts.allow 只允许adsl动态ip登录功能。
同理,我们也可以用另两个方法,这里就不多讲了。
本文转自 jackjiaxiong 51CTO博客,原文链接:http://blog.51cto.com/xiangcun168/1699264