You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

树莓派局域网内通过Python传图至Samba服务器遇curl连接失败

解决树莓派上传图片至Samba服务器的问题

问题根源

curl 默认不支持SMB/CIFS协议,直接使用 smb:// 格式的URL会导致连接失败,这就是你遇到 curl: (7) Couldn't connect to server 错误的核心原因。

可行解决方案

方案1:用smbclient替代curl

smbclient 是专门处理SMB协议的命令行工具,先在树莓派上安装:

sudo apt update && sudo apt install smbclient

然后通过Python的subprocess调用上传命令:

import subprocess

local_img = "/home/pi/Desktop/test.png"
smb_target = "//10.51.112.128/home/thomas/thomasdrive/destination"
user = "thomas"
pwd = "87651234"

# 构造smbclient上传指令
cmd = [
    "smbclient", smb_target,
    "-U", f"{user}%{pwd}",
    "-c", f"put {local_img}"
]

try:
    subprocess.run(cmd, check=True, capture_output=True, text=True)
    print("图片上传成功")
except subprocess.CalledProcessError as e:
    print(f"上传失败: {e.stderr}")

方案2:使用Python专用SMB库(pysmb)

直接用Python库操作SMB,无需依赖外部命令:

  1. 安装pysmb:
pip install pysmb
  1. 编写上传代码:
from smb.SMBConnection import SMBConnection

local_img = "/home/pi/Desktop/test.png"
server_ip = "10.51.112.128"
share_name = "home"  # 替换为Ubuntu上实际的Samba共享名称
remote_dir = "thomas/thomasdrive/destination"
user = "thomas"
pwd = "87651234"
client_hostname = "raspberrypi"  # 树莓派主机名,可自定义

# 建立SMB连接
conn = SMBConnection(user, pwd, client_hostname, server_ip, use_ntlm_v2=True)
if conn.connect(server_ip, 139):
    with open(local_img, 'rb') as f:
        conn.storeFile(share_name, f"{remote_dir}/test.png", f)
    conn.close()
    print("图片上传成功")
else:
    print("无法连接到Samba服务器")

注意:share_name 必须是Ubuntu服务器上配置的Samba共享名,不是完整路径。

方案3:挂载Samba共享到本地

把Samba共享目录挂载到树莓派本地,之后上传就像操作本地文件:

  1. 安装挂载工具:
sudo apt install cifs-utils
  1. 创建挂载点:
sudo mkdir /mnt/samba_share
  1. 临时挂载(重启后失效):
sudo mount -t cifs //10.51.112.128/home/thomas/thomasdrive/destination /mnt/samba_share -o username=thomas,password=87651234
  1. 配置开机自动挂载(可选):
    编辑 /etc/fstab 文件,添加一行:
//10.51.112.128/home/thomas/thomasdrive/destination /mnt/samba_share cifs username=thomas,password=87651234 0 0
  1. Python上传代码(直接复制文件):
import shutil

local_img = "/home/pi/Desktop/test.png"
dest_path = "/mnt/samba_share/test.png"

try:
    shutil.copy(local_img, dest_path)
    print("图片上传成功")
except Exception as e:
    print(f"上传失败: {str(e)}")

额外排查要点

  • 确认Ubuntu的Samba服务运行正常:sudo systemctl status smbd
  • 检查Samba共享目录权限,确保thomas用户有写入权限
  • 验证树莓派能ping通服务器:ping 10.51.112.128
  • 确认服务器防火墙未阻挡139/445端口(SMB默认端口)

内容的提问来源于stack exchange,提问作者tommyokie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 13:55:29