Python实现FTP文件对比与数据库记录

Python代码:判断FTP上文件是否相同,并写入数据库

在实际开发中,我们有时需要判断FTP服务器上两份文件是否一致,并将结果存储数据库。以下是实现此需求的步骤与示例代码:

步骤

  1. 连接FTP服务器,下载或读取两个文件。
  2. 计算文件哈希值(MD5或SHA256),确保文件内容一致性。
  3. 比较文件哈希结果,判断文件是否相同。
  4. 写入数据库保存对比结果。

示例代码

import hashlib
from ftplib import FTP
import sqlite3

# 连接FTP函数
def connect_ftp(host, user, passwd):
    ftp = FTP(host)
    ftp.login(user=user, passwd=passwd)
    return ftp

# 获取文件哈希值
def get_file_hash(ftp, filepath):
    hash_md5 = hashlib.md5()
    ftp.retrbinary(f'RETR {filepath}', hash_md5.update)
    return hash_md5.hexdigest()

# 写入数据库
def write_to_db(filename, result):
    conn = sqlite3.connect('file_comparison.db')
    cursor = conn.cursor()
    cursor.execute('''CREATE TABLE IF NOT EXISTS file_check (filename TEXT, match TEXT)''')
    cursor.execute('INSERT INTO file_check (filename, match) VALUES (?, ?)', (filename, result))
    conn.commit()
    conn.close()

# 主流程
ftp = connect_ftp('ftp.example.com', 'username', 'password')
file1_hash = get_file_hash(ftp, 'path/to/file1')
file2_hash = get_file_hash(ftp, 'path/to/file2')

result = 'Match' if file1_hash == file2_hash else 'Mismatch'
write_to_db('file1_vs_file2', result)

ftp.quit()

代码说明

  • connect_ftp 函数用于连接FTP服务器
  • get_file_hash 函数用于获取文件的哈希值
  • write_to_db 函数将对比结果写入SQLite数据库

运行该代码后,可以在 file_comparison.db 数据库中查询对比结果。

py 文件大小:1.38KB