mycpen

Mycpen

记录学习历程与受益知识
github
telegram
bilibili

01_PHP-CentOS8.2 编译安装 PHP8.1.10

一。前言#

https://www.jsdelivr.com/ 失效,博主打算将 GitHub 托管的图床备份到其他平台。

网上看到 兰空图床 萌生了自建图床的念头,搭建环境要求 PHP >= 8.0.2,于是打算编译安装 PHP。

最终因服务器配置太低(1 核 2G)编译失败而放弃。转而投身之前已经搭建好环境的又拍云平台。

博文内容:PHP-CentOS8.2 编译安装 PHP8.1.10 + 编写GitHub图床迁移至又拍云的脚本(ftp) + 编写批量修改文章内容的脚本

二。正文#

2.1❤ CentOS8.2 编译安装 PHP8.1.10#

2.1.1 PHP8 和 oniguruma 源码下载并上传至服务器 /mnt 目录

https://www.php.net/distributions/php-8.1.10.tar.gz

https://codeload.github.com/kkos/oniguruma/tar.gz/refs/tags/v6.9.4

# 解压
tar xzf oniguruma-6.9.4.tar.gz
tar xzf php-8.1.10.tar.gz

2.1.2 安装 PHP8 依赖包

# 2 安装 PHP8 依赖包
yum -y install autoconf freetype gd libpng libpng-devel libjpeg libxml2 libxml2-devel zlib curl curl-devel net-snmp-devel libjpeg-devel php-ldap openldap-devel openldap-clients freetype-devel gmp-devel libzip libzip-devel sqlite-devel automake libtool

2.1.3 编译 PHP8 依赖包 oniguruma

# 3.1 生成 configure
cd /mnt/oniguruma-6.9.4
./autogen.sh

# 3.2 生成编译配置文件
./configure --prefix=/usr

# 3.3 编译并安装
make && make install

2.1.4 编译 PHP8 主包

# 4.1 生成编译配置文件
cd /mnt/php-8.1.10
./configure --prefix=/usr/local/php --with-config-file-path=/usr/local/php/etc --enable-fpm --with-fpm-user=nginx --with-fpm-group=nginx --enable-mysqlnd --with-mysqli --with-pdo-mysql --enable-opcache --with-pcre-jit --enable-gd --with-jpeg --with-freetype --with-gettext --with-curl --with-openssl --enable-sockets --enable-mbstring --enable-xml --with-zip --with-zlib --with-snmp --with-mhash --enable-ftp --enable-bcmath --enable-soap --enable-shmop --enable-sysvsem --enable-pcntl --with-gmp

# 4.2 编译并安装
make && make install

因为配置过低,编译失败。

2.1.5 编译安装后目录

/usr/local/php

参考

https://www.bilibili.com/read/cv9248283/

2.2 基于 FTP 将 GitHub 图床迁移至又拍云#

参考

官方视频教程 - 创建存储服务和使用 FTP 上传 可以得到用户名和密码

默认已经完成了又拍云云存储服务的申请 + 绑定自定义域名 https://help.upyun.com/knowledge-base/quick_start/

2.2.1 编写 Python 脚本 实现批量

源码来自 http://blog.csdn.net/ouyang_peng/article/details/79271113

#!/usr/bin/python
# -*- coding: UTF-8 -*-


from cmath import log
from ftplib import FTP
import os
import sys
import time
import socket
import subprocess

