Samba

出自 Arch Linux 中文维基

Samba 是用於 Linux 和 Unix的標準 Windows 互操作性程序套件。自 1992 年以來,Samba 為所有使用 SMB/CIFS 協議的客戶端提供了安全、穩定和快速的文件和打印服務,例如所有版本的 DOS 和 Windows、OS/2、Linux 和許多其他系統。

要通過 Samba 共享文件,請參閱#伺服器部分;要訪問其他機器上通過 Samba 共享的文件,請參見#客戶端部分。

伺服器[編輯 | 編輯原始碼]

安裝[編輯 | 編輯原始碼]

安裝 samba 軟件包。

Samba 服務的配置文件是 /etc/samba/smb.confsmb.conf(5)提供了詳細的文檔。

samba 軟件包沒有提供此文件,啟動 smb.service 前需要先創建這個文件。

Samba 的 Git 倉庫可以獲取到示例文件 smb.conf.default,可參考其配置 /etc/samba/smb.conf

注意:

本文內容或本節內容已經過期。

原因: 參見 Talk:Samba#logging to systemd。 (在Talk:Samba討論)
  • 從上面獲取的默認配置文件裡把日誌 log file 設置到一個不能寫的地方,這會引起錯誤。下列任一辦法可以解決這個問題:
    • 把日誌文件配置到可寫的路徑:log file = /var/log/samba/%m.log
    • 把日誌存到非文件後端:logging = syslog 配合 syslog only = yes,或者使用 logging = systemd
  • 如果需要的話;在 [global] 部份中指定的 workgroup 需要對應 Windows 工作組的名稱 (默認是 WORKGROUP)。
  • 默認配置會將用戶的主目錄以可寫權限暴露到網絡上。如果你擔心該操作導致的安全問題,可以考慮將 [homes] 一節完全註釋掉。詳細信息可參考 smb.conf(5) § The [homes] section
提示:修改 smb.conf 文件後,運行 testparm(1) 命令看看有沒有語法錯誤。

啟用並啟動服務[編輯 | 編輯原始碼]

要通過 SMB 提供基礎文件共享服務,請啟用/啟動 smb.service。詳情請參考 smbd(8)

如果你要讓伺服器可通過 NetBIOS 主機名訪問,需在 smb.conf 中的 netbios name 選項配置目標名稱,並啟用/啟動 nmb.service。詳情請參考 smbd(8)

