django 调用paramiko 向windows 上传文件

发布于:2025-06-19 ⋅ 阅读:(9) ⋅ 点赞:(0)

在 Django 中使用 paramiko 库来通过 SSH 协议上传文件到 Windows 服务器是一种常见需求。以下是一个详细的步骤指南,帮助你在 Django 项目中实现这一功能。

步骤 1: 安装必要的库
首先,确保你的 Django 项目中安装了 paramiko 库。你可以通过 pip 来安装它:

pip install paramiko

步骤 2: 编写上传文件的视图
在你的 Django 应用中,创建一个视图来处理文件上传和通过 SSH 上传到服务器。

import paramiko
from django.http import JsonResponse
from django.core.files.storage import FileSystemStorage
 
def upload_file(request):
    if request.method == 'POST':
        uploaded_file = request.FILES['document']
        fs = FileSystemStorage()
        filename = fs.save(uploaded_file.name, uploaded_file)
        url = fs.url(filename)
        
        # 使用 paramiko 上传文件到 Windows 服务器
        upload_to_server(url)
        
        return JsonResponse({'message': 'File uploaded successfully', 'url': url})
    else:
        return JsonResponse({'error': 'Invalid request method'}, status=400)
 
def upload_to_server(local_file_path):
    ssh_host = 'your.windows.server.ip'
    ssh_port = 22  # 默认端口是22
    ssh_username = 'your_username'
    ssh_password = 'your_password'
    remote_path = '/path/to/remote/directory/'
    
    try:
        # 创建 SSH 客户端实例
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(ssh_host, port=ssh_port, username=ssh_username, password=ssh_password)
        
        # 使用 SCP 上传文件
        sftp = client.open_sftp()
        sftp.put(local_file_path, remote_path + uploaded_file.name)
        sftp.close()
        client.close()
        print("File uploaded successfully to the server.")
    except Exception as e:
        print(f"Error uploading file: {e}")

步骤 3: 配置 URLconf
在你的 Django 项目的 urls.py 文件中添加一个 URL 模式来指向你的视图函数。

from django.urls import path
from .views import upload_file
 
urlpatterns = [
    path('upload/', upload_file, name='upload_file'),
]
步骤 4: 创建前端表单(可选)
你可以在 HTML 模板中创建一个简单的文件上传表单。例如,在 templates/upload.html:

<!DOCTYPE html>
<html>
<head>
    <title>Upload File</title>
</head>
<body>
    <h1>Upload a file</h1>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="file" name="document">
        <button type="submit">Upload</button>
    </form>
</body>
</html>

步骤 5: 测试你的应用
运行你的 Django 项目,并通过浏览器访问上传表单页面进行测试。确保服务器配置正确,并且你有适当的权限来上传文件到目标路径。

注意:
确保服务器的防火墙和 SSH 设置允许从你的 IP 地址进行连接。

对于生产环境,考虑使用密钥认证代替密码认证以提高安全性。你可以使用 paramiko.RSAKey.from_private_key_file 来加载私钥进行认证。

处理文件上传时,确保对上传的文件进行适当的验证和清理,以避免安全风险。例如,限制文件类型和大小。

通过以上步骤,你应该能够在 Django 应用中通过 SSH 使用 paramiko 上传文件到 Windows 服务器。


网站公告

今日签到

点亮在社区的每一天
去签到