class MyFTP:
    """
        ftp自动下载、自动上传脚本,可以递归目录操作
        作者:欧阳鹏
        博客地址:http://blog.csdn.net/ouyang_peng/article/details/79271113
    """

    def __init__(self, host, port=21):
        """ 初始化 FTP 客户端
        参数:
                 host:ip地址

                 port:端口号
        """
        # print("__init__()---> host = %s ,port = %s" % (host, port))

        self.host = host
        self.port = port
        self.ftp = FTP()
        # 重新设置下编码方式
        #self.ftp.encoding = 'gbk'
        self.ftp.encoding = 'utf8'
        # 获取脚本路径
        path = os.path.dirname(os.path.realpath(__file__))
        self.log_file = open(path + "/log.txt", "a", encoding='utf-8')
        self.file_list = []

    def login(self, username, password):
        """ 初始化 FTP 客户端
            参数:
                  username: 用户名

                 password: 密码
            """
        try:
            timeout = 60
            socket.setdefaulttimeout(timeout)
            # 0主动模式 1 #被动模式
            self.ftp.set_pasv(True)
            # 打开调试级别2,显示详细信息
            # self.ftp.set_debuglevel(2)

            self.debug_print('开始尝试连接到 %s' % self.host)
            self.ftp.connect(self.host, self.port)
            self.debug_print('成功连接到 %s' % self.host)

            self.debug_print('开始尝试登录到 %s' % self.host)
            self.ftp.login(username, password)
            self.debug_print('成功登录到 %s' % self.host)

            self.debug_print(self.ftp.welcome)
        except Exception as err:
            self.deal_error("FTP 连接或登录失败 ,错误描述为:%s" % err)
            pass

    def is_same_size(self, local_file, remote_file):
        """判断远程文件和本地文件大小是否一致

           参数:
             local_file: 本地文件

             remote_file: 远程文件
        """
        try:
            remote_file_size = self.ftp.size(remote_file)
        except Exception as err:
            # self.debug_print("is_same_size() 错误描述为:%s" % err)
            remote_file_size = -1

        try:
            local_file_size = os.path.getsize(local_file)
        except Exception as err:
            # self.debug_print("is_same_size() 错误描述为:%s" % err)
            local_file_size = -1

        self.debug_print('local_file_size:%d  , remote_file_size:%d' % (local_file_size, remote_file_size))
        if remote_file_size == local_file_size:
            return 1
        else:
            return 0

    def download_file(self, local_file, remote_file):
        """从ftp下载文件
            参数:
                local_file: 本地文件

                remote_file: 远程文件
        """
        self.debug_print("download_file()---> local_path = %s ,remote_path = %s" % (local_file, remote_file))

        if self.is_same_size(local_file, remote_file):
            self.debug_print('%s 文件大小相同,无需下载' % local_file)
            return
        else:
            try:
                self.debug_print('>>>>>>>>>>>>下载文件 %s ... ...' % local_file)
                buf_size = 1024
                file_handler = open(local_file, 'wb')
                self.ftp.retrbinary('RETR %s' % remote_file, file_handler.write, buf_size)
                file_handler.close()
            except Exception as err:
                self.debug_print('下载文件出错,出现异常:%s ' % err)
                return

    def download_file_tree(self, local_path, remote_path):
        """从远程目录下载多个文件到本地目录
                       参数:
                         local_path: 本地路径

                         remote_path: 远程路径
                """
        print("download_file_tree()--->  local_path = %s ,remote_path = %s" % (local_path, remote_path))
        try:
            self.ftp.cwd(remote_path)
        except Exception as err:
            self.debug_print('远程目录%s不存在,继续...' % remote_path + " ,具体错误描述为:%s" % err)
            return

        if not os.path.isdir(local_path):
            self.debug_print('本地目录%s不存在,先创建本地目录' % local_path)
            os.makedirs(local_path)

        self.debug_print('切换至目录: %s' % self.ftp.pwd())

        self.file_list = []
        # 方法回调
        self.ftp.dir(self.get_file_list)

        remote_names = self.file_list
        self.debug_print('远程目录 列表: %s' % remote_names)
        for item in remote_names:
            file_type = item[0]
            file_name = item[1]
            local = os.path.join(local_path, file_name)
            if file_type == 'd':
                print("download_file_tree()---> 下载目录: %s" % file_name)
                self.download_file_tree(local, file_name)
            elif file_type == '-':
                print("download_file()---> 下载文件: %s" % file_name)
                self.download_file(local, file_name)
        self.ftp.cwd("..")
        self.debug_print('返回上层目录 %s' % self.ftp.pwd())
        return True

    def upload_file(self, local_file, remote_file):
        """从本地上传文件到ftp

           参数:
             local_path: 本地文件

             remote_path: 远程文件
        """
        if not os.path.isfile(local_file):
            self.debug_print('%s 不存在' % local_file)
            return

        if self.is_same_size(local_file, remote_file):
            self.debug_print('跳过相等的文件: %s' % local_file)
            return

        buf_size = 1024
        file_handler = open(local_file, 'rb')
        self.ftp.storbinary('STOR %s' % remote_file, file_handler, buf_size)
        file_handler.close()
        self.debug_print('上传: %s' % local_file + "成功!")

    def upload_file_tree(self, local_path, remote_path):
        """从本地上传目录下多个文件到ftp
           参数:

             local_path: 本地路径

             remote_path: 远程路径
        """
        if not os.path.isdir(local_path):
            self.debug_print('本地目录 %s 不存在' % local_path)
            return

        self.ftp.cwd(remote_path)
        self.debug_print('切换至远程目录: %s' % self.ftp.pwd())

        local_name_list = os.listdir(local_path)
        for local_name in local_name_list:
            src = os.path.join(local_path, local_name)
            if os.path.isdir(src):
                try:
                    self.ftp.mkd(local_name)
                except Exception as err:
                    self.debug_print("目录已存在 %s ,具体错误描述为:%s" % (local_name, err))
                self.debug_print("upload_file_tree()---> 上传目录: %s" % local_name)
                self.upload_file_tree(src, local_name)
            else:
                self.debug_print("upload_file_tree()---> 上传文件: %s" % local_name)
                self.upload_file(src, local_name)
        self.ftp.cwd("..")

    def close(self):
        """ 退出ftp
        """
        self.debug_print("close()---> FTP退出")
        self.ftp.quit()
        self.log_file.close()

    def debug_print(self, s):
        """ 打印日志
        """
        self.write_log(s)

    def deal_error(self, e):
        """ 处理错误异常
            参数:
                e:异常
        """
        log_str = '发生错误: %s' % e
        self.write_log(log_str)
        sys.exit()

    def write_log(self, log_str):
        """ 记录日志
            参数:
                log_str:日志
        """
        time_now = time.localtime()
        date_now = time.strftime('%Y-%m-%d', time_now)
        format_log_str = "%s ---> %s \n " % (date_now, log_str)
        print(format_log_str)
        self.log_file.write(format_log_str)

    def get_file_list(self, line):
        """ 获取文件列表
            参数:
                line:
        """
        file_arr = self.get_file_name(line)
        # 去除  . 和  ..
        if file_arr[1] not in ['.', '..']:
            self.file_list.append(file_arr)

    def get_file_name(self, line):
        """ 获取文件名
            参数:
                line:
        """
        pos = line.rfind(':')
        while (line[pos] != ' '):
            pos += 1
        while (line[pos] == ' '):
            pos += 1
        file_arr = [line[0], line[pos:]]
        return file_arr


