xy/kk_sftp_save_api.py
2025-12-03 16:13:38 +08:00

91 lines
3.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import paramiko
import os
import posixpath
def mkdir_p(sftp, remote_dir):
"""递归创建远程目录(类似 mkdir -p"""
if remote_dir == '/':
return # 根目录假设已存在
try:
sftp.stat(remote_dir)
return
except FileNotFoundError:
pass
parent_dir = posixpath.dirname(remote_dir)
if parent_dir != '/':
mkdir_p(sftp, parent_dir)
try:
sftp.mkdir(remote_dir)
except Exception as e:
raise RuntimeError(f"创建目录失败: {remote_dir}, 错误: {str(e)}")
def sftp_upload(host, port, username, password, local_path, remote_path,file_name):
# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(host, port, username, password)
# 创建SFTP会话
sftp = ssh.open_sftp()
result = False
return_path = ""
try:
mkdir_p(sftp, remote_path)
# 上传文件
target_path = remote_path+"/"+file_name
sftp.put(local_path, target_path)
print(f"文件上传成功: {local_path} -> {target_path}")
result = True
return_path = target_path
finally:
# 关闭SFTP会话和SSH连接
sftp.close()
ssh.close()
return result,return_path
def sftp_upload_one_file(local_path,mkdir_remote_path,file_name):
HOSTNAME = '47.106.222.181'
PORT = 25078 # 默认SSH端口是22
USERNAME = 'user'
PASSWORD = 'password'
# local_path = '/home/cat/shuikeWorkSpace/vscode_code/2025_workspace/shuike_dev/3rdparty/rk3576_NDK/app/node/save_data_app/Snipaste_2025-07-22_16-28-55.jpg' # 本地文件路径
# remote_path = '/files/
remote_base_path = "/files/uploads/device_info" #文件系统的鹿鸣
remote_path = remote_base_path+"/"+ mkdir_remote_path # 远程文件路径
print("remote_path1:",remote_path)
flag,remote_path = sftp_upload(HOSTNAME, PORT, USERNAME, PASSWORD, local_path, remote_path,file_name)
if flag:
print("上传成功")
#远程路径
print("remote_path2:",remote_path)
remote_path_without_prefix = remote_path.replace("/files/", "") # /uploads/device_info
get_url = "http://47.106.222.181:25079/sftp-images/" + remote_path_without_prefix
# http://47.106.222.181:25079/sftp-images/uploads/device_info
print("get_url:",get_url)
return get_url
if __name__ == "__main__":
# 使用示例
#本地图片
# local_path = '/home/cat/shuikeWorkSpace/vscode_code/2025_WorkSpace/snapshot_1.jpg' # 本地文件路径
local_path = r'D:/ntxm/sensor_data/snapshot_1.jpg'
#远程路径
mkdir_remote_path = "d80801000058/sensor/20250814/20250814_01" #本地存储路径
#图片链接
file_name = 'Snipaste_2025-07-22_16-28-55.jpg' # 远程文件路径
#进行上传
down_url = sftp_upload_one_file(local_path,mkdir_remote_path,file_name)