最近在处理网站内的图片域名替换,由于大小专区网站众多(上百个),各网站均用静态文件发布器创建后生成html,css,js文件,要替换文件特别多,域名均写在页面源码里或js,css文件内,纯手工更改是不可能的,因此用python写了一个图片域名替换脚本进行批量替换,执行过程中也遇到过不少编码格式、乱码文件名等问题,但总算是完成了替换工作。
replace_2_7.py
# !/usr/bin/env Python
# coding=utf-8
# -*- coding: UTF-8 -*-
## python 2.7 网站静态资源文件内容域名替换脚本
## 运行:python replace_2_7.py
# 因服务器默认安装的是python2.7,没有升级,如果是3.X,请注释掉import sys、imp 等前四行
import sys
import imp
imp.reload(sys)
sys.setdefaultencoding('utf8')
from io import open
import os
# 读取指定目录下所有文件(此方法停用,os.walk()读取目录下如文件或文件夹乱码命名、非utf-8文件加载,均会失败,open_listdir兼容性强)
def open_dir(_dir, _dict):
for root, dirs, files in os.walk(_dir):
print('dir %s' % root) # 当前目录路径
# print(dirs) # 当前路径下所有子目录
# print(files) # 当前路径下所有子文件
for file in files:
f_type = os.path.splitext(file)[1]
f_path = '%s/%s' % (root, file)
if f_type == '.html' or f_type == '.HTML' or f_type == '.js' or f_type == '.JS' or f_type == '.css' or f_type == '.CSS':
if skip_file(f_path) == 1:
replace_file(f_path, _dict)
# 读取指定目录下所有文件
def open_listdir(_dir, _dict):
_dirs = os.listdir(_dir)
for file in _dirs:
if file == 'music' or file == 'img' or file == 'images' or file == 'sound' or file == 'doc':
print('skip dir : %s' % file)
continue
f_path = '%s/%s' % (_dir, file)
if os.path.isdir(f_path):
print('dir : %s' % _dir)
open_listdir(f_path, _dict)
if os.path.isfile(f_path):
f_type = os.path.splitext(file)[1]
if f_type == '.html' or f_type == '.HTML' or f_type == '.js' or f_type == '.JS' or f_type == '.css' or f_type == '.CSS':
if skip_file(f_path) == 1:
replace_file(f_path, _dict)
# 检验是否跳过不替换的文件
def skip_file(f_path):
f_name = os.path.basename(f_path);
# print('%s name : %s' % (f_path, f_name))
skip_files = ['jquery.min.js', 'jquery.mousewheel.js', 'main.css']
for skip_f in skip_files:
if f_name == skip_f:
print('skip file : %s' % skip_f)
return 0
return 1
# 读取域名替换文件
def open_txt(f_path):
_dict = {}
_lines = read_file(f_path, 'utf-8')
for line in _lines:
_strs = line.replace('\n', '').split(',')
_dict[_strs[0]] = _strs[1]
print('替换清单 %s' % _dict)
return _dict
# 查找替换的内容,并重写文件内容
def replace_file(f_path, _dict):
_content = []
_lines = read_file(f_path, 'utf-8')
for _line in _lines:
_content.append(line_replace(_line, _dict))
if len(_content) > 0:
write_file(f_path, _content, 'utf-8')
print()
# 进行行比较与替换
def line_replace(_str, _dict):
_keys = _dict.keys()
for _k in _keys:
_i = _str.find(_k)
if _i != -1:
print('index = %s %s to %s' % (_i, _k, _dict[_k]))
_str = _str.replace(_k, _dict[_k])
return _str
# 读取文件
def read_file(f_path, encoding):
print('read %s' % f_path)
f = None
try:
f = open(f_path, mode='r', encoding=encoding)
return f.readlines()
except UnicodeDecodeError:
if encoding == 'utf-8':
print('文件格式转换错误,切换成gbk')
return read_file(f_path, 'gbk')
if encoding == 'gbk':
print('文件格式转换错误,切换成gb2312')
return read_file(f_path, 'gb2312')
finally:
if f:
f.close()
return []
# 重新写入文件
def write_file(f_path, _content, encoding):
print('write %s' % f_path)
f = None
try:
f = open(f_path, mode='w', encoding=encoding)
f.writelines(_content)
finally:
if f:
f.close()
# 入口
if __name__ == '__main__':
_dict = open_txt('/opt/app/domain.txt')
_dirs = read_file('/opt/app/www_dirs.txt')
for _dir in _dirs:
_dir = _dir.replace('\n', '')
open_listdir('/data/www/' + _dir, _dict)
print('%s 处理完毕...' % _dir)
print('全部替换,处理完毕...')
domain.txt
img1.old.xxx.com,img1.news.xxx.com
img2.old.xxx.com,img2.news.xxx.com
img3.old.xxx.com,img3.news.xxx.com
以逗号分隔,前面为旧的域名,后面为新的替换后的域名,如:img1.old.xxx.com替换为img2.news.xxx.com
www_dirs.txt
a.xxx.com
b.xxx.com
c.xxx.com
...
此文件清单为各个静态网站在服务器上的存放目录,统一放在/data/www目录下,通过遍历此目录下所有网站文件进行批量图片域替换;
执行脚本
# 在linux服务器上执行
python replace_2_7.py