if __name__ == "__main__":
    # 清除日志
    path = os.path.dirname(os.path.realpath(__file__))      # 脚本路径
    if os.path.exists(path + '/log.txt'):
        log_file = path + '/log.txt 'if os.sep == "/" else path + '\\' + 'log.txt'
        subprocess.Popen(f'rm -rf {log_file}', shell=True)
        time.sleep(1)

    my_ftp = MyFTP("xxx.ftp.upyun.com")
    my_ftp.login("xxx/xxx", "xxx")


    # 下载单个文件
    # my_ftp.download_file("E:/code_zone/image_bed/image/wallpaper/1.jpg", "/image/wallpaper/1.jpg")

    # 上传单个文件
    # my_ftp.upload_file("G:/ftp_test/Release/XTCLauncher.apk", "/App/AutoUpload/ouyangpeng/I12/Release/XTCLauncher.apk")

    # 下载目录
    # image.cpen.top/image/ → 本地 E:/code_zone/image_bed/image/    (本地图床目录, 又拍云路径)
    if os.sep == "\\":
        my_ftp.download_file_tree("E:/code_zone/image_bed/image/", "/image/")
    elif os.sep == "/":     # aliyun
        my_ftp.download_file_tree("/root/code_zone/image_bed/image/", "/image/")

    # 上传目录
    # 本地 E:/code_zone/image_bed/image/ → image.cpen.top/image/    (本地图床目录, 又拍云路径)
    if os.sep == "\\":      # Windows
        my_ftp.upload_file_tree("E:/code_zone/image_bed/image/", "/image/")    
        my_ftp.close()
    elif os.sep == "/":     # aliyun
        my_ftp.upload_file_tree("/root/code_zone/image_bed/image/", "/image/")  
        my_ftp.close()


