Ubuntu Server 18.04 下 iptables 的備份與還原

【備份】

  • 目標:每晚一點,將 iptables 規則導出到本地,並備份到 FTP 服務器。

  • config.ini

[config]
;本地備份目錄
LocalBakFile=/home/walker/iptables_rules_bak/iptables.rules
;FTP 主機
FtpHost=192.168.30.xx 
;FTP 目錄
FtpBakRoot=iptables_bak
;FTP 用戶名  
FtpUser=ftpadmin
;FTP 密碼
FtpPwd=ftppwd
  • iptablesbak2ftp.py

# encoding: utf-8
# author: walker
# date: 2019-02-22 
# summary: Python3 備份 iptables 規則(本地+FTP) 

import os
import sys
import time
import pprint
import psutil
from configparser import ConfigParser
from ftplib import FTP

cur_dir_fullpath = os.path.dirname(os.path.abspath(__file__))

LocalBakFile = ''   # 本地備份文件
LocalIP = ''

FtpHost = ''        # FTP 主機
FtpBakRoot = ''     # FTP 目錄
FtpUser = ''
FtpPwd = ''

def ReadConfig(): 
    r""" 讀取配置文件 """
    global LocalBakFile
    global FtpHost, FtpBakRoot, FtpUser, FtpPwd
      
    cfg = ConfigParser()
    # cfg.optionxform = str   # 保持鍵的大小寫
    cfgFile = os.path.join(cur_dir_fullpath, 'config.ini')
    if not os.path.exists(cfgFile):
        input(cfgFile + ' not found')
        sys.exit(-1)
    with open(cfgFile, mode='rb') as f:
        content = f.read()
    if content.startswith(b'\xef\xbb\xbf'):     # 去掉 utf8 bom 頭
        content = content[3:]
    cfg.read_string(content.decode('utf8'))
    if not cfg.sections():
        input('Read config.ini failed...')
        sys.exit(-1)          

    LocalBakFile = cfg.get('config', 'LocalBakFile').strip()
    if not os.path.exists(LocalBakFile):
        print('Error: not exists %s' % LocalBakFile)
        sys.exit(-1)

    FtpHost = cfg.get('config', 'FtpHost').strip()
    FtpBakRoot = cfg.get('config', 'FtpBakRoot').strip()
    FtpUser = cfg.get('config', 'FtpUser').strip()
    FtpPwd = cfg.get('config', 'FtpPwd').strip()

    print('LocalBakFile: %s' % LocalBakFile)
    print('FtpHost: %s' % FtpHost)
    print('FtpBakRoot: %s' % FtpBakRoot)
    print('FtpUser: %s' % FtpUser)
    print('FtpPwd: %s' % FtpPwd)
          
    print('Read config.ini successed!')

def GetLocalIPByPrefix(prefix):
    r""" 根據前綴獲取IP """
    localIP = ''
    dic = psutil.net_if_addrs()
    for adapter in dic:
        snicList = dic[adapter]
        for snic in snicList:
            if not snic.family.name.startswith('AF_INET'):
                continue
            ip = snic.address
            if ip.startswith(prefix):
                localIP = ip
      
    return localIP
  
def Main():
    filename = '%s_%s.iptables_rules' % (time.strftime('%Y%m%d', time.localtime()), LocalIP)
    cmd = '/sbin/iptables-save > %s' % LocalBakFile
    print('cmd: %s' % cmd)
    rtn = os.system(cmd)
    if 0 != rtn:
        print('Error: 0 != rtn')
        return False

    ftp = FTP()
    ftp.encoding = 'gb18030'
    ftp.set_pasv(False)
    ftp.connect(FtpHost, port=21, timeout=10)
    ftp.login(user=FtpUser, passwd=FtpPwd)

    print(ftp.getwelcome())
    ftp.cwd(FtpBakRoot)
    # 以 sql 服務器 ip 作爲子目錄名
    if LocalIP not in ftp.nlst():
        ftp.mkd(LocalIP)       # 創建子目錄
    ftp.cwd(LocalIP)
    with open(LocalBakFile, mode='rb') as f:
        ftp.storbinary('STOR ' + filename, f)

    return True    
                                          
if __name__ == '__main__':
    ReadConfig()
    LocalIP = GetLocalIPByPrefix('192.168.30.')
    Main()
  • iptables_bak.sh

python3 -u /home/walker/Python3Project/iptablesbak2ftp/iptablesbak2ftp.py > /home/walker/Python3Project/iptablesbak2ftp/log.log 2>&1
  • 定時任務

# m h  dom mon dow   command
# 每晚一點執行
0  1  *  *  *  /home/walker/Python3Project/iptablesbak2ftp/iptables_bak.sh


【還原】

  • 目標:開機自動還原備份的 iptables 規則

  • 創建文件:/etc/systemd/system/rc-local.service

  • 在 rc-local.service 裏面添加如下內容

[Unit]
Description=/etc/rc.local Compatibility
ConditionPathExists=/etc/rc.local
After=network.target

[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
SysVStartPriority=99

[Install]
WantedBy=multi-user.target
  • 創建文件:/etc/rc.local 並添加如下內容

#!/bin/bash
/sbin/iptables-restore < /home/walker/iptables_rules_bak/iptables.rules
exit 0
  • 給 rc.local 添加可執行權限

sudo chmod 754 /etc/rc.local
  • 啓用服務(開機自啓動)

sudo systemctl enable rc-local
# 等價於
ln -s /etc/systemd/system/rc-local.service /etc/systemd/system/multi-user.target.wants/
  • 啓動服務並檢查狀態

sudo systemctl start rc-local.service
sudo systemctl status rc-local.service
  • 重啓服務器檢查是否能夠開機啓動


【相關鏈接】


*** walker ***


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章