> For the complete documentation index, see [llms.txt](https://book.bsdcn.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://book.bsdcn.org/di-35-zhang-fu-wu-qi/di-35.2-jie-samba-wen-jian-gong-xiang.md).

# 35.2 Samba 文件共享

## Samba 概述

Samba 是服务器消息块（Server Message Block，SMB）与通用互联网文件系统（Common Internet File System，CIFS）协议的自由软件重新实现，其核心目标在于实现 UNIX 系统与 Windows 网络环境之间的互操作性。

就体系结构而言，smbd（文件与打印服务守护进程）与 nmbd（NetBIOS 名称服务守护进程）协同工作：smbd 处理文件共享与打印服务请求，nmbd 提供 NetBIOS 名称解析与网络浏览服务。

```sh
Windows 客户端
   │
   ├── 文件/打印请求 ──► smbd（文件与打印服务守护进程）
   │                      TCP 445 / TCP 139
   │
   └── NetBIOS 名称解析 ──► nmbd（NetBIOS 名称服务守护进程）
                           UDP 137 / UDP 138
```

Samba 需要在防火墙中放行以下端口：

| 协议  | 端口  | 服务            | 必需条件                |
| --- | --- | ------------- | ------------------- |
| TCP | 139 | NetBIOS 会话服务  | 仅 SMBv1（NT1）协议时方为必需 |
| UDP | 137 | NetBIOS 名称服务  | 仅 SMBv1（NT1）协议时方为必需 |
| UDP | 138 | NetBIOS 数据报服务 | 仅 SMBv1（NT1）协议时方为必需 |
| TCP | 445 | SMB over TCP  | 始终必需                |

若配置 `min protocol = SMB2` 及以上，可仅开放 TCP 445。

Samba 作者 Andrew Tridgell 在开发早期因项目原名“smbserver”已被 Syntax 公司（其商业产品 TotalNet Advanced Server 拥有该名称商标）主张商标权而须更名，新名称通过 Unix 命令 `grep -i '^s.*m.*b' /usr/share/dict/words` 从系统词典中搜索按顺序包含 s、m、b 三个字母的单词而得，“Samba”即由此而来。需要指出的是，“samba”在葡萄牙语及英语中亦有“桑巴舞”之义，此为词形上的巧合。

## 安装 Samba

Samba 有两种主要安装方式：

* 使用 pkg 安装：

```sh
# pkg install samba423
```

* 或使用 Ports 安装：

```sh
# cd /usr/ports/net/samba423/
# make install clean
```

* 查看安装信息：

```sh
# pkg info -D samba423
```

## 相关项目结构

```sh
/
├── usr
│   └── local
│       ├── etc
│       │   └── smb4.conf                # Samba 主配置文件
│       └── bin
│           └── samba-tool               # Samba 综合管理工具
├── var
│   ├── db
│   │   └── samba4                       # Samba 相关数据库目录
│   └── log
│       └── samba4                       # Samba 日志目录
├── etc
│   ├── rc.conf                           # 系统启动配置文件
│   ├── resolv.conf                       # DNS 解析配置文件
│   ├── sysctl.conf                        # 系统参数配置文件
│   └── nsswitch.conf                      # 名称服务切换配置文件
└── samba
    └── testshare                         # Samba 共享目录
```

## 基础配置

### 编辑 Samba 配置文件

创建 Samba 配置文件 **/usr/local/etc/smb4.conf**，写入以下内容并保存：

```ini
[global]
    min protocol = SMB2

[test_share]
    comment = root's stuff
    path = /home/ykla/test
    valid users = ykla
    public = no
    browseable = yes
    writable = yes
    printable = no
    create mask = 0644
```

注释说明：

| 配置项                      | 说明                                     |
| ------------------------ | -------------------------------------- |
| `[global]`               | 全局配置段，适用于所有共享项                         |
| `min protocol = SMB2`    | 将最小支持协议限制为 SMB2，以便较新版本 Windows 访问      |
| `[test_share]`           | 定义共享名称                                 |
| `comment = root's stuff` | 该共享的描述信息，Windows 资源管理器浏览共享时将显示此文本      |
| `path = /root`           | 共享的实际路径为 **/root**，**不建议** 在生产环境中共享该目录 |
| `valid users = ykla`     | 仅允许用户 ykla 访问 Samba 服务器                |
| `public = no`            | 不允许匿名访问（等价于 `guest ok = no`）           |
| `browseable = yes`       | 可在网络邻居中浏览该共享                           |
| `writable = yes`         | 允许客户端写入该目录                             |
| `printable = no`         | 本共享非打印机共享                              |
| `create mask = 0644`     | 新建文件的默认权限为 0644，避免文件被意外赋予可执行属性         |

### 目录权限调整

准备目录，调整目录权限：

```sh
$ mkdir -p /home/ykla/test
# chown -R ykla:ykla /home/ykla/test
```

此时，目录 **/home/ykla/test** 的权限应如下所示：

```sh
drwxr-xr-x  2 ykla ykla  uarch    2 Jun 10 15:37 test
```

将若干文件置入目录 **/home/ykla/test** 便于测试。

### 用户管理

出于安全考虑，避免创建 Samba root 用户。

Samba 仅识别已纳入其内部数据库的账号，因此需将 FreeBSD 用户账户映射至 Samba 账号数据库后，Windows 客户端方可访问共享。pdbedit(8) 支持基于 smbpasswd、ldap、nis+ 与 tdb 等多种后端的用户数据库。可使用 pdbedit(8) 将已有的 FreeBSD 用户账户 `ykla` 映射至 Samba：

```sh
# pdbedit -a -u ykla
new password: # 此处为 Samba 用户 ykla 设置密码
retype new password: # 重复输入密码
Unix username:        ykla
NT username:
Account Flags:        [U          ]
User SID:             S-1-5-21-3200006731-1126116281-3495519786-1000
Primary Group SID:    S-1-5-21-3200006731-1126116281-3495519786-513
Full Name:            User &
Home Directory:       \\YKLA\ykla

……以下省略部分输出……
```

此处设置的密码可以与 FreeBSD 用户账户不同，只是用于验证 Samba 服务器的密码。

### 启动 Samba 服务

* 将 Samba 服务设置为开机启动：

```sh
# service samba_server enable
```

* 启动 Samba 服务

```sh
# service samba_server start
```

* 查看 Samba 服务的运行状态：

```sh
# service samba_server status
nmbd is running as pid 5250.
smbd is running as pid 5255.
```

Samba 包含 nmbd、smbd 及 winbindd 三个守护进程，其中 nmbd 与 smbd 由 `samba_server_enable` 统一管理，winbindd 须通过 `winbindd_enable` 单独启用（本例中无须启用）。

## 使用 Samba 共享服务

* 在 Windows 系统中访问共享文件夹：同时按下 **Windows 徽标键 + R** 组合键以打开“运行”对话框，输入以下 UNC 路径（请将示例 IP 地址替换为实际值）：

```powershell
\\192.168.179.128
```

![Windows 访问网络共享资源](/files/jcKVtUK2an8ktVFzOzPD)

在凭据提示框中输入 Samba 用户名 `ykla` 及其密码：

![键入 Samba 用户名](/files/oh6oq8LcCx7mU4dzEqqJ)

连接成功，可以看到共享的项目名称“test\_share”。

![连接 Samba](/files/OS8S5VAsB2sNqQqizcL2)

进一步点击共享项目“test\_share”，浏览文件：

![连接 Samba](/files/ACyHJbFxB9r0DuAhVNvZ)

读写操作均正常。

## 域成员配置

### 系统参数优化

```sh
# echo "kern.maxfiles=25600" >> /etc/sysctl.conf        # 设置系统最大打开文件数
# echo "kern.maxfilesperproc=16384" >> /etc/sysctl.conf # 设置每个进程最大打开文件数
# echo "net.inet.tcp.sendspace=65536" >> /etc/sysctl.conf  # 设置 TCP 发送缓冲区大小
# echo "net.inet.tcp.recvspace=65536" >> /etc/sysctl.conf  # 设置 TCP 接收缓冲区大小
```

### Kerberos 认证

```ini
[libdefaults]
    default_realm = SVROS.COM        # 设置 Kerberos 默认领域
    dns_lookup_realm = false         # 禁用通过 DNS 查找域
    dns_lookup_kdc = true            # 启用通过 DNS 查找 KDC
    ticket_lifetime = 24h            # 设置票据有效期为 24 小时
    renew_lifetime = 7d              # 设置票据可续期时间为 7 天
    forwardable = yes                # 允许票据可转发
```

### 配置名称服务

配置 NSS，使系统依次通过本地文件与 Winbind 解析用户记录：

```sh
# sed -i '' -e "s/^passwd:.*/passwd: files winbind/" /etc/nsswitch.conf
```

配置 NSS，使系统依次通过本地文件与 Winbind 解析组记录：

```sh
# sed -i '' -e "s/^group:.*/group: files winbind/" /etc/nsswitch.conf
```

### Samba 主配置文件

```ini
[global]
	workgroup = SVROS
	server string = Samba Server Version %v
	security = ads
	realm = SVROS.COM
	domain master = no
	local master = no
	preferred master = no
	use sendfile = true

	idmap config * : backend = tdb
	idmap config * : range = 100000-299999
	idmap config SVROS : backend = rid
	idmap config SVROS : range = 10000-99999
	winbind separator = +
	winbind enum users = yes
	winbind enum groups = yes
	winbind use default domain = yes
	winbind nested groups = yes
	winbind refresh tickets = yes
	template homedir = /home/%D/%U
	template shell = /bin/false

	client use spnego = yes
	restrict anonymous = 2
	log file = /var/log/samba4/log.%m
	max log size = 50

#============================ 自定义共享信息 ==============================

[testshare]
	comment = Test share
	path = /samba/testshare
	read only = no
	force group = "Domain Users"
	directory mode = 0770
	force directory mode = 0770
	create mode = 0660
	force create mode = 0660
```

上述 `testshare` 共享段中 `create mode` 与 `force create mode` 两项用于实际运行时调整新建文件的权限，属可选配置：

```ini
create mode = 0750
force create mode = 0750
```

## 域管理

### 服务自启动配置

设置 Winbind 服务开机自动启动：

```sh
# service winbindd enable
```

将主机加入 Active Directory 域，不更新 DNS：

```sh
net ads join --no-dns-updates -U administrator   # 
net ads testjoin                                 # 测试主机是否成功加入域
# 应输出 "Join is OK"
# 后续：在域控制器上打开 DNS 管理控制台（MMC），为该 BSD 服务器添加一条 A 记录，以便客户端解析
```

### Kerberos 认证验证

```sh
kinit administrator   # 使用管理员账户获取 Kerberos 票据，输入密码后应正常返回提示符
klist                  # 查看当前 Kerberos 票据缓存
# 输出示例：
Credentials cache: FILE:/tmp/krb5cc_0
    Principal: administrator@SVROS.COM

Issued                Expires               Principal
Dec  6 10:15:39 2021  Dec  7 10:15:39 2021  krbtgt
```

### Winbind 服务验证

```sh
wbinfo -u
# 应返回域用户列表

wbinfo -g
# 应返回域用户组列表

getent passwd
# 用户列表末尾应包含 UID 大于 10000 的域用户

getent group
# 用户组列表末尾应包含 GID 大于 10000 的域用户组
```

若 `wbinfo` 命令返回错误，可重启 Samba 服务后再次验证：

```sh
# service samba_server restart
```

### 共享目录配置

```sh
# mkdir -p /samba/testshare                                # 创建共享目录
# chown "administrator:domain users" /samba/testshare   # 设置目录所有者为 administrator，组为 domain users
# chmod 0770 /samba/testshare                              # 设置目录权限为 0770（属主与属组可读写执行，其他用户无任何权限）
```

如仅允许属主可读写、属组仅可读取，可执行：

```sh
# chmod 0750 /samba/testshare	# 设置目录权限为 0750（属主可读写执行，属组可读执行，其他用户无任何权限）
```

如仅允许属主可读写、属组及其他用户均不可访问，可执行：

```sh
# chmod -R 0700 /samba/testshare	# 递归设置目录及其内容权限为 0700（仅属主可读写执行）
```

## 故障排除

Samba 日志文件默认位于 **/var/log/samba4** 目录下，文件名以 `log.` 为前缀并附带客户端主机名，可据此排查连接与认证故障。

## 参考文献

* HERTEL C. Samba: An Introduction\[EB/OL]. (2001)\[2026-04-18]. <https://www.samba.org/samba/docs/SambaIntro.html>. Samba 官方文档，说明 SMB/CIFS 协议实现及名称来源。
* Microsoft Corporation. \[MS-CIFS]: Common Internet File System (CIFS) Protocol\[EB/OL]. (2025-06-11)\[2026-04-18]. <https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-cifs/934c2faa-54af-4526-ac74-6a24d126724e>. Microsoft 开放规范，CIFS 是 SMB 协议的一个方言（dialect）。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://book.bsdcn.org/di-35-zhang-fu-wu-qi/di-35.2-jie-samba-wen-jian-gong-xiang.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
