跳转到内容
搜索 Fedora 文档

    浏览当前文档目录

    Samba 文件共享:Linux 与 Windows/macOS 互通

    Samba 让 Windows/macOS 直接访问 Linux 目录。这篇把「配了共享但连不上/打不开文件」的所有实测坑串起来。

    Terminal window
    sudo dnf install -y samba samba-client

    实测 samba 4.25.0。samba 是服务端,samba-client 带 smbclient 调试工具(必装,不然没法本机验证)。

    准备目录与配置:

    Terminal window
    sudo mkdir -p /srv/smbtest
    echo "hello from samba" | sudo tee /srv/smbtest/hello.txt

    /etc/samba/smb.conf:

    [global]
    server role = standalone server
    map to guest = Bad User
    [share]
    path = /srv/smbtest
    read only = yes
    guest ok = yes
    Terminal window
    sudo systemctl enable --now smb

    第一个坑:Access denied 不是配置错

    Section titled “第一个坑:Access denied 不是配置错”

    配置如上、服务 active,但实测:

    $ smbclient //127.0.0.1/share -N -c "ls"
    Anonymous login successful
    NT_STATUS_ACCESS_DENIED listing \*

    ls 都被拒。testparm -s 看配置没有问题、目录 755、文件 644——是 SELinux。普通目录的标签是 var_t/user_tmp_t,smbd 没权限读:

    Terminal window
    sudo semanage fcontext -a -t samba_share_t "/srv/smbtest(/.*)?"
    sudo restorecon -Rv /srv/smbtest

    实测打完标签立刻通:

    $ smbclient //127.0.0.1/share -N -c "get hello.txt /tmp/h.txt"
    $ cat /tmp/h.txt
    hello from samba

    匿名只读适合分发包;实际共用要账号:

    [secure]
    path = /srv/smbtest
    read only = no
    guest ok = no
    valid users = labuser

    设置密码——smbpasswd 交互式在脚本里会失败(实测 Unable to get new password),非交互姿势:

    Terminal window
    printf "密码\n密码\n" | sudo smbpasswd -s -a labuser

    实测 Windows 访问路径 \\服务器IP\secure,macOS 在 Finder 的「连接服务器」填 smb://服务器IP/secure。

    Terminal window
    sudo dnf install -y cifs-utils
    sudo mount -t cifs //服务器IP/secure /mnt/share -o \
    username=labuser,uid=$(id -u),gid=$(id -g)

    写进 fstab 用 credentials 文件避免密码裸奔:

    //服务器IP/secure /mnt/share cifs credentials=/etc/smb-cred,uid=1000,gid=1000 0 0

    /etc/smb-cred(600 权限):

    username=labuser
    password=密码
    Terminal window
    sudo firewall-cmd --add-service=samba --permanent && sudo firewall-cmd --reload

    Windows 资源管理器里直接 \\IP\share 永远可用;要让主机名被发现还需要 mDNS/NetBIOS(avahi 已默认装,Windows 侧较新版本支持 mDNS)。

    1. systemctl is-active smb
    2. smbclient //127.0.0.1/share -N -c "ls" 本机回环先通
    3. Access denied → ls -lZ 看 SELinux 标签,缺 samba_share_t 就 restorecon
    4. NT_STATUS_LOGON_FAILURE → 密码错或用户没 smbpasswd -a
    5. 远程连不上 → 防火墙 --add-service=samba
    现象原因
    匿名 ls 都 Access deniedSELinux 标签不是 samba_share_t
    smbpasswd 交互卡住脚本里用 `printf “pw\npw\n”
    Windows 看得到打不开目录权限与 smb.conf 的 valid users 叠加限制
    写入失败(只读)read only = no 没写,或文件系统只读挂载
    中文文件名乱码客户端与 unix charset 不一致,默认 utf-8 一般无需改
    重启后共享消失smb 没设开机自启(enable)