python 取本地动态IP修改一下IPTABLES的连接端口

回复 收藏
本帖最后由 模拟人生 于 2016-3-18 17:06 编辑

首先,ADSL的使用者都没有固定的IP,想着远端服务器的安全,连接的22端口也已经做了fail2ban,
但是技术主管那边还是不放心,所以写了这个脚本。应用之前请先安装好花生壳等动态域名工具,并
注册好动态域名。测试发现,花生壳效果不错,在dig命令下本人暂时还没有发现解释错误的。
dig命令也要先安装才可以用。

#!/bin/env python
#write by andy.zhang
import os
of=file('/etc/sysconfig/iptables','r')
old_ip=''
while True:
        line=of.readline()
        if '/32' in line and '--dport 22' in line:
                ''' print len(line) '''
                fir=0
                for i in range(len(line)):
                        if line in '0123456789':
                                fir=i
                                break
                for i in range(len(line)):
                        if line == '/':
                                old_ip= line[fir:i].lstrip().rstrip()
                                break
        if line =='' or old_ip != '':
                break
of.close()
if old_ip == '':
        '''print "Setting Is Erroy!Please check IPTABLES!!!" '''
        exit
if os.system('dig +short yhzxq.eicp.net >/tmp/new_ip.txt') != 0:
        ''' print 'IP Error,Exit' '''
        exit
of_new_ip=file('/tmp/new_ip.txt','r')
new_ip=of_new_ip.readline().lstrip().rstrip()
of_new_ip.close()
'''
print old_ip,'\t',new_ip,'\t',fir
'''
if old_ip != new_ip:
        of=file('/etc/sysconfig/iptables','r')
        new_file=file('/etc/sysconfig/new_iptables','w')
        while True:
                line=of.readline()
                if old_ip in line:
                        wline=line.replace(old_ip,new_ip)
                        print wline,'\n'
                        new_file.write(wline)
                else:
                        print line,'\n'
                        new_file.write(line)
                if line == '':
                        new_file.flush()
                        new_file.close()
                        of.close()
                        break
        os.system('rm -f /etc/sysconfig/iptables')
        os.system('mv /etc/sysconfig/new_iptables /etc/sysconfig/iptables')
        os.system('/etc/init.d/iptables restart')

2016-03-04 13:59 举报
已邀请:
0
本帖最后由 模拟人生 于 2016-3-4 14:02 编辑

使用前,请将iptables备份,并在22端口那里加入一个IP地址。如
-A IPTABLES -s 192.168.11.11/32 -p tcp --dport 22 -j ACCEPT
类似这样子。
0
铭哥,在不,来看看我的程序,出BUG了。程序有时会把新IP地址重复很多写入到iptables里。
请帮看看bug在哪?我找了很久,没发现。
0

Eric_NeuroSky

赞同来自:

模拟人生 发表于 2016-3-4 14:01
使用前,请将iptables备份,并在22端口那里加入一个IP地址。如
-A IPTABLES -s 192.168.11.11/32 -p tcp - ...

iptbales -A INPUT -s 192.168.11.11/32 -p tcp --dport 22 -j ACCEPT

回复帖子,请先登录注册

退出全屏模式 全屏模式 回复
评分
  • 评分区间
  • 学分
  • -30 ~ 30
可选评分理由: