freeBuf
主站

分类

云安全 AI安全 开发安全 终端安全 数据安全 Web安全 基础安全 企业安全 关基安全 移动安全 系统安全 其他安全

特色

热点 工具 漏洞 人物志 活动 安全招聘 攻防演练 政策法规

点我创作

试试在FreeBuf发布您的第一篇文章 让安全圈留下您的足迹
我知道了

官方公众号企业安全新浪微博

FreeBuf.COM网络安全行业门户,每日发布专业的安全资讯、技术剖析。

FreeBuf+小程序

FreeBuf+小程序

0

1

2

3

4

5

6

7

8

9

0

1

2

3

4

5

6

7

8

9

0

1

2

3

4

5

6

7

8

9

0

1

2

3

4

5

6

7

8

9

0

1

2

3

4

5

6

7

8

9

0

1

2

3

4

5

6

7

8

9

实用工具|Markdown文件一键上传Freebuf
Skeerr 2024-07-11 16:17:18 76126

实用工具|Markdown文件一键上传Freebuf

1.背景

本文主要解决本地编写的markdown文件上传freebuf的问题,核心痛点是本地编辑完markdown文件后,图片保存在本地,需要一张一张上传freebuf,并且逐个替换图片链接。在参考了大佬的相关文档后,感觉实现方式较为复杂,于是打算采用个新的思路实现freebuf文章的上传。于是造了个轮子,核心代码不超过50行,并且增加了一个功能:图片未被引用的情况下自动检测,可以进一步扩展例如自动删除无用图片等功能。

2.原理

1.读取文件路径,获取图片文件夹下的所有图片文件 。[图片文件夹下自然都是图片文件]。

2.在markdown文件中按照图片文件名逐个进行二进制查找,如果找不到说明该图片文件名,则说明该图片未被引用,剔除。

3.逐个替换markdown文件中的图片链接,保存为freebuf_xxxxx.md。

3.使用

3.1Typora设置

首先,打开typora,文件偏好设置图像,进行如下设置

image-20240711142419153

3.2获取上传TOKEN

手动上传一张图片,获取上传图片需要的的Bearer token,【备注:也可使用抓包方式获取】

将文章的编写模式改为markdown模式。按F12键 ( 或者 CTRL+SHIF+I)打开浏览器的开发者模式。

image-20240711135212960

点击图片,选择图片文件上传。

image-20240711135253275

在网络选项卡中可以看到对应url地址,以及token,从 Bearer 开始复制 到结束。注意红框中的内容,token较长,进行了自动换行。

image-20240711135547308

3.3安装

需要用到requests库,使用 pip install requests安装requests

image-20240711140548796

将文章末尾的代码保存为 freebuf.py,通过python运行, python freebuf.py,提示输入token后,粘贴3.2节获取到的token,然后输入文件路径,如下图所示:

image-20240711140749037

image-20240711140810356

脚本对未引用的图片资源进行检测后,逐个上传图片文件,并且将原始文件保存为freebuf_xxxxx.md。上传完成后,直接打开md文件,粘贴到freebuf即可。

image-20240711140900152

将以下文件保存为,例如保存为:freebuf.py

import json
import os
import sys
from pathlib import Path
import requests


def upload_image(token, image_data):
    r"""
    :param token:  http头部字段 "Authorization": token, 以Bearer开头的JWT字符串
    :param image_data: 图片文件的二进制数据
    :return: 上传后的图片url地址
    """
    session = requests.session()
    url = "https://www.freebuf.com:443/fapi/frontend/upload/image"
    headers = {"Connection": "close", "Accept": "application/json, text/plain, */*",
               "Authorization": token,
               "X-Client-Type": "web",
               "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36",
               "Content-Type": "multipart/form-data; boundary=----WebKitFormBoundaryeByfZpAtj8FqfYwc",
               "Origin": "https://www.freebuf.com", "Sec-Fetch-Site": "same-origin", "Sec-Fetch-Mode": "cors",
               "Sec-Fetch-Dest": "empty", "Referer": "https://www.freebuf.com/write",
               "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8"}
    data = "------WebKitFormBoundaryeByfZpAtj8FqfYwc\r\nContent-Disposition: form-data; name=\"file\"; filename=\"image.png\"\r\nContent-Type: image/png\r\n\r\n__CONTENT__\r\n------WebKitFormBoundaryeByfZpAtj8FqfYwc\r\nContent-Disposition: form-data; name=\"is_base64\"\r\n\r\n0\r\n------WebKitFormBoundaryeByfZpAtj8FqfYwc--\r\n"

    result = session.post(url, headers=headers, data=data.encode().replace('__CONTENT__'.encode(), image_data))
    if result.status_code == 200:
        json_data = json.loads(result.text)
        if json_data['code'] != 200:
            print("[-]上传图片失败,token错误,请重新获取token后重新尝试,错误信息:{}".format(json_data['msg']))
            sys.exit(1)
        else:
            return json_data['data']['url']
    print("[-]服务器链接失败 ", result)
    sys.exit(1)