# 命令
# python E:/code_zone/tools/python-ftp/ftp.py
# python3 /root/code_zone/tools/python-ftp/ftp.py

2.2.2 说明

my_ftp.login("用户名xxx/xxx", "密码xxx") 参考 https://techs.upyun.com/videos/cdnpage/creating_storage.html

后期又将脚本传到云服务器上,通过计划任务,每 15 分钟同步,保持 GitHub 与又拍云图床一致

# root @ CentOS in ~ [18:05:59]
$ crontab -l
*/15 * * * *  cd /root/code_zone/image_bed/; git pull; python3 /root/code_zone/tools/python-ftp/ftp.py; bash git.sh

迁移好图床后,博客中调用图片资源时 浏览器自动 http 跳 https,因为没有证书导致图片失效,于是又申请了 ssl 证书,上传至又拍云。

image-20220910180219146

2.3 编写批量修改文章内容的脚本#

源码参考 https://blog.csdn.net/qq_38150250/article/details/118026219

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 源码参考  https://blog.csdn.net/qq_38150250/article/details/118026219

import os
import re

# 文件查找 find . -name file_name -type f
# 查找函数:search_path 查找根路径 

# 获取文章路径
def search(search_path, search_result):
    # 获取当前路径下地所有文件
    all_file = os.listdir(search_path)
    # 对于每一个文件
    for each_file in all_file:
        # 若文件为一个文件夹
        if os.path.isdir(search_path + each_file):
            # 递归查找
            search(search_path + each_file + '/', search_result)
        # 如果是需要被查找的文件
        else:
            if re.findall('.*\.md$', each_file) == [each_file]:
            # 输出路径
                search_result.append(search_path + each_file)


# 替换 sed -i 's/old_str/new_str/'
# 文本替换 replace_file_name 需要替换的文件路径,replace_old_str 要替换的字符,replace_new_str 替换的字符
def replace(replace_file_name, replace_old_str, replace_new_str):
    with open(replace_file_name, "r", encoding = "UTF-8") as f1: 
        content = f1.read()
        f1.close()
        t = content.replace(replace_old_str, replace_new_str)
    with open(replace_file_name, "w", encoding = "UTF-8") as f2:
        f2.write(t)
    f2.close()


# 需要改的地方
#path = 'E:/code_zone/.history/20220831_blog/source/_posts/'
path_list = [
    'E:/code_zone/hexo-source/source/_posts/',
    'E:/code_zone/hexo-source-butterfly/source/_posts/',
    'E:/code_zone/hexo-source-diary/source/_posts/',
]
old_str = 'https://image.cpen.top/image/'
new_str = 'https://image.cpen.top/image/'
search_result = []

if __name__ == '__main__':
    result = []                 # 存放文件路径
    # 默认当前目录
    # path = os.getcwd()
    for path in path_list:
        search(path, result)    # 获取文章路径
    count = 0
    for file_name in result:
        replace(file_name, old_str, new_str)
        count += 1
        print("{} done  {}".format(file_name, count))

# 命令
# python E:/code_zone/tools/python-replace/replace.py

2.3.1 说明

search 函数指定文件类型为 .md,可获得文章的完整路径;

path_list 列表存放需要修改的文章父目录路径,可以递归查询子目录;

old_str 需要替换的内容

new_str 新内容

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.