You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
3.8 KiB

7 months ago
import os
import shutil
import paramiko
import argparse
import Contant
from LoggerUtils import Logger, initLogger
import configparser
import requests
import time
# python3 sftp.py --local="/mnt/tmp_srt_file" --logDir="./logs"
# python3 sftp.py --local="/mnt/test_file" --logDir="./logs"
if __name__ == "__main__":
# 读取参数
parser = argparse.ArgumentParser(description="")
parser.add_argument("--local", type=str, default="")
parser.add_argument('--logDir', type=str, default='')
args = parser.parse_args()
Contant.logDir = args.logDir
initLogger()
# 读取配置文件
config = configparser.ConfigParser()
config.read('sftp_config.ini')
# 获取SFTP配置信息
hostname = config.get('sftp_config', 'hostname')
port = config.getint('sftp_config', 'port')
username = config.get('sftp_config', 'username')
password = config.get('sftp_config', 'password')
Logger.info("host:{},port:{},username:{},password:{}".format(
hostname, port, username, password))
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sftp_client = None # 设置默认值
ssh_client.connect(hostname, port, username, password)
# 创建SFTP客户端
sftp_client = ssh_client.open_sftp()
Logger.info("SFTP客户端已经建立:{}".format(sftp_client))
remote_root = "/Inbound/YouTube Captions"
local_root = args.local
Logger.info("remote_root:{},local_root:{}".format(remote_root, local_root))
names = os.listdir(local_root)
for name in names:
# sftp创建文件夹
try:
sftp_client.chdir(remote_root + "/" + name)
except BaseException:
sftp_client.mkdir(remote_root + "/" + name)
sftp_client.chdir(remote_root + "/" + name)
# 遍历本地临时文件夹
srtList = os.listdir(local_root + "/" + name)
for srt in srtList:
# 获取远程文件路径以及本地文件路径
remotePath = remote_root + "/" + name + "/" + srt
localPath = local_root + "/" + name + "/" + srt
# 如果远程文件存在,则进行删除
try:
sftp_client.stat(remotePath)
# 如果文件存在,删除它
sftp_client.remove(remotePath)
Logger.info("Remote file '{}' deleted.".format(remotePath))
except FileNotFoundError:
Logger.info("Remote file '{}' not found.".format(remotePath))
# 上传本地文件
try:
# 判断远程地址长度,过长需要截取一部分
if len(remotePath) > 120:
remotePath = remotePath[:-20] + ".srt"
# 判断本地文件是否存在,存在则上传
if os.path.exists(localPath):
Logger.info("本地文件 '{}' 存在,开始上传.".format(localPath))
sftp_client.put(localPath, remotePath, confirm=False)
os.remove(localPath)
else:
Logger.info("本地文件 '{}' 不存在,无法上传.".format(localPath))
except Exception as e:
Logger.info("上传失败 '{}' 文件名长度{}".format(
remotePath, len(remotePath)))
Logger.error(e)
sftp_client.close()
sftp_client = ssh_client.open_sftp()
# 发送钉钉消息
webhook = "https://oapi.dingtalk.com/robot/send?access_token=c8c8d7d42c4eecd449dd303025ef968f647d1d8e8694e3fabc0ab5770d646dcb"
jsonData = {
"msgtype": "text",
"text": {
"content": "[Youtube]sftp finished"
}
}
requests.post(webhook, json=jsonData)
Logger.info("sftp发送钉钉消息成功...")