def init_check(image_files, file_content):
    r"""检查图片文件是否在Markdown中被引用过,输出检查结果,移除未被引用到的图片。

    :param image_files:
    :param file_content:
    :return:
    """
    for image_file in image_files:
        if image_file.encode() not in file_content:
            print("[-]发现未被引用的文件 {}".format(image_file))
            image_files.remove(image_file)  # 移除未被引用到的图片
            # 可以做一些额外操作,比如删减无用的图片等。
    print("[+]检测到图片文件{}个".format(len(image_files)))


if __name__ == '__main__':

    TOKEN = ""  # 如果需要上传多个文件,请给token赋值,可以减少输入次数。
    file_path = ""

    if TOKEN == "":
        TOKEN = input("请输入Freebuf的token 示例token:  Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp....\n>>>")
    if file_path == "":
        file_path = input("请输入Mark文件路径 例如D:\\data\\python入门.md\n>>>")
        while (not Path(file_path).exists()) or (file_path == ""):
            file_path = input("文件路径{}不存在,请重新输入\n>>>".format(file_path))

    image_dir = Path(file_path).parent / (Path(file_path).stem + ".assets")  # 图片为同一目录下.assets文件夹
    print(image_dir)

    image_files = os.listdir(image_dir)
    # 新文件路径
    new_file_name = "freebuf_" + Path(file_path).name
    new_file_path = Path(file_path).parent / new_file_name
    # 获取文件内容
    with open(file_path, 'rb') as file:
        file_content = file.read()

    # 初始检测
    init_check(image_files, file_content)
    # 开始上传
    # 逐个上传文件,并且替换原始文件内容
    count = 0
    for image_file in image_files:
        if image_file.encode() in file_content:
            count += 1
            # 获取图片文件二进制内容
            with open(Path(image_dir) / image_file, 'rb') as file:
                image_file_content = file.read()
                server_url = upload_image(TOKEN, image_file_content)
                # 本地markdown图片引用前边带着文件夹名称,需要一同替换掉: ![image](文章标题.assets/image-20240706154926605.png)
                file_content = file_content.replace(
                    (Path(image_dir).name + '/' + image_file).encode(),
                    server_url.encode()
                )
                print("[+]上传成功第{}个:{}".format(count, image_file))
    print("[+]上传图片文件成功{}个".format(count))
    with open(new_file_path, 'wb+') as file:
        file.write(file_content)
        print("[+]文件保存成功 {}".format(new_file_path.absolute()))

4.后记

如果需要上传多个markdown文件,不想每次输入token,请在代码第58行 给token赋值.。TOKEN = "" # 位置。

如有其他疑问,或者更好的建议,欢迎私信。

参考文章:

https://www.freebuf.com/sectool/327474.html【相关内容已失效】

# 工具使用 # 热门文章 # Markdown # typora # 文章撰写
免责声明
1.一般免责声明:本文所提供的技术信息仅供参考,不构成任何专业建议。读者应根据自身情况谨慎使用且应遵守《中华人民共和国网络安全法》,作者及发布平台不对因使用本文信息而导致的任何直接或间接责任或损失负责。
2. 适用性声明:文中技术内容可能不适用于所有情况或系统,在实际应用前请充分测试和评估。若因使用不当造成的任何问题,相关方不承担责任。
3. 更新声明:技术发展迅速,文章内容可能存在滞后性。读者需自行判断信息的时效性,因依据过时内容产生的后果,作者及发布平台不承担责任。
本文为 Skeerr 独立观点,未经授权禁止转载。
如需授权、对文章有疑问或需删除稿件,请联系 FreeBuf 客服小蜜蜂(微信:freebee1024)
被以下专辑收录,发现更多精彩内容
+ 收入我的专辑
+ 加入我的收藏
相关推荐
Skeerr LV.2
这家伙太懒了,还未填写个人描述!
  • 3 文章数
  • 2 关注者
【踩坑系列】最简单的方式对Android App 抓包
2024-07-06
记一次OA系统被植入冰蝎内存马后的溯源
2024-06-13
文章目录