注意: 無需用到 nmb.service。但對於部分主機,需要該服務才能通過主機名(例如 smb://hostname/)訪問 Samba 伺服器。如果你的網絡中只包含運行 Windows 10 及更高版本的設備,可以考慮同時安裝 WSD 守護進程來使你的伺服器出現在「網絡」視圖中。

使伺服器可被發現[編輯 | 編輯原始碼]

安裝 avahi 軟件包, 然後啟用/啟動 avahi-daemon.service 以通過 Zeroconf 使 Samba 伺服器可被發現。這應當在多數非 Windows 文件管理器上可用(macOS Finder,Linux 和 BSD 上各種基於 GUI 的文件管理器,等等)。

如果 avahi-daemon.service 尚未運行,伺服器仍可被訪問,僅不可被發現。也就是說,它不會出現在文件管理器中,但你仍可直接通過 IP 或者域名連接它。

Windows 資源管理器單獨依賴 WS-Directory 協議;參見 #Windows 1709 及更高版本無法在「網絡」視圖中發現 Samba 伺服器

配置防火牆[編輯 | 編輯原始碼]

如果使用了 防火牆,請記得打開需要的端口(通常是 137-139 + 445)。完整列表請查看 Samba 所需端口

UFW 規則[編輯 | 編輯原始碼]

A Ufw App Profile for SMB/CIFS is included by default with the default installation of UFW in ufw-fileserver.

Allow Samba by running ufw allow CIFS as root.

If you deleted the profile, create/edit /etc/ufw/applications.d/samba and add the following content:

[Samba]
title=LanManager-like file and printer server for Unix
description=The Samba software suite is a collection of programs that implements the SMB/CIFS protocol for unix systems, allowing you to serve files and printers to Windows, NT, OS/2 and DOS clients. This protocol is sometimes also referred to as the LanManager or NetBIOS protocol.
ports=137,138/udp|139,445/tcp

Then load the profile into UFW run ufw app update Samba as root.

Then finally, allow Samba by running ufw allow Samba as root.

firewalld 服務[編輯 | 編輯原始碼]

To configure firewalld to allow Samba in the home zone, run:

# firewall-cmd --permanent --add-service={samba,samba-client,samba-dc} --zone=home

The three services listed are:

--permanent ensures the changes remain after firewalld.service is restarted.

基礎配置[編輯 | 編輯原始碼]

用戶管理[編輯 | 編輯原始碼]

下列章節描述了如何創建本地(tdbsam)Samba 用戶數據庫。出於用戶驗證及其他用途,Samba 也可以被綁定到一個 Active Directory 域中,或是自己作為 Active Directory 域控制器,或者被用作 LDAP 伺服器。

添加用戶[編輯 | 編輯原始碼]

Samba 需要 Linux 賬戶才能使用 - 可以使用已有賬戶或創建新用戶

注意: 用戶/用戶組 nobody 應已在系統中創建。它被作為默認來賓賬戶,可用於包含 guest ok = yes 的共享,使得用戶無需登錄即可使用該共享。

雖然 Samba 和 Linux 系統共享用戶名,但 Samba 使用單獨的密碼管理。將下面的 samba_user 替換為選擇的 Samba 用戶:

# smbpasswd -a samba_user

根據伺服器角色的差異,可能需要為 Samba 用戶賬戶修改已有的文件權限與屬性

要讓新創建的用戶僅能訪問 Samba 遠程文件伺服器,可以禁用其它登錄選項:

  • 禁用 shell - usermod --shell /usr/bin/nologin --lock samba_user
  • 禁用 SSH 登錄 - 編輯 /etc/ssh/sshd_config 文件,修改 AllowUsers 選項

另請參閱安全一文來加固系統。

查詢用戶[編輯 | 編輯原始碼]

使用 pdbedit(8) 命令查詢現有用戶:

# pdbedit -L -v
更改 samba 用戶的密碼[編輯 | 編輯原始碼]

使用 smbpasswd 修改 samba 用戶的密碼:

# smbpasswd samba_user

創建匿名共享[編輯 | 編輯原始碼]

1. 創建新 Linux 用戶,匿名 Samba 用戶將映射到該用戶。

# useradd guest -s /bin/nologin
注意: 用戶名可以是任意合規 Linux 用戶名,不限於「guest」。該用戶不需要作為 Samba 用戶。

2. 在 /etc/samba/smb.conf 添加下列內容:

/etc/samba/smb.conf
...
[global]
security = user
map to guest = bad user
guest account = guest

[guest_share]
    comment = guest share
    path = /tmp/
    public = yes
    only guest = yes
    writable = yes
    printable = no

現在匿名用戶將被映射到 Linux 用戶 guest,並可以訪問 guest_share.path 中定義的任何目錄,在該例子中為 /tmp/

注意: 共享名稱不一定要包含「guest」,它可以是任何合規 Samba 共享名稱。

請確保 Linux 用戶 guest 擁有訪問 guest_share.path 中文件的相應權限。

另外,請確保共享已正確按照 smb.conf.default 中的 Share Definitions 一節進行配置。

高級配置[編輯 | 編輯原始碼]

Enable symlink following[編輯 | 編輯原始碼]

警告: Enabling the follow symlinks option can be a security risk.
/etc/samba/smb.conf
...
[global]
   follow symlinks = yes
   wide links = yes
   unix extensions = no

Then, restart smb.service.

注意: When using AppArmor, if the symlink points to a directory outside the user's home or the usershare directory, then you need to modify the AppArmor profile permissions.

為 macOS 客戶端啟用服務端複製[編輯 | 編輯原始碼]

服務端複製使得在服務端複製文件時不需要在伺服器及客戶端間進行數據傳輸。該選項默認啟用,但在 macOS 客戶端下無效。如果你有 macOS 客戶端,需要將下面的配置添加到 smb.conf,然後重啟 smb.service

/etc/samba/smb.conf
...
[global]
   fruit:copyfile = yes

啟用 Usershare[編輯 | 編輯原始碼]

注意: 此為可選功能,如無需要可以跳過。

Usershares 可以讓不具有 root 權限的用戶擁有進行添加、修改和刪除自己的文件夾的操作權限。參見 smb.conf(5) § USERSHARES

  1. 為 usershares 創建目錄:
    # mkdir /var/lib/samba/usershares
  2. 創建一個 用戶組
    # groupadd -r sambashare
  3. 將目錄的所有者修改為 root,組修改為 sambashare
    # chown root:sambashare /var/lib/samba/usershares
  4. 修改 usershares 目錄的權限,使 sambashare 組中的用戶可以創建文件。該命令同時配置了 黏着位,防止用戶刪除其他用戶的 usershares:
    # chmod 1770 /var/lib/samba/usershares

smb.conf 配置文件中設置如下配置:

/etc/samba/smb.conf
[global]
  usershare path = /var/lib/samba/usershares
  usershare max shares = 100
  usershare allow guests = yes
  usershare owner only = yes

將用戶添加到 sambashare 組,將 your_username 替換為你用戶的名稱:

# gpasswd sambashare -a your_username

重啟 smb.servicenmb.service 服務。

註銷並重新登錄。

如果你希望共享主目錄下的路徑,其必須允許 others 組的用戶訪問。

本文或本章節的事實準確性存在爭議。

原因: 不確定該需求是否正確,也不確定指的是哪個路徑:是 smb.conf 的 'usershare path' 選項路徑還是共享目錄的路徑?(在 Talk:Samba#permissions 中討論)


在 GUI 下,你可以使用 ThunarDolphin - 右鍵點擊任何目錄,然後通過網絡共享。

在命令行下,使用下列任一命令,替換掉斜體的 sharenameuser,...:

# net usershare add sharename abspath [comment] [user:{R|D|F}] [guest_ok={y|n}]
# net usershare delete sharename
# net usershare list wildcard-sharename
# net usershare info wildcard-sharename

設置並強制應用權限[編輯 | 編輯原始碼]

權限可同時應用於伺服器和共享:

/etc/samba/smb.conf
[global]
  ;inherit owner = unix only ; Inherit ownership of the parent directory for new files and directories
  ;inherit permissions = yes ; Inherit permissions of the parent directory for new files and directories
  create mask = 0664
  directory mask = 2755
  force create mode = 0644
  force directory mode = 2755
  ...

[media]
  comment = Media share accessible by greg and pcusers
  path = /path/to/media
  valid users = greg @pcusers
  force group = +pcusers
  public = no
  writable = yes
  create mask = 0664
  directory mask = 2775
  force create mode = 0664
  force directory mode = 2775

[public]
  comment = Public share where archie has write access
  path = /path/to/public
  public = yes
  read only = yes
  write list = archie
  printable = no

[guests]
  comment = Allow all users to read/write
  path = /path/to/guests
  public = yes
  only guest = yes
  writable = yes
  printable = no

參見 smb.conf(5) 查看完整的可用權限標誌和設置。

限制協議以增強安全性[編輯 | 編輯原始碼]

警告: 默認情況下,4.11 前的 Samba 版本允許使用過時和不安全的 SMB1 協議連接。使用這些版本時,強烈建議設置 server min protocol = SMB2_02 以保護自己免遭勒索軟件攻擊。在 Samba 4.11 及更新版本,SMB2 已是默認最低協議,因此不再需要此更改。

/etc/samba/smb.conf添加 server min protocolserver max protocol 以強制最低和最高可用協議版本;

/etc/samba/smb.conf
[global]
  server min protocol = SMB2_10
  ; server max protocol = SMB3

參見 smb.conf(5) 中的 server max protocol 部分以獲取所支持協議的概述。

為了和舊版本的客戶端和/或伺服器兼容,你或許需要將 client min protocolserver min protocol 設置到舊一點的版本,但請注意你將更易於遭受攻擊。

提示:當客戶端只應使用最新的 SMB3 協議連接時,使用 server min protocol = SMB3,例如運行 Windows 10 及之後版本的客戶端。

使用 mount.cifs客戶端也許需要指定正確的 vers=*,例如:

# mount -t cifs //SERVER/sharename /mnt/mountpoint -o username=username,password=password,iocharset=utf8,vers=3.1.1

參見 mount.cifs(8) 獲取更多信息.

使用原生 SMB 傳輸加密[編輯 | 編輯原始碼]

原生 SMB 傳輸加密在 SMB 3.0 及更新版本可用。支持該類型加密的客戶端包括 Windows 8 以及更新版本,Windows Server 2012 及更新版本,以及 Samba 4.1 及更新版本的 smbclient。

為了默認使用原生 SMB 傳輸加密,需全局和/或按共享設置 server smb encrypt 參數。可用的值有offenabled(默認值),desiredrequired

/etc/samba/smb.conf
[global]
  server smb encrypt = desired

To configure encryption for on the client side, use the option client smb encrypt.

參見 smb.conf(5) 獲取更多信息,特別是 對 SMB1 的影響對 SMB2 的影響 的段落。

提示:#手動掛載 一個共享時,指定 seal 掛載選項以強制使用加密。

禁用打印機共享[編輯 | 編輯原始碼]

默認情況下 Samba 會共享由 CUPS 設置的打印機。

如果你不想打印機被共享,使用以下設置:

/etc/samba/smb.conf
[global]
  load printers = no
  printing = bsd
  printcap name = /dev/null
  disable spoolss = yes
  show add printer wizard = no

防止 Samba 共享特定後綴的文件[編輯 | 編輯原始碼]

注意: 設置這項參數會影響 Samba 的性能,因為它會被強制要求檢查所有掃描到的文件和目錄是否匹配要求。

Samba 提供了一個選項以屏蔽滿足特定命名模式的文件,比如文件擴展名。該選項可用於防止病毒傳播或阻止用戶用特定的文件浪費空間。更多關於此選項的信息可在 smb.conf(5) 找到。

/etc/samba/smb.conf
...
[myshare]
  comment = Private
  path = /mnt/data
  read only = no
  veto files = /*.exe/*.com/*.dll/*.bat/*.vbs/*.tmp/*.mp3/*.avi/*.mp4/*.wmv/*.wma/

提高吞吐量[編輯 | 編輯原始碼]

警告: 注意,下列操作有可能會造成損壞/連接問題,可能會損壞你的 TCP/IP 棧。

默認設置應滿足多數用戶的用例。雖然正確配置 'socket options' 可以提升性能,但錯誤配置也會同比例降低性能。在進行大幅更改前請確保進行了測試。

在應用下列任何配置前請閱讀 smb.conf(5) 文檔。

下列設置需要附加/etc/samba/smb.conf[global] 一節中。

設置 deadtime 可防止大量非活躍連接消耗系統資源:

deadtime = 30

sendfile 可能會更高效利用 CPU 資源,讓 Samba 變得更快:

use sendfile = yes

配置最低 receivefile 大小可以利用零複製直接從網絡套接字緩衝區寫入到作業系統緩存(如果可用)。這一操作可能會提高性能,但建議用戶進行測試:

min receivefile size = 16384

提高接收/發送緩存大小及配置套接字優化標誌可能有助於提升吞吐量。由於在某些網絡下可能會出現問題,建議對各個標誌進行單獨測試:

socket options = IPTOS_LOWDELAY TCP_NODELAY IPTOS_THROUGHPUT SO_RCVBUF=131072 SO_SNDBUF=131072
注意: 部分選項可能需要調整網絡接口,詳見 Sysctl#網絡

Enable access for old clients/devices[編輯 | 編輯原始碼]

Latest versions of Samba no longer offer older authentication methods and protocols which are still used by some older clients (IP cameras, etc). These devices usually require Samba server to allow NTMLv1 authentication and NT1 version of the protocol, known as CIFS. For these devices to work with latest Samba, you need to add these two configuration parameters into [global] section:

server min protocol = NT1
ntlm auth = yes

Anonymous/guest access to a share requires just the first parameter. If the old device will access with username and password, you also need the add the second line too.

Enable Spotlight searching[編輯 | 編輯原始碼]

Spotlight allows supporting clients (e.g. MacOS Finder) to quickly search shared files.

Install and start/enable OpenSearch. Install fs2es-indexerAUR, configure the directories you want to index in /etc/fs2es-indexer/config.yml, and start/enable fs2es-indexer.service for periodic indexing.

Edit smb.conf as described in the Samba wiki to enable Spotlight per share, and restart smb.service to apply the changes.

客戶端配置[編輯 | 編輯原始碼]

要使用類似 ftp 的命令行界面,請安裝軟件包 smbclient。常用命令請參考 smbclient(1)

如需更輕量級的替代品(沒有可用共享查詢等功能),可安裝 cifs-utils,其提供了 /usr/bin/mount.cifs

部分桌面環境可能提供了圖形界面,搭配文件管理器的用法請參考#文件管理器配置

注意:

顯示可用共享[編輯 | 編輯原始碼]

下面命令會顯示伺服器上的可用共享:

$ smbclient -L hostname -U%

smbtree 可用顯示共享目錄樹,不建議再有大量計算機的網絡上使用此功能。可用它檢查共享名是否可用。

另外,使用 $ smbtree -N 會以樹狀圖顯示所有可用共享,它使用了廣播查詢,因此不建議在有大量設備的網絡中使用,但有助於檢查共享名是否可用。使用 -N-no-pass)選項可以忽略密碼輸入請求。

注意: smbtree 使用了 SMB1 和 NetBIOS,意味着它們必須已在伺服器上啟用,且需要在客戶端的 smb.conf 文件中設置 client min protocol = NT1,否則 smbtree 只會顯示空輸出。

NetBIOS/WINS 主機名[編輯 | 編輯原始碼]

Samba clients handle NetBIOS host names automatically by default (the behavior is controlled by the name resolve order option in smb.conf). Other programs (including mount.cifs) typically use Name Service Switch, which does not handle NetBIOS by default.

The smbclient package provides a libnss driver to resolve NetBIOS host names. To use it, install it along with the samba package (which provides the winbindd daemon), start/enable winbind.service and add wins to the hosts line in nsswitch.conf(5):

/etc/nsswitch.conf
...
hosts: mymachines resolve [!UNAVAIL=return] files myhostname dns wins
...
注意: Due to a current mistake in winbind.service, you may have to modify the unit file as described in this bug-report

Now, during host resolving (e.g. when using mount.cifs or just ping netbios-name), winbindd will resolve the host name by sending queries using NetBIOS Name Service (NBNS, also known as WINS) protocol.

By default it sends a broadcast query to your local network. If you have a WINS server, you can add wins server = wins-server-ip to smb.conf and restart winbind.service, then winbindd and other Samba clients will send unicast queries to the specified IP.

If you want to resolve your local host name (specified in the netbios name option in smb.conf), start/enable nmb.service, which will handle incoming queries.

You can test WINS resolution with nmblookup. By default it sends broadcast queries to your local network regardless of the wins server option.

Note that WINS resolution requires incoming traffic originating from port 137.

Disable NetBIOS/WINS support[編輯 | 編輯原始碼]

When not using NetBIOS/WINS host name resolution, it may be preferred to disable this protocol:

/etc/samba/smb.conf
[global]
  disable netbios = yes
  dns proxy = no

Finally disable/stop winbind.service.

手動掛載[編輯 | 編輯原始碼]

使用 mount.cifs 作為掛載類型 type,下面列出的選項並不是全部都需要:

# mount --mkdir -t cifs //SERVER/sharename /mnt/mountpoint -o username=username,password=password,workgroup=workgroup,iocharset=utf8,uid=username,gid=group

其中 uidgid 對應了被授予特定路徑讀寫權限的本地(例如客戶端)用戶/用戶組

注意:
  • If the uid and gid being used does not match the user of the server, the forceuid and forcegid options may be helpful. However note permissions assigned to a file when forceuid or forcegid are in effect may not reflect the real (server) permissions. See the File And Directory Ownership And Permissions section in mount.cifs(8) § FILE AND DIRECTORY OWNERSHIP AND PERMISSIONS for more information.
  • To mount a Windows share without authentication, use "username=*".

本文或本章節的事實準確性存在爭議。

原因: Regardless of recommendation, there's no substantial evidence for the claimed I/O error risk. The warning was added without comment or reference in 2013 and challenged without defense in 2018. It's unclear whether it's true at all.(在 Talk:Samba#Unfounded warning regarding I/O errors and manual mounting? 中討論)


注意: 請注意這裏有 s,其它文件系統一般用的是 user

使用 uidgid 掛載選項時,請注意 文件權限,否则会出现 I/O 错误。}}

注意: 使用 uid 和/或 gid 作為掛載選項可能會導致 I/O 錯誤,建議轉而設置並檢查 文件權限與屬性
  • SERVER — 伺服器名稱
  • sharename — 共享目錄
  • mountpoint — 本地掛載點
  • [-o options] — 詳情請參考 {{man|8|mount.cifs}。
注意:

保存共享密碼[編輯 | 編輯原始碼]

不建議將密碼保存在所有人都可讀的文件中,一個更安全的方式是創建憑證文件,例如寫入到 /etc/samba/credentials

/etc/samba/credentials/share
username=myuser
password=mypass

將掛載命令中的 username=myuser,password=mypass 替換為 credentials=/etc/samba/credentials/share

應僅根用戶允許有憑證文件的讀寫權限:

# chown root:root /etc/samba/credentials
# chmod 700 /etc/samba/credentials
# chmod 600 /etc/samba/credentials/share

自動掛載[編輯 | 編輯原始碼]

注意: You may need to enable systemd-networkd-wait-online.service or NetworkManager-wait-online.service (depending on your setup) to proper enable booting on start-up.

Using NetworkManager and GIO/gvfs[編輯 | 編輯原始碼]

NetworkManager can be configured to run a script on network status change. This script uses the gio command so that it mounts the Samba shares automatically, the same way your file manager does, as explained below. The script also safely unmounts the Samba shares before the relevant network connection is disabled by listening for the pre-down and vpn-pre-down events. Make the script is executable after creating it.

/etc/NetworkManager/dispatcher.d/30-samba.sh
#!/bin/sh

# Find the connection UUID with "nmcli con show" in terminal.
# All NetworkManager connection types are supported: wireless, VPN, wired...
WANTED_CON_UUID="CHANGE-ME-NOW-9c7eff15-010a-4b1c-a786-9b4efa218ba9"

# The user the share will be mounted under
USER="yourusername"
# The path that appears in your file manager when you manually mount the share you want
SMB_URL="smb://servername/share"

# Get runtime user directory. If it does not exist, do nothing and just exit
XDG_RUNTIME_DIR=$(loginctl show-user --property=RuntimePath --value "$USER") || exit 0

if [ "$CONNECTION_UUID" = "$WANTED_CON_UUID" ]; then
    
    # Script parameter $1: network interface name, not used
    # Script parameter $2: dispatched event
    
    case "$2" in
        "up"|"vpn-up")
            su $USER -c "DBUS_SESSION_BUS_ADDRESS=unix:path=$XDG_RUNTIME_DIR/bus gio mount $SMB_URL"
            ;;
        "pre-down"|"vpn-pre-down")
            su $USER -c "DBUS_SESSION_BUS_ADDRESS=unix:path=$XDG_RUNTIME_DIR/bus gio mount -uf $SMB_URL"
            ;;
    esac
fi

Create a symlink inside /etc/NetworkManager/dispatcher.d/pre-down to catch the pre-down events:

# ln -s /etc/NetworkManager/dispatcher.d/30-samba.sh /etc/NetworkManager/dispatcher.d/pre-down.d/30-samba.sh
注意: Since this script uses the user bus, it will only work if the user has active sessions. This means that the share will not mount automatically after boot if the connection is established before you are logged in.

作為掛載路徑[編輯 | 編輯原始碼]

This is a simple example of a cifs mount entry that requires authentication:

/etc/fstab
//SERVER/sharename /mnt/mountpoint cifs _netdev,nofail,username=myuser,password=mypass 0 0
注意:
  • See examples below on better security for authentication credentials
  • Spaces in sharename should be replaced by \040 (ASCII code for space in octal). For example, //SERVER/share name on the command line should be //SERVER/share\040name in /etc/fstab.
  • To allow users to mount it as long as the mount point resides in a directory controllable by the user; i.e. the user's home, append the users mount option. The option is users (plural). For other filesystem types handled by mount, this option is usually user; sans the "s".
提示:Use x-systemd.automount if you want them to be mounted only upon access. See Fstab#Remote file system for details.

作為 systemd 單元[編輯 | 編輯原始碼]

/etc/systemd/system 下創建一個新的 .mount 文件,例如:mnt-myshare.mount。詳細信息請查看 systemd.mount(5)

注意: 請確保文件名與你要使用的掛載點對應。 例如 mnt-myshare.mount 只能用於掛載位於 /mnt/myshare 下的共享,否則可能會出現像這樣的報錯:systemd[1]: mnt-myshare.mount: Where= setting does not match unit name. Refusing

What= 要使用的共享路徑

Where= 將共享掛載到的位置

Options= 共享掛載選項

注意:
  • 網絡掛載單元會自動獲取 remote-fs-pre.targetnetwork.targetnetwork-online.targetAfter 部分的依賴,並在沒有設置 nofail 掛載選項的情況下會獲得對 remote-fs.targetBefore 依賴。對於後者,還會添加一個 Wants 單元。
  • noauto 添加Options 可以防止在啟動階段自動掛載(除非被其它單元拉起)。
  • 如果你想用主機名而不是 IP 來連接共享伺服器,需要在 After 中加入 nss-lookup.target。這可以避免在測試時正常,但啟動時掛載報錯的情況出現。
/etc/systemd/system/mnt-myshare.mount
[Unit]
Description=Mount Share at boot

[Mount]
What=//server/share
Where=/mnt/myshare
Options=_netdev,credentials=/etc/samba/credentials/myshare,iocharset=utf8,rw
Type=cifs
TimeoutSec=30

[Install]
WantedBy=multi-user.target
提示:
  • 遇到無法連通的主機時,將 ForceUnmount=true 添加[Mount] 以允許強制卸載共享。
  • 如果你的共享使用了只讀權限的組,可以添加 uid=username 或者 gid=groupOptions= 來指定擁有寫入權限的用戶/用戶組。

要使用 mnt-myshare.mount,需啟動該單元,然後通過啟用使其在系統啟動時運行。

自動化掛載[編輯 | 編輯原始碼]

可以使用如下單元來在訪問時自動掛載共享(類似 autofs):

/etc/systemd/system/mnt-myshare.automount
[Unit]
Description=Automount myshare

[Automount]
Where=/mnt/myshare

[Install]
WantedBy=multi-user.target

禁用/停止 mnt-myshare.mount,然後啟用/啟動 mnt-myshare.automount 來在訪問掛載路徑時自動掛載共享。

提示:添加 TimeoutIdleSec 以啟用自動掛載。詳細信息可參考 systemd.automount(5)

smbnetfs[編輯 | 編輯原始碼]

注意: smbnetfs needs an intact Samba server setup. See above on how to do that.

First, check if you can see all the shares you are interested in mounting:

$ smbtree -U remote_user

If that does not work, find and modify the following line in /etc/samba/smb.conf accordingly:

domain master = auto

Now restart smb.service and nmb.service.

If everything works as expected, install smbnetfs.

Then, add the following line to /etc/fuse.conf:

user_allow_other

Now copy the directory /etc/smbnetfs/.smb to your home directory:

$ cp -a /etc/smbnetfs/.smb ~

Then create a link to smb.conf:

$ ln -sf /etc/samba/smb.conf ~/.smb/smb.conf

If a username and a password are required to access some of the shared folders, edit ~/.smb/smbnetfs.auth to include one or more entries like this:

~/.smb/smbnetfs.auth
auth			"hostname" "username" "password"

It is also possible to add entries for specific hosts to be mounted by smbnetfs, if necessary. More details can be found in ~/.smb/smbnetfs.conf.

If you are using the Dolphin or GNOME Files, you may want to add the following to ~/.smb/smbnetfs.conf to avoid "Disk full" errors as smbnetfs by default will report 0 bytes of free space:

~/.smb/smbnetfs.conf
free_space_size 1073741824

When you are done with the configuration, you need to run

$ chmod 600 ~/.smb/smbnetfs.*

Otherwise, smbnetfs complains about 'insecure config file permissions'.

Finally, to mount your Samba network neighbourhood to a directory of your choice, call

$ smbnetfs mount_point
Daemon[編輯 | 編輯原始碼]

The Arch Linux package also maintains an additional system-wide operation mode for smbnetfs. To enable it, you need to make the said modifications in the directory /etc/smbnetfs/.smb.

Then, you can start and/or enable the smbnetfs daemon as usual. The system-wide mount point is at /mnt/smbnet/.

autofs[編輯 | 編輯原始碼]

See Autofs for information on the kernel-based automounter for Linux.

文件管理器配置[編輯 | 編輯原始碼]

GNOME Files、Nemo、Caja、Thunar 和 PCManFM[編輯 | 編輯原始碼]

為了通過 GNOME Files,Nemo,Caja,Thunar 或 PCManFM 訪問 samba 共享,需安裝 gvfs-smb 軟件包。

Ctrl+l 然後在地址欄輸入 smb://servername/share 以訪問您的共享。

共享很可能掛載到了文件系統中的 /run/user/your_UID/gvfs~/.gvfs 位置下。

KDE[編輯 | 編輯原始碼]

KDE 有內建的瀏覽 Samba 共享的能力。為了使用 KDE 系統設置的 GUI,你需要安裝 kdenetwork-filesharing 軟件包。

KDE 應用(例如 Dolphin)自帶 Samba 共享瀏覽功能。在地址欄輸入 smb://servername/share就可以瀏覽文件。如果你想在非 KDE 應用訪問文件,可以安裝 kio-fuse

To use a GUI in the KDE System Settings, you will need to install the kdenetwork-filesharing package.

其它圖形環境[編輯 | 編輯原始碼]

There are a number of useful programs, but they may need to have packages created for them. This can be done with the Arch package build system. The good thing about these others is that they do not require a particular environment to be installed to support them, and so they bring along less baggage.

  • pyneighborhoodAUR
  • LinNeighborhood, RUmba, xffm-samba plugin for Xffm are not available in the official repositories or the AUR. As they are not officially (or even unofficially supported), they may be obsolete and may not work at all.

提示與技巧[編輯 | 編輯原始碼]

Discovering network shares[編輯 | 編輯原始碼]

If nothing is known about other systems on the local network, and automated tools such as smbnetfs are not available, you can manually probe for Samba shares.

First, install the nmap and smbclient packages.

Use nmap to scan your local network to find systems with TCP port 445 open, which is the port used by the SMB protocol. Note that you may need to use -Pn or set a custom ping scan type (e.g. -PS445) because Windows systems are usually firewalled.

$ nmap -p 445 "192.168.1.*"
Starting Nmap 7.92 ( https://nmap.org ) at 2022-03-13 12:00 UTC
Nmap scan report for 192.168.1.1
Host is up (0.0011s latency).

PORT    STATE  SERVICE
445/tcp open  microsoft-ds

Nmap scan report for 192.168.1.2
Host is up (0.00011s latency).

PORT    STATE SERVICE
445/tcp open  microsoft-ds

Nmap done: 256 IP addresses (2 hosts up) scanned in 2.45 seconds

The first result is another system; the second happens to be the client from where this scan was performed.

Now you can connect to their IP addresses directly, but if you want to use NetBIOS host names, you can use nmblookup(1) to check for NetBIOS names. Note that this will not work if NetBIOS is disabled on the server.

$ nmblookup -A 192.168.1.1
Looking up status of 192.168.1.1
        PUTER           <00> -         B <ACTIVE>
        HOMENET         <00> - <GROUP> B <ACTIVE>
        PUTER           <03> -         B <ACTIVE>
        PUTER           <20> -         B <ACTIVE>
        HOMENET         <1e> - <GROUP> B <ACTIVE>
        USERNAME        <03> -         B <ACTIVE>
        HOMENET         <1d> -         B <ACTIVE>
        MSBROWSE        <01> - <GROUP> B <ACTIVE>

Regardless of the output, look for <20>, which shows the host with open services.

Use smbclient(1) to list which services are shared on these systems. You can use NetBIOS host name (PUTER in this example) instead of IP when available. If prompted for a password, pressing enter should still display the list:

$ smbclient -L \\192.168.1.1
Sharename       Type      Comment
---------       ----      -------
MY_MUSIC        Disk
SHAREDDOCS      Disk
PRINTER$        Disk
PRINTER         Printer
IPC$            IPC       Remote Inter Process Communication

Server               Comment
---------            -------
PUTER

Workgroup            Master
---------            -------
HOMENET               PUTER

Remote control of Windows computer[編輯 | 編輯原始碼]

Samba offers a set of tools for communication with Windows. These can be handy if access to a Windows computer through remote desktop is not an option, as shown by some examples.

Send shutdown command with a comment:

$ net rpc shutdown -C "comment" -I IPADDRESS -U USERNAME%PASSWORD

A forced shutdown instead can be invoked by changing -C with comment to a single -f. For a restart, only add -r, followed by a -C or -f.

Stop and start services:

$ net rpc service stop SERVICENAME -I IPADDRESS -U USERNAME%PASSWORD

To see all possible net rpc command:

$ net rpc

疑難解答[編輯 | 編輯原始碼]

啟動 Samba SMB/CIFS 伺服器失敗[編輯 | 編輯原始碼]

可能的解決方法:

  • 通過 testparm(1) 檢查 smb.conf 中的配置問題。
  • /var/cache/samba/ 中配置正確的權限,然後重啟 smb.service
# chmod 0755 /var/cache/samba/msg

SELinux 權限問題[編輯 | 編輯原始碼]

SELinux 默認不允許 samba 訪問用戶的主目錄。要解決此問題,執行:

# setsebool -P samba_enable_home_dirs 1

類似地,samba_export_all_rosamba_export_all_rw 使 Samba 擁有讀取或「讀和寫」所有文件的能力。

AppArmor 權限問題[編輯 | 編輯原始碼]

如果使用了一個在家目錄或用戶共享目錄之外的共享路徑,請在 /etc/apparmor.d/local/usr.sbin.smbd 中將其加入白名單。例如:

/etc/apparmor.d/local/usr.sbin.smbd
"/data/" rk,
"/data/**" lrwk,

No dialect specified on mount[編輯 | 編輯原始碼]

The client is using an unsupported SMB/CIFS version that is required by the server.

See #Restrict protocols for better security for more information.

Unable to overwrite files, permissions errors[編輯 | 編輯原始碼]

本文或本章節的事實準確性存在爭議。

原因: An user should set/check for server/client permissions, instead of using incorrect/possible insecure flags.(在 Talk:Samba 中討論)


Possible solutions:

  • Append the mount option nodfs to the /etc/fstab entry.
  • Add msdfs root = no to the [global] section of the server's /etc/samba/smb.conf.

Windows clients keep asking for password even if Samba shares are created with guest permissions[編輯 | 編輯原始碼]

Set map to guest inside the global section of /etc/samba/smb.conf:

map to guest = Bad Password

If you are still using Samba < 4.10.10, use Bad User instead of Bad Password.

Windows 10 1709 和更高版本的連接性問題 - "Windows cannot access" 0x80004005[編輯 | 編輯原始碼]

This error affects some machines running Windows 10 version 1709 and later. It is not related to SMB1 being disabled in this version but to the fact that Microsoft disabled insecure logons for guests on this version for some, but not others.

To fix, open Group Policy Editor (gpedit.msc). Navigate to Computer configuration\administrative templates\network\Lanman Workstation > Enable insecure guest logons and enable it. Alternatively,change the following value in the registry:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters]
"AllowInsecureGuestAuth"=dword:1

Error: Failed to retrieve printer list: NT_STATUS_UNSUCCESSFUL[編輯 | 編輯原始碼]

If you are a home user and using samba purely for file sharing from a server or NAS, you are probably not interested in sharing printers through it. If so, you can prevent this error from occurring by adding the following lines to your /etc/samba/smb.conf:

/etc/samba/smb.conf
[global]
  load printers = No
  printing = bsd
  printcap name = /dev/null
  disable spoolss = Yes

Restart the samba service, smb.service, and then check your logs:

# cat /var/log/samba/smbd.log

and the error should now no longer be appearing.

Sharing a folder fails[編輯 | 編輯原始碼]

It means that while you are sharing a folder from Dolphin (file manager) and everything seems ok at first, after restarting Dolphin the share icon is gone from the shared folder, and also some output like this in terminal (Konsole) output:

‘net usershare’ returned error 255: net usershare: usershares are currently disabled

To fix it, enable usershare as described in #啟用 Usershares.

"Browsing" network fails with "Failed to retrieve share list from server"[編輯 | 編輯原始碼]

And you are using a firewall (iptables) because you do not trust your local (school, university, hotel) network. This may be due to the following: When the smbclient is browsing the local network it sends out a broadcast request on udp port 137. The servers on the network then reply to your client but as the source address of this reply is different from the destination address iptables saw when sending the request for the listing out, iptables will not recognize the reply as being "ESTABLISHED" or "RELATED", and hence the packet is dropped. A possible solution is to add:

iptables -t raw -A OUTPUT -p udp -m udp --dport 137 -j CT --helper netbios-ns

to your iptables setup.

For Uncomplicated Firewall, you need to add nf_conntrack_netbios_ns to the end of the following line in /etc/default/ufw

IPT_MODULES="nf_conntrack_ftp nf_nat_ftp nf_conntrack_irc nf_nat_irc"

and then run the following commands as root:

echo 1 > /proc/sys/net/netfilter/nf_conntrack_helper
ufw allow CIFS
ufw reload

To make this change persistent across reboots, add the following line at the end of /etc/ufw/sysctl.conf:

net.netfilter.nf_conntrack_helper=1

Protocol negotiation failed: NT_STATUS_INVALID_NETWORK_RESPONSE[編輯 | 編輯原始碼]

The client probably does not have access to shares. Make sure clients' IP address is in hosts allow = line in /etc/samba/smb.conf.

Another problem could be, that the client uses an invalid protocol version. To check this try to connect with the smbclient where you specify the maximum protocol version manually:

$ smbclient -U <user name> -L //<server name> -m <protocol version: e. g. SMB2> -W <domain name>

If the command was successful then create a configuration file:

~/.smb/smb.conf
[global]
  workgroup = <domain name>
  client max protocol = SMB2

Connection to SERVER failed: (Error NT_STATUS_UNSUCCESSFUL)[編輯 | 編輯原始碼]

You are probably passing a wrong server name to smbclient. To find out the server name, run hostnamectl on the server and look at "Transient hostname" line

Connection to SERVER failed: (Error NT_STATUS_CONNECTION_REFUSED)[編輯 | 編輯原始碼]

Make sure that the server has started. The shared directories should exist and be accessible.

Protocol negotiation failed: NT_STATUS_CONNECTION_RESET[編輯 | 編輯原始碼]

Probably the server is configured not to accept protocol SMB1. Add option client max protocol = SMB2 in /etc/samba/smb.conf. Or just pass argument -m SMB2 to smbclient.

Password Error when correct credentials are given (error 1326)[編輯 | 編輯原始碼]

Samba 4.5 has NTLMv1 authentication disabled by default. It is recommend to install the latest available upgrades on clients and deny access for unsupported clients.

If you still need support for very old clients without NTLMv2 support (e.g. Windows XP), it is possible force enable NTLMv1, although this is not recommend for security reasons:

/etc/samba/smb.conf
[global]
  lanman auth = yes
  ntlm auth = yes

If NTLMv2 clients are unable to authenticate when NTLMv1 has been enabled, create the following file on the client:

/home/user/.smb/smb.conf
[global]
  sec = ntlmv2
  client ntlmv2 auth = yes

This change also affects samba shares mounted with mount.cifs. If after upgrade to Samba 4.5 your mount fails, add the sec=ntlmssp option to your mount command, e.g.

mount.cifs //server/share /mnt/point -o sec=ntlmssp,...

See the mount.cifs(8) man page: ntlmssp - Use NTLMv2 password hashing encapsulated in Raw NTLMSSP message. The default in mainline kernel versions prior to v3.8 was sec=ntlm. In v3.8, the default was changed to sec=ntlmssp.

Mapping reserved Windows characters[編輯 | 編輯原始碼]

Starting with kernel 3.18, the cifs module uses the "mapposix" option by default. When mounting a share using unix extensions and a default Samba configuration, files and directories containing one of the seven reserved Windows characters : \ * < > ? are listed but cannot be accessed.

Possible solutions are:

  • Use the undocumented nomapposix mount option for cifs
# mount.cifs //server/share /mnt/point -o nomapposix
  • Configure Samba to remap mapposix ("SFM", Services for Mac) style characters to the correct native ones using fruit
/etc/samba/smb.conf
[global]
  vfs objects = catia fruit
  fruit:encoding = native
  • Manually remap forbidden characters using catia
/etc/samba/smb.conf
[global]
  vfs objects = catia
  catia:mappings = 0x22:0xf022, 0x2a:0xf02a, 0x2f:0xf02f, 0x3a:0xf03a, 0x3c:0xf03c, 0x3e:0xf03e, 0x3f:0xf03f, 0x5c:0xf05c, 0x7c:0xf07c, 0x20:0xf020

The latter approach (using catia or fruit) has the drawback of filtering files with unprintable characters.

Folder shared inside graphical environment is not available to guests[編輯 | 編輯原始碼]

This section presupposes:

  1. Usershares are configured following previous section
  2. A shared folder has been created as a non-root user from GUI
  3. Guests access has been set to shared folder during creation
  4. Samba service has been restarted at least once since last /etc/samba/smb.conf file modification

For clarification purpose only, in the following sub-sections is assumed:

  • Shared folder is located inside user home directory path (/home/yourUser/Shared)
  • Shared folder name is MySharedFiles
  • Guest access is read-only.
  • Windows users will access shared folder content without login prompt

Verify correct samba configuration[編輯 | 編輯原始碼]

Run the following command from a terminal to test configuration file correctness:

$ testparm

Verify correct shared folder creation[編輯 | 編輯原始碼]

Run the following commands from a terminal:

$ cd /var/lib/samba/usershares
$ ls

If everything is fine, you will notice a file named mysharedfiles

Read the file contents using the following command:

$ cat mysharedfiles

The terminal output should display something like this:

/var/lib/samba/usershares/mysharedfiles
path=/home/yourUser/Shared
comment=
usershare_acl=S-1-1-0:r
guest_ok=y
sharename=MySharedFiles

Verify folder access by guest[編輯 | 編輯原始碼]

Run the following command from a terminal. If prompted for a password, just press Enter:

$ smbclient -L localhost

If everything is fine, MySharedFiles should be displayed under Sharename column

Run the following command in order to access the shared folder as guest (anonymous login)

$ smbclient -N //localhost/MySharedFiles

If everything is fine samba client prompt will be displayed:

smb: \>

From samba prompt verify guest can list directory contents:

smb: \> ls

If the NTFS_STATUS_ACCESS_DENIED error is displayed, the issue is likely to be with Unix directory permissions. Ensure that your samba user has access to the folder and all parent folders. You can test this by sudoing to the user and attempting to list the mount directory, and all of its parents.

Mount error: Host is down[編輯 | 編輯原始碼]

This error might be seen when mounting shares of Synology NAS servers. Use the mount option vers=1.0 to solve it.

Template:主要

Software caused connection abort[編輯 | 編輯原始碼]

File managers that utilizes gvfs-smb can show the error Software caused connection abort when writing a file to a share/server. This may be due to the server running SMB/CIFS version 1, which many routers use for USB drive sharing (e.g. Belkin routers). To write to these shares specify the CIFS version with the option vers=1.0. E.g.:

/etc/fstab
//SERVER/sharename /mnt/mountpoint cifs _netdev,guest,file_mode=0777,dir_mode=0777,vers=1.0 0 0

This can also happen after updating Samba to version 4.11, which deactivates SMB1 as default, and accessing any Samba share. You can reenable it by adding

/etc/samba/smb.conf
[global]
client min protocol = CORE

Connection problem (due to authentification error)[編輯 | 編輯原始碼]

Be sure that you do not leave any space characters before your username in Samba client configuration file as follows:

~/.samba
username= user
password=pass

The correct format is:

~/.samba
username=user
password=pass

Windows 1709 及更高版本無法在「網絡」視圖中發現 Samba 伺服器[編輯 | 編輯原始碼]

隨着 Windows 10 1511 版本的推出,對 SMBv1 的支持以及由此的 NetBIOS 設備發現被默認禁用。根據實際版本不同,從1709版本("秋季創意者更新")開始的 Windows 版本不允許再安裝 SMBv1 客戶端。這導致運行 Samba 的主機無法在資源管理器的「網絡(網上鄰居)」視圖中被列出。雖然並無連接問題,而且 Samba 仍然可以正常運行,但用戶可能想讓他們的 Samba 主機被 Windows 自動列出。wsddAUR 實現了一個 Web Service Discovery 宿主守護進程。這使得(Samba)主機,比方說你的本地 NAS 設備,能夠被像 Windows 這樣的 Web Service Discovery 客戶端找到。默認設置應該適用於大多數用例,你要做的就是啟用 wsdd.service

默認配置(在組 "WORKGROUP "中使用機器主機名公示自己)應適用於絕大多數情況。如果有需要,你可以通過在 /etc/conf.d/wsdd 中添加額外的參數來改變配置選項(詳見wsdd的手冊頁)。

wsdd2AUR 的功能相同,但它是用 C 語言而不是 Python 編寫的。默認情況下,它將在 smb.conf 中尋找 netbios nameworkgroup 值。

GNOME Files not showing Windows machines (version 1709 or up) with shared folders in Network view[編輯 | 編輯原始碼]

See GNOME/Files#Windows machines (version 1709 or up) with shared folders don't show up in Network view.

iOS/iPadOS Files can no longer copy-to Samba share on Arch Linux beginning with iOS/iPadOS 14.5[編輯 | 編輯原始碼]

Beginning with iOS/iPadOS 14.5 attempting to transfer from a device running iOS/iPadOS using the "Files" app to a samba share on Arch Linux will result in the error:

The operation couldn't be completed
Operation canceled

To correct this problem, add add the following to the global section of your smb.conf and restart smb.service. Comment optional:

## addition for iOS/iPadOS 14.5+ Files transfer-to server
vfs object = fruit streams_xattr

See https://apple.stackexchange.com/q/424681 Apple.Stackexchange.com - "The operation couldn't be completed"/"Operation canceled" error message when saving to a Samba share via Files app.

Slow initial connections from certain clients without other performance problems[編輯 | 編輯原始碼]

Some SMB clients, such as Solid Explorer for Android, take significantly longer to connect to Samba if they fail to resolve the NetBIOS name. Enabling nmb.service will greatly speed up initial connections if this is the case. Since this is a bug in the client software, please report such cases to the authors of conflicting software.

更多參考[編輯 | 編輯原始碼]