效果
使用方法
python3 GenLike.py -w <目录> --index
例如
[root@localhost installation]# python3 GenLike.py -w /var/www/package/ --index
/var/www/package/
在这个目录检测所有文件
--index
: 在检测路径生成index.html
文件,默认生成FileList.html
源码
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
@File : GenLike.py
@Time : 2023-03-13 16:43
@Author : 坐公交也用券
@Version : 1.0
@Contact : liumou.site@qq.com
@Homepage : https://liumou.site
@Desc : 生成网站目录导航
"""
import os
from argparse import ArgumentParser
from pathlib import Path
class GenHtml:
def __init__(self, work):
"""
:param work:
"""
self.work = work
self.htmlFile = ""
self.htmlDic = {}
self.fnList = ["deb", "zip", "py"] # 生成下载链接的文件格式列表
def index(self):
txt = f"""<!DOCTYPE html>
<html lang="zh">
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>进入文件下载</title>
</head>
<body>"""
for i in self.fnList:
txt = txt + f"""\n<li><a href="{i}.html">浏览{i}文件</a></li>"""
txt = txt + """\n</body>\n</html>"""
file = Path(self.work).joinpath("FileList.html")
if index_:
file = Path(self.work).joinpath("index.html")
try:
with open(file=file, mode='w', encoding="utf8") as w:
w.write(txt)
print("写入成功: ", file)
except Exception as e:
print("写入失败: ", e)
def init(self):
for i in self.fnList:
self.htmlDic[i] = f"""<!DOCTYPE html>
<html lang="zh">
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>进入文件下载</title>
</head>
<body>
"""
def create(self):
"""
创建最终代码
:return:
"""
for i in self.htmlDic:
self.htmlFile = self.htmlFile + """\n</body>\n</html>"""
os.chdir(self.work)
f = Path(self.work).joinpath(f"{i}.html")
try:
with open(file=f, mode='w+', encoding="utf8") as w:
w.write(self.htmlDic[i])
print("写入成功: ", f)
except Exception as e:
print(f"[ {f} ]写入文件失败: ", e)
def getFormat(self, file):
"""
获取格式名称
:return: 是否需要生成
"""
fn = str(file).split(".")[-1].lower()
if fn in self.fnList:
return True, fn
return False, None
def get(self):
for dir_path, subpaths, files in os.walk(self.work, False):
for i in files:
ft = Path(dir_path).joinpath(i)
ft = str(ft).replace(self.work, '')
ft_href = str(self.work).split("/")[-1] + ft
# ft_href = ft
get = self.getFormat(ft)
if get[0]:
txt = f"""\n<li><a href="{ft}">{ft}</a></li>"""
tmp = self.htmlDic[get[1]]
print("tmp:", ft_href)
print(tmp)
tmp = tmp + txt
self.htmlDic[get[1]] = tmp
def Start(self):
self.init()
self.get()
self.index()
self.create()
if __name__ == "__main__":
arg = ArgumentParser(description='当前脚本版本: 1.0', prog="网站文件下载目录生成")
arg.add_argument('-w', type=str, default='DB', help='设置目录', required=False)
arg.add_argument('--index', action='store_true', help='是否写入目录首页文件')
args = arg.parse_args()
wo = args.w
index_ = args.index
g = GenHtml(work=wo)
g.Start()