目錄
Chapter 12. Moving Files Across the Network
This chapter surveys options for moving and sharing files between machines on a network. We’ll start by looking at some ways to copy files other than the scp and sftp utilities that you’ve already seen. Then we’ll briefly look at true file sharing, where you attach a directory on one machine to another machine.
這一章節將對網絡中機器之間移動和共享文件的選項進行概述。
我們首先會看一些除了你已經瞭解的scp和sftp工具之外的複製文件的方法。
然後,我們將簡要介紹真正的文件共享,即將一個機器上的目錄附加到另一個機器上。
This chapter describes some alternative ways to transfer files because not every file transfer problem is the same. Sometimes you need to provide quick, temporary access to machines that you don’t know much about, sometimes you need to efficiently maintain copies of large directory structures, and sometimes you need more constant access.
本章將描述一些替代的文件傳輸方式,因為並非所有的文件傳輸問題都相同。
有時候你需要為你對機器瞭解不多的機器提供快速、臨時的訪問權限,有時候你需要高效地維護大型目錄結構的副本,有時候你需要更持續的訪問權限。
12.1 Quick Copy(快速複製)
Let’s say you want to copy a file (or files) from your machine to another one on your network, and you don’t care about copying it back or need to do anything fancy. You just want to do it quickly. There’s a convenient way to do this with Python. Just go to the directory containing the file(s) and run
假設你想要將文件(或文件)從你的機器複製到網絡上的另一台機器,而且你不關心是否需要將其複製回來或需要進行任何複雜的操作。
你只想快速完成。
使用Python有一種方便的方法來實現這一點。
只需進入包含文件的目錄並運行以下命令:
$ python -m SimpleHTTPServer
This starts a basic web server that makes the directory available to any browser on the network. It usually runs on port 8000, so if the machine you run this on is at 10.1.2.4, go to http://10.1.2.4:8000 on the destination and you’ll be able to grab what you need.
這將啓動一個基本的Web服務器,使目錄對網絡上的任何瀏覽器可用。
它通常運行在8000端口上,所以如果你運行此命令的機器的IP地址是10.1.2.4,在目標機器上打開http://10.1.2.4:8000,你就可以獲取你所需的文件。
12.2 rsync
If you want to move an entire directory structure around, you can do so with scp -r—or if you need a little more performance, tar in a pipeline:
如果你想要移動整個目錄結構,你可以使用scp -r命令,或者如果你需要更高的性能,可以使用tar命令進行管道操作:
$ tar cBvf - directory | ssh remote_host tar xBvpf -
These methods get the job done but are not very flexible. In particular, after the transfer completes, the remote host may not have an exact copy of the directory. If directory already exists on the remote machine and contains some extraneous files, those files persist after the transfer.
這些方法可以完成任務,但並不是非常靈活。
特別是,在傳輸完成後,遠程主機上可能沒有目錄的完全副本。
如果目錄在遠程機器上已經存在幷包含一些多餘的文件,那麼這些文件在傳輸之後仍然存在。
If you need to do this sort of thing regularly (and especially if you plan to automate the process), use a dedicated synchronizer system. On Linux, rsync is the standard synchronizer, offering good performance and many useful ways to perform transfers. We’ll cover some of the essential rsync operation modes and look at some of its peculiarities.
如果你需要經常進行這種操作(尤其是如果你計劃自動化這個過程),請使用專用的同步系統。
在Linux上,rsync是標準的同步器,提供良好的性能和許多有用的傳輸方式。
我們將介紹一些基本的rsync操作模式,並瞭解一些它的特點。
12.2.1 rsync Basics(rsync 基礎知識)
To get rsync working between two hosts, the rsync program must be installed on both the source and destination, and you’ll need a way to access one machine from the other. The easiest way to transfer files is to use a remote shell account, and we’ll assume that you want to transfer files using SSH access. However, remember that rsync can be handy even for copying files and directories between locations on a single machine, such as from one filesystem to another.
On the surface, the rsync command is not much different from scp. In fact, you can run rsync with the same arguments. For example, to copy a group of files to your home directory on host, enter
要在兩台主機之間使用rsync,源主機和目標主機都必須安裝rsync程序,並且您需要一種從一台機器訪問另一台機器的方式。
最簡單的文件傳輸方式是使用遠程shell帳户,我們假設您想使用SSH訪問來傳輸文件。
然而,請記住,即使在單台機器的不同位置之間複製文件和目錄,例如從一個文件系統到另一個文件系統,rsync也可以非常方便。
從表面上看,rsync命令與scp並沒有太大區別。
實際上,您可以使用相同的參數運行rsync。例如,要將一組文件複製到主機上的主目錄中,請輸入
$ rsync file1 file2 ... host:
On any modern system, rsync assumes that you’re using SSH to connect to the remote host. Beware of this error message:
在任何現代系統上,rsync 都會假定你使用 SSH 連接到遠程主機。
請注意此錯誤信息:
rsync not found
rsync: connection unexpectedly closed (0 bytes read so far)
rsync error: error in rsync protocol data stream (code 12) at io.c(165)
This notice says that your remote shell can’t find rsync on its system. If rsync isn’t in the remote path but is on the system, use --rsync-path=path to manually specify its location.
這個通知表示你的遠程 shell 在系統上找不到 rsync。
如果 rsync 不在遠程路徑中但是存在於系統中,可以使用 --rsync-path=path 來手動指定其位置。
If your username is different on the remote host, add user@ to the hostname, where user is your username on host:
如果你在遠程主機上的用户名不同,請在主機名前添加 user@,其中 user 是你在主機上的用户名。
$ rsync file1 file2 ... user@host:
Unless you supply extra options, rsync copies only files. In fact, if you specify just the options described so far and you supply a directory dir as an argument, you’ll see this message:
除非提供額外選項,否則 rsync 只複製文件。
事實上,如果你只指定了上述選項,並將目錄 dir 作為參數,你就會看到這條信息:
skipping directory dir
To transfer entire directory hierarchies—complete with symbolic links, permissions, modes, and devices— use the -a option. Furthermore, if you want to copy to some place other than your home directory on the remote host, place this destination after the remote host, like this:
要傳輸整個目錄層次結構,包括符號鏈接、權限、模式和設備,請使用 -a 選項。
此外,如果要複製到遠程主機上主目錄以外的其他地方,請將此目標放在遠程主機之後,如下所示:
$ rsync -a dir host:destination_dir
Copying directories can be tricky, so if you’re not exactly sure what will happen when you transfer the files, use the -nv option combination. The -n option tells rsync to operate in “dry run” mode—that is, to run a trial without actually copying any files. The -v option is for verbose mode, which shows details about the transfer and the files involved:
複製目錄可能會很棘手,所以如果你對文件傳輸時會發生什麼不確定,可以使用-nv選項組合。
-n選項告訴rsync以“干擾運行”模式操作,即進行試運行而不實際複製任何文件。
-v選項用於詳細模式,顯示有關傳輸和涉及的文件的詳細信息:
$ rsync -nva dir host:destination_dir
The output looks like this:
輸出結果如下
building file list ... done
ml/nftrans/nftrans.html
[more files]
wrote 2183 bytes read 24 bytes 401.27 bytes/sec
12.2.2 Making Exact Copies of a Directory Structure(製作目錄結構的精確副本)
By default, rsync copies files and directories without considering the previous contents of the destination directory. For example, if you transferred the directory d containing the files a and b to a machine that already had a file named d/c, the destination would contain d/a, d/b, and d/c after the rsync.
默認情況下,rsync在複製文件和目錄時不考慮目標目錄中的先前內容。
例如,如果您將包含文件a和b的目錄d傳輸到已經存在名為d/c的文件的計算機上,那麼在rsync之後,目標目錄將包含d/a,d/b和d/c。
To make an exact replica of the source directory, you must delete files in the destination directory that do not exist in the source directory, such as d/c in this example. Use the --delete option to do that:
要創建源目錄的精確副本,您必須刪除目標目錄中源目錄中不存在的文件,例如在此示例中的d/c。使用--delete選項來實現這一點:
$ rsync -a --delete dir host:destination_dir
WARNING This can be dangerous, because you should typically inspect the destination directory to see if there’s anything that you’ll inadvertently delete. Remember, if you’re not certain about your transfer, use the -n option to perform a dry run so that you’ll know exactly when rsync wants to delete a file.
警告 這可能很危險,因為你通常應該檢查一下目標目錄,看看是否有你會無意中刪除的內容。
記住,如果你不確定是否要進行傳輸,可以使用 -n 選項執行一次模擬運行,這樣你就能準確知道 rsync 什麼時候要刪除文件。
12.2.3 Using the Trailing Slash(使用斜線)
Be particularly careful when specifying a directory as the source in an rsync command line. Consider the basic command that we’ve been working with so far:
在 rsync 命令行中指定一個目錄作為源文件時要特別小心。
請看我們目前使用的基本命令:
$ rsync -a dir host:dest_dir
Upon completion, you’ll have a directory dir inside dest_dir on host. Figure 12-1 shows an example of how rsync normally handles a directory with files named a and b. However, adding a slash (/) significantly changes the behavior:
完成後,主機上 dest_dir 內將出現一個目錄 dir。
圖 12-1 顯示了 rsync 通常如何處理包含 a 和 b 文件的目錄的示例:
$ rsync -a dir/ host:dest_dir
Here, rsync copies everything inside dir to dest_dir on host without actually creating dir on the destination host. Therefore, you can think of a transfer of dir/ as an operation similar to cp dir/* dest_dir on the local filesystem.
在這裏,rsync將dir目錄中的所有內容複製到主機上的dest_dir目錄,而不會在目標主機上創建dir目錄。
因此,你可以將dir/的傳輸視為類似於在本地文件系統上運行cp dir/* dest_dir的操作。
For example, say you have a directory dir containing the files a and b (dir/a and dir/b). You run the trailingslash version of the command to transfer them to the dest_dir directory on host
例如,假設你有一個包含文件a和b的目錄dir(dir/a和dir/b)。
你可以運行帶有尾部斜槓版本的命令將它們傳輸到主機上的dest_dir目錄中。
$ rsync -a dir/ host:dest_dir
When the transfer completes, dest_dir contains copies of a and b but not dir. If, however, you had omitted the trailing / on dir, dest_dir would have gotten a copy of dir with a and b inside. Then, as a result of the transfer, you’d have files and directories named dest_dir/dir/a and dest_dir/dir/b on the remote host. Figure 12-2 illustrates how rsync handles the directory structure from Figure 12-1 when using a trailing slash.
當傳輸完成時,dest_dir中包含a和b的副本,但不包含dir。
然而,如果你在dir後面省略了斜槓/,dest_dir將會得到一個包含a和b的dir副本。
然後,作為傳輸的結果,你將在遠程主機上有名為dest_dir/dir/a和dest_dir/dir/b的文件和目錄。
圖12-2展示了在使用尾部斜槓時,rsync如何處理圖12-1中的目錄結構。
When transferring files and directories to a remote host, accidentally adding a / after a path would normally be nothing more than a nuisance; you could go to the remote host, add the dir directory, and put all of the transferred items back in dir. Unfortunately, you must be careful to avoid disaster when combining the trailing / with the --delete option, because you can easily remove unrelated files this way.
當將文件和目錄傳輸到遠程主機時,意外在路徑後添加/通常只是一個麻煩;你可以去遠程主機,添加dir目錄,並將所有傳輸的項目放回dir中。
不幸的是,當將尾部/與--delete選項結合使用時,你必須小心避免災難,因為這樣你很容易刪除不相關的文件。
Figure 12-1. Normal rsync copy
圖 12-1. 正常 rsync 複製
Figure 12-2. Effect of trailing slash in rsync
圖 12-2. rsync 中尾部斜線的影響
NOTE Be wary of your shell’s automatic filename completion feature. GNU readline and many other completion libraries tack trailing slashes onto completed directory names.
注意 要警惕 shell 的文件名自動補全功能。
GNU readline 和許多其他補全庫都會在補全的目錄名上添加斜線。
12.2.4 Excluding Files and Directories(排除文件和目錄)
One very important feature of rsync is its ability to exclude files and directories from a transfer operation. For example, say you’d like to transfer a local directory called src to host, but you want to exclude anything named .git. You can do it like this:
rsync 有一個非常重要的功能,就是可以在傳輸操作中排除文件和目錄。
例如,你想將名為 src 的本地目錄傳輸到主機,但又想將名為 .git 的文件排除在外。
你可以這樣做
$ rsync -a --exclude=.git src host:
Note that this command excludes all files and directories named .git because --exclude takes a pattern, not an absolute filename. To exclude one specific item, specify an absolute path that starts with /, as shown here
請注意,這條命令會排除所有以 .git 命名的文件和目錄,因為 --exclude 使用的是模式,而不是絕對文件名。
要排除某個特定項目,請指定以 / 開頭的絕對路徑,如圖所示:
$ rsync -a --exclude=/src/.git src host:
NOTE The first / in /src/.git in this command is not the root directory of your system but rather the base directory of the transfer.
注意:此命令中/src/.git中的第一個/不是您系統的根目錄,而是傳輸的基本目錄。
Here are a few more tips on how to exclude patterns:
以下是關於如何排除模式的幾個提示:
o You can have as many --exclude parameters as you like.
o If you use the same patterns repeatedly, place them in a plaintext file (one pattern per line) and use --exclude-from=file.
o To exclude directories named item but include files with this name, use a trailing slash: -- exclude=item/.
o The exclude pattern is based on a full file or directory name component and may contain simple globs (wildcards). For example, t*s matches this, but it does not match ethers.
o If you exclude a directory or filename but find that your pattern is too restrictive, use --include to specifically include another file or directory.
- 您可以使用任意多個--exclude參數。
- 如果您重複使用相同的模式,請將它們放在一個純文本文件中(每行一個模式),然後使用--exclude-from=file。
- 若要排除名為item的目錄,但包括具有此名稱的文件,請使用尾部斜槓:--exclude=item/。
- 排除模式基於完整的文件或目錄名組件,可以包含簡單的通配符(通配符)。例如,t*s可以匹配這個,但不能匹配ethers。
-
如果您排除了一個目錄或文件名,但發現您的模式過於嚴格,請使用--include來明確包含另一個文件或目錄。
12.2.5 Transfer Integrity, Safeguards, and Verbose Modes(傳輸完整性、保障措施和簡明模式)
To speed operation, rsync uses a quick check to determine whether any files on the transfer source are already on the destination. The quick check uses a combination of the file size and its last-modified date. The first time you transfer an entire directory hierarchy to a remote host, rsync sees that none of the files already exist at the destination, and it transfers everything. Testing your transfer with rsync -n verifies this for you.
為了加快操作速度,rsync使用快速檢查來確定傳輸源上的任何文件是否已經存在於目標位置。
快速檢查使用文件大小和最後修改日期的組合。
第一次將整個目錄層次結構傳輸到遠程主機時,rsync會發現目標位置沒有任何文件存在,然後會傳輸所有文件。
使用rsync -n命令來測試傳輸過程,可以驗證這一點。
After running rsync once, run it again using rsync -v. This time you should see that no files show up in the transfer list because the file set exists on both ends, with the same modification dates.
在運行一次rsync之後,再次運行rsync -v命令。
這時,你應該會看到傳輸列表中沒有任何文件,因為文件集在兩端都存在,並且修改日期相同。
When the files on the source side are not identical to the files on the destination side, rsync transfers the source files and overwrites any files that exist on the remote side. The default behavior may be inadequate, though, because you may need additional reassurance that files are indeed the same before skipping over them in transfers, or you may want to put in some extra safeguards. Here are some options that come in handy:
當源端的文件與目標端的文件不相同時,rsync會傳輸源文件並覆蓋目標端已存在的文件。
然而,默認行為可能不足以滿足需求,因為在傳輸過程中,你可能需要額外的確認文件是否相同,然後再跳過它們,或者你可能希望增加一些額外的保護措施。
以下是一些有用的選項:
o --checksum (abbreviation: -c) Compute checksums (mostly unique signatures) of the files to see if they’re the same. This consumes additional I/O and CPU resources during transfers, but if you’re dealing with sensitive data or files that often have uniform sizes, this option is a must.
o --ignore-existing Doesn’t clobber files already on the target side.
o --backup (abbreviation: -b) Doesn’t clobber files already on the target but rather renames these existing files by adding a ~ suffix to their names before transferring the new files.
o --suffix=s Changes the suffix used with --backup from ~ to s.
o --update (abbreviation: -u) Doesn’t clobber any file on the target that has a later date than the corresponding file on the source.
- --checksum(縮寫:-c)計算文件的校驗和(大部分是唯一的簽名),以判斷它們是否相同。這會在傳輸過程中消耗額外的I/O和CPU資源,但如果你處理的是敏感數據或者文件大小經常相同的文件,這個選項是必需的。
- --ignore-existing 不覆蓋目標端已經存在的文件。
- --backup(縮寫:-b)不覆蓋目標端已經存在的文件,而是在傳輸新文件之前,將這些現有文件重命名為帶有~後綴的名稱。
- --suffix=s 更改--backup選項使用的後綴,將~更改為s。
- --update(縮寫:-u)不覆蓋目標端上具有比源端對應文件更晚修改日期的任何文件。
With no special options, rsync operates quietly, only producing output when there is a problem. However, you can use rsync -v for verbose mode or rsync -vv for even more details. (You can tack on as many v options as you like, but two is probably more than you need.) For a comprehensive summary after the transfer, use rsync --stats.
在沒有特殊選項的情況下,rsync會靜默運行,只在出現問題時產生輸出。
但是,你可以使用rsync -v來啓用詳細模式,或者使用rsync -vv來獲取更多細節。
(你可以添加儘可能多的-v選項,但是兩個應該已經足夠了。)
要在傳輸完成後獲得全面的摘要信息,請使用rsync --stats命令。
12.2.6 Compression(壓縮)
Many users like the -z option in conjunction with -a to compress the data before transmission:
許多用户喜歡將 -z 選項與 -a 選項結合使用,以便在傳輸前壓縮數據:
$ rsync -az dir host:destination_dir
Compression can improve performance in certain situations, such as when uploading a large amount of data across a slow connection (like the slow upstream link on many DSL connections) or when the latency between the two hosts is high. However, across a fast local area network, the two endpoint machines can be constrained by the CPU time that it takes to compress and decompress data, so uncompressed transfer may be faster.
壓縮可以在某些情況下提高性能,比如在通過慢速連接(如許多DSL連接的上行鏈路)上傳大量數據或兩個主機之間的延遲較高時。
然而,在快速的局域網中,兩個端點機器可能受到壓縮和解壓數據所需的CPU時間的限制,因此未壓縮的傳輸可能更快。
12.2.7 Limiting Bandwidth(限制帶寬)
It’s easy to clog the uplink of Internet connections when uploading a large amount of data to a remote host. Even though you won’t be using your (normally large) downlink capacity during such a transfer, your connection will still seem quite slow if you let rsync go as fast as it can, because outgoing TCP packets such as HTTP requests will have to compete with your transfers for bandwidth on your uplink.
當向遠程主機上傳大量數據時,很容易導致互聯網連接的上行鏈路堵塞。
即使在此類傳輸過程中不會使用您(通常較大的)下行帶寬,如果您允許rsync以最快的速度進行傳輸,您的連接仍然會顯得非常慢,因為像HTTP請求這樣的出站TCP數據包將不得不與您的傳輸競爭上行帶寬。
To get around this, use --bwlimit to give your uplink a little breathing room. For example, to limit the bandwidth to 10,000 Kpbs you might do something like this:
為了解決這個問題,可以使用--bwlimit參數給您的上行鏈路留出一些空間。
例如,要將帶寬限制為10,000 Kbps,您可以像這樣操作:
$ rsync --bwlimit=10000 -a dir host:destination_dir
12.2.8 Transferring Files to Your Computer(將文件傳輸到電腦)
The rsync command isn’t just for copying files from your local machine to a remote host. You can also transfer files from a remote machine to your local host by placing the remote host and remote source path as the first argument on the command line. Therefore, to transfer src_dir on the host to dest_dir on the local host, run this command:
rsync 命令不僅可以將文件從本地機器複製到遠程主機。
你也可以將遠程主機和遠程源路徑作為命令行的第一個參數,將文件從遠程機器傳輸到本地主機。
因此,要將主機上的 src_dir 傳輸到本地主機上的 dest_dir,請運行此命令:
$ rsync -a host:src_dir dest_dir
NOTE As mentioned before, you can use rsync to duplicate directories on your local machines if you omit host: entirely
注意 如前所述,如果完全省略 host:,就可以使用 rsync 複製本地機器上的目錄。
12.2.9 Further rsync Topics(更多 rsync 主題)
Whenever you need to copy numerous files, rsync should be one of the first utilities that comes to mind. Running rsync in batch mode is particularly useful, and you’ll find a number of options to employ auxiliary files related to command options, logging, and transfer state. In particular, the state files make long transfers faster and easier to resume when interrupted.
每當你需要複製大量文件時,rsync應該是你首先想到的工具之一。
以批處理模式運行rsync特別有用,你會發現有許多選項可以使用相關的輔助文件,包括命令選項、日誌和傳輸狀態。
特別是狀態文件可以使長時間傳輸更快且在中斷後更容易恢復。
You’ll also find rsync useful for making backups. For example, you can attach Internet storage, such as Amazon’s S3, to your Linux system and then use rsync --delete to periodically synchronize a filesystem with the network storage to create a very effective backup system.
你還會發現rsync在備份方面非常有用。
例如,你可以將互聯網存儲(如Amazon的S3)連接到你的Linux系統,然後使用rsync --delete定期將文件系統與網絡存儲進行同步,創建一個非常有效的備份系統。
There are many more command-line options than those described here. For a rough overview, run rsync - -help. You’ll find more detailed information in the rsync(1) manual page as well as at the rsync home page: http://rsync.samba.org/.
除了這裏描述的選項,還有許多其他的命令行選項。要獲取大致的概述,請運行rsync --help。
你可以在rsync(1)手冊頁面以及rsync的主頁http://rsync.samba.org/上找到更詳細的信息。
12.3 Introduction to File Sharing(文件共享簡介)
Your Linux machine probably doesn’t live alone on your network, and when you have multiple machines on a network, there’s nearly always a reason to share files between them. For the remainder of this chapter, we’ll primarily be concerned with file sharing between Windows and Mac OS X machines, because it’s interesting to see how Linux adapts to completely foreign environments. For the purpose of sharing files between Linux machines, or for accessing files from a Network Area Storage (NAS) device, we’ll briefly talk about using Network File System (NFS) as a client
你的 Linux 機器很可能不是獨自存在於你的網絡中,當你在一個網絡上有多個機器時,幾乎總會有共享文件的需求。
在本章的剩餘部分,我們主要關注的是 Windows 和 Mac OS X 機器之間的文件共享,因為看到 Linux 如何適應完全陌生的環境是很有趣的。
為了在 Linux 機器之間共享文件,或者訪問網絡存儲區(NAS)設備上的文件,我們將簡要介紹使用網絡文件系統(NFS)作為一種方法。
12.4 Sharing Files with Samba( 使用 Samba 共享文件)
If you have machines running Windows, you’ll probably want to permit access to your Linux system’s files and printers from those Windows machines using the standard Windows network protocol, Server Message Block (SMB). Mac OS X also supports SMB file sharing.
如果您的機器運行的是Windows系統,您可能希望使用標準的Windows網絡協議Server Message Block(SMB)允許Windows機器訪問您的Linux系統的文件和打印機。
Mac OS X也支持SMB文件共享。
The standard file-sharing software suite for Unix is called Samba. Not only does Samba allow your network’s Windows computers to get to your Linux system, but it works the other way around: You can print and access files on Windows servers from your Linux machine with the Samba client software.
Unix系統的標準文件共享軟件套件稱為Samba。
Samba不僅允許您的網絡中的Windows計算機訪問您的Linux系統,還可以實現相反的功能:您可以使用Samba客户端軟件在Linux機器上打印和訪問Windows服務器上的文件。
To set up a Samba server, perform these steps:
要設置Samba服務器,請執行以下步驟:
- Create an smb.conf file.
- Add file-sharing sections to smb.conf.
- Add printer-sharing sections to smb.conf.
- Start the Samba daemons nmbd and smbd.
- 創建一個smb.conf文件。
- 在smb.conf中添加文件共享部分。
- 在smb.conf中添加打印機共享部分。
- 啓動Samba守護進程nmbd和smbd。
When you install Samba from a distribution package, your system should perform the steps listed above using some reasonable defaults for the server. However, it probably won’t be able to determine which particular shares (resources) on your Linux machine you offer to clients.
當您從發行包中安裝Samba時,系統應該會使用一些合理的默認設置執行上述步驟。
然而,它可能無法確定您在Linux機器上提供給客户端的特定共享資源。
NOTE The discussion of Samba in this chapter is brief and limited to getting Windows machines on a single subnet to see a standalone Linux machine through the Windows Network Places browser. There are countless ways to configure Samba, because there are many possibilities for access control and network topology. For the gory details on how to configure a large-scale server, see Using Samba, 3rd edition (O’Reilly, 2007), a much more extensive guide, and visit the Samba website, http://www.samba.org/.
注意:本章中關於Samba的討論簡要,並且僅限於通過Windows網絡瀏覽器將單個子網上的Windows機器看到獨立的Linux機器。
由於訪問控制和網絡拓撲有很多可能性,配置Samba有無數種方式。
要了解如何配置大規模服務器的詳細信息,請參閲
《使用Samba,第3版》(O'Reilly,2007),這是一本更詳盡的指南,並訪問Samba網站http://www.samba.org/。
12.4.1 Configuring the Server(配置服務器)
The central Samba configuration file is smb.conf, which most distributions place in an etc directory such as /etc/samba. However, you may have to hunt around to find this file, as it may also be in a lib directory such as /usr/local/ samba/lib.
中央Samba配置文件是smb.conf,大多數發行版將其放置在/etc/samba等etc目錄中。
然而,您可能需要四處尋找此文件,因為它也可能位於lib目錄(例如/usr/local/samba/lib)中。
The smb.conf file is similar to the XDG style that you’ve seen elsewhere (such as the systemd configuration format) and breaks down into several sections denoted with square brackets (such as [global] and [printers]). The [global] section in smb.conf contains general options that apply to the entire server and all shares. These options primarily pertain to network configuration and access control. The sample [global] section below shows how to set the server name, description, and workgroup:
smb.conf文件類似於您在其他地方看到的XDG樣式(例如systemd配置格式),並分為幾個用方括號表示的部分(例如[global]和[printers])。
smb.conf中的[global]部分包含適用於整個服務器和所有共享的常規選項。這些選項主要涉及網絡配置和訪問控制。
下面是示例的[global]部分,顯示瞭如何設置服務器名稱、描述和工作組:
[global]
# server name
netbios name = name
# server description
server string = My server via Samba
# workgroup
workgroup = MYNETWORK
These parameters work like this:
這些參數是這樣工作的:
o netbios name The server name. If you omit this parameter, Samba uses the Unix hostname.
o server string A short description of the server. The default is the Samba version number.
o workgroup The SMB workgroup name. If you’re on a Windows domain, set this parameter to the name of your domain.
o netbios name 服務器名稱。如果省略此參數,Samba 將使用 Unix 主機名。
o server string 服務器的簡短描述。默認為 Samba 版本號。
o 工作組 SMB 工作組名稱。如果在 Windows 網域中,請將此參數設置為網域名稱。
12.4.2 Server Access Control( 服務器訪問控制)
You can add options to your smb.conf file to limit the machines and users that can access your Samba server. The following list includes many options that you can set in your [global] section and in the sections that control individual shares (as described later in the chapter):
您可以通過在smb.conf文件中添加選項來限制可以訪問Samba服務器的機器和用户。
以下列表包括您可以在[global]部分和控制單個共享的部分(如本章後面所述)中設置的許多選項:
o interfaces Set this to have Samba listen on the given networks or interfaces. For example:
o interfaces = 10.23.2.0/255.255.255.0interfaces = eth0
o bind interfaces only Set this to yes when using the interfaces parameter in order to limit access to machines that you can reach on those interfaces.
o valid users Set this to allow the given users access. For example: valid users = jruser, bill
o guest ok Set this parameter to true to make a share available to anonymous users on the network.
o guest only Set this parameter to true to allow anonymous access only.
o browseable Set this to make shares viewable by network browsers. If you set this parameter to no for any shares, you’ll still be able to access the shares on the Samba server, but you’ll need to know their exact names in order to be able to access them.
o interfaces 將其設置為使Samba偵聽給定的網絡或接口。例如:
o interfaces = 10.23.2.0/255.255.255.0interfaces = eth0
o bind interfaces only 當使用interfaces參數時,將其設置為yes以限制僅能夠在這些接口上訪問的機器。
o valid users 將其設置為允許給定的用户訪問。例如:valid users = jruser, bill
o guest ok 將此參數設置為true,以使共享對網絡上的匿名用户可用。
o guest only 將此參數設置為true,僅允許匿名訪問。
o browseable 將其設置為使共享可由網絡瀏覽器查看。如果對任何共享將此參數設置為no,您仍然可以訪問Samba服務器上的共享,但需要知道它們的確切名稱才能訪問它們。
12.4.3 Passwords(密碼)
In general, you should only allow access to your Samba server with password authentication. Unfortunately, the basic password system on Unix is different than that on Windows, so unless you specify clear-text network passwords or authenticate passwords with a Windows server, you must set up an alternative password system. This section shows you how to set up an alternative password system using Samba’s Trivial Database (TDB) backend, which is appropriate for small networks.
一般來説,您應該只允許通過密碼驗證來訪問您的Samba服務器。
不幸的是,Unix系統上的基本密碼系統與Windows系統上的不同,所以除非您指定明文網絡密碼或使用Windows服務器進行密碼驗證,否則您必須設置一種替代的密碼系統。
本節將向您展示如何使用Samba的Trivial Database(TDB)後端設置替代密碼系統,適用於小型網絡。
First, use these entries in your smb.conf [global] section to define the Samba password database characteristics:
首先,在您的smb.conf [global]部分中使用以下條目來定義Samba密碼數據庫的特性:
# use the tdb for Samba to enable encrypted passwords
security = user
passdb backend = tdbsam
obey pam restrictions = yes
smb passwd file = /etc/samba/passwd_smb
These lines allow you to manipulate the Samba password database with the smbpasswd command. The obey pam restrictions parameter ensures that any user changing their password with the smbpasswd command must obey any rules that PAM enforces for normal password changes. For the passdb backend parameter, you can add an optional pathname for the TDB file after a colon; for example, tdbsam:/etc/samba/private/passwd.tdb.
NOTE If you have access to a Windows domain, you can set security = domain to make Samba use the domain’s usernames and eliminate the need for a password database. However, in order for domain users to access the machine running Samba, each domain user must have a local account with the same username on the machine running Samba.
這些行允許您使用smbpasswd命令操縱Samba密碼數據庫。
obey pam restrictions參數確保使用smbpasswd命令更改密碼的任何用户必須遵守PAM對普通密碼更改強制執行的規則。
對於passdb backend參數,您可以在冒號後添加可選的TDB文件路徑名;
例如,tdbsam:/etc/samba/private/passwd.tdb。
注意:如果您可以訪問Windows域,您可以設置security = domain以使Samba使用域的用户名,並消除對密碼數據庫的需求。然而,為了讓域用户訪問運行Samba的機器,每個域用户必須在運行Samba的機器上擁有相同用户名的本地帳户。
Adding and Deleting Users
The first thing you need to do in order to give a Windows user access to your Samba server is to add the user to the password database with the smbpasswd -a command:
為了讓Windows用户能夠訪問您的Samba服務器,您需要先使用smbpasswd -a命令將用户添加到密碼數據庫中。
# smbpasswd -a username
The username parameter to the smbpasswd command must be a valid username on your Linux system. Like the regular system’s passwd program, smbpasswd asks you to enter the new user’s password twice. If the password passes any necessary security checks, smbpasswd confirms that it has created the new user. To remove a user, use the -x option to smbpasswd:
smbpasswd命令的用户名參數必須是您Linux系統上的有效用户名。
與常規系統的passwd程序類似,smbpasswd要求您輸入新用户的密碼兩次。
如果密碼通過了任何必要的安全檢查,smbpasswd會確認已創建新用户。
要刪除用户,請使用smbpasswd的-x選項。
# smbpasswd -x username
To temporarily deactivate a user instead, use the -d option; the -e option will reenable the user:
要暫時停用用户,可使用 -d 選項;使用 -e 選項可重新啓用用户:
# smbpasswd -d username
# smbpasswd -e username
Changing Passwords(更改密碼)
You can change a Samba password as the superuser by using smbpasswd with no options or keywords other than the username:
您可以使用 smbpasswd 以超級用户身份更改 Samba 密碼,除用户名外沒有其他選項或關鍵字:
# smbpasswd username
However, if the Samba server is running, any user can change their own Samba password by entering smbpasswd by itself on the command line.
然而,如果Samba服務器正在運行,任何用户都可以在命令行上輸入smbpasswd來更改自己的Samba密碼。
Finally, here’s one place in your configuration to beware of. If you see a line like this in your smb.conf file, be careful:
最後,這裏有一個需要注意的配置位置。如果你在smb.conf文件中看到像這樣的一行,請小心:
unix password sync = yes
This line causes smbpasswd to change a user’s normal password in addition to the Samba password. The result can be very confusing, especially when a user changes their Samba password to something that’s not their Linux password and discovers that they can no longer log in. Some distributions set this parameter by default in their Samba server packages!
這一行會導致smbpasswd在更改用户的Samba密碼的同時也更改其普通密碼。
結果可能非常令人困惑,特別是當用户將Samba密碼更改為與Linux密碼不同的內容時,發現無法再登錄。
一些發行版在其Samba服務器軟件包中默認設置了此參數!
12.4.4 Starting the Server(啓動服務器)
You may need to start your server if you didn’t install Samba from a distribution package. To do so, run nmbd and smbd with the following arguments, where smb_config_file is the full path of your smb.conf file:
如果您沒有從發行版軟件包中安裝Samba,則可能需要啓動您的服務器。
要這樣做,請使用以下參數運行nmbd和smbd,其中smb_config_file是您的smb.conf文件的完整路徑:
# nmbd -D -s smb_config_file
# smbd -D -s smb_config_file
The nmbd daemon is a NetBIOS name server, and smbd does the actual work of handling share requests. The -D option specifies daemon mode. If you alter the smb.conf file while smbd is running, you can notify the daemon of the changes with a HUP signal or use your distribution’s service restart command (such as systemctl or initctl).
nmbd守護進程是一個NetBIOS名稱服務器,而smbd則負責處理共享請求的實際工作。
-D選項指定了守護進程模式。
如果在smbd運行時修改了smb.conf文件,可以通過發送HUP信號通知守護進程進行更改,或使用您的發行版的服務重啓命令(如systemctl或initctl)。
12.4.5 Diagnostics and Log Files(診斷和日誌文件)
If something goes wrong when starting one of the Samba servers, an error message appears on the command line. However, runtime diagnostic messages go to the log.nmbd and log.smbd log files, which are usually in a /var/log directory, such as /var/log/samba. You’ll also find other log files there, such as individual logs for each individual client.
如果啓動Samba服務器時出現問題,命令行上會顯示錯誤消息。
然而,運行時診斷消息會被記錄在log.nmbd和log.smbd日誌文件中,這些文件通常位於/var/log目錄下,例如/var/log/samba。
您還會在那裏找到其他日誌文件,例如每個客户端的單獨日誌。
12.4.6 Configuring a File Share(配置文件共享)
To export a directory to SMB clients (that is, to share a directory with a client), add a section like this to your smb.conf file, where label is what you would like to call the share and path is the full directory path:
要將目錄導出到 SMB 客户端(即與客户端共享目錄),請在 smb.conf 文件中添加如下內容,其中 label 是共享的名稱,path 是完整的目錄路徑:
[label]
path = path
comment = share description
guest ok = no
writable = yes
printable = no
These parameters are useful in directory shares:
這些參數在目錄共享中非常有用:
o guest ok Allows guest access to the share. The public parameter is a synonym.
o writable A yes or true setting here marks the share as read-write. Do not allow guest access to a read write share.
o printable Specifies a printing share. This parameter must be set to no or false for a directory share.
o veto files Prevents the export of any files that match the given patterns. You must enclose each pattern between forward slashes (so that it looks like /pattern/). This example bars object files, as well as any file or directory named bin:
o guest ok 允許訪客訪問共享。public參數是其同義詞。
o writable 在此處設置為yes或true表示將共享標記為可讀寫。不要允許訪客訪問讀寫共享。
o printable 指定一個打印共享。此參數必須設置為no或false以用於目錄共享。
o veto files 阻止導出與給定模式匹配的任何文件。您必須在斜槓之間包圍每個模式(使其看起來像/pattern/)。此示例禁止導出對象文件,以及任何名為bin的文件或目錄。
veto files = /*.o/bin/
12.4.7 Home Directories(Home 目錄)
You can add a section called [homes] to your smb.conf file if you want to export home directories to users.
如果要向用户導出 home 目錄,可以在 smb.conf 文件中添加名為 [homes] 的部分。
The section should look like this:
該部分應如下所示:
[homes]
comment = home directories
browseable = no
writable = yes
By default, Samba reads the logged-in user’s /etc/passwd entry to determine their home directory for [homes]. However, if you don’t want Samba to follow this behavior (that is, you want to keep the Windows home directories in a different place than the regular Linux home directories), you can use the %S substitution in a path parameter. For example, here’s how you would switch a user’s [homes] directory to /u/user :
默認情況下,Samba會讀取已登錄用户的/etc/passwd條目,以確定他們在[homes]中的家目錄。
然而,如果您不希望Samba遵循這種行為(即,您希望將Windows的家目錄與常規的Linux家目錄放在不同的位置),您可以在路徑參數中使用%S替代。
例如,下面是如何將用户的[homes]目錄切換到/u/user的示例。
path = /u/%S
Samba substitutes the current username for the %S .
Samba將當前用户名替換為%S。
12.4.8 Sharing Printers(共享打印)
You can export all of your printers to Windows clients by adding a [printers] section to your smb.conf file. Here’s how the section looks when you’re using CUPS, the standard Unix printing system:
通過在 smb.conf 文件中添加 [printers] 部分,可以將所有打印機導出到 Windows 客户端。
下面是使用標準 Unix 打印系統 CUPS 時該部分的外觀:
[printers]
comment = Printers
browseable = yes
printing = CUPS
path = cups
printable = yes
writable = no
To use the printing = CUPS parameter, your Samba installation must be configured and linked against the CUPS library.
NOTE Depending on your configuration, you may also want to allow guest access to your printers with the guest ok = yes option rather than give a Samba password or account to everyone who needs to access the printers. For example, it’s easy to limit printer access to a single subnet with firewall rules.
要使用打印=CUPS參數,您的Samba安裝必須配置並與CUPS庫鏈接起來。
注意:根據您的配置,您可能還希望使用guest ok = yes選項允許訪客訪問打印機,而不是為每個需要訪問打印機的人提供Samba密碼或帳户。
例如,您可以通過防火牆規則輕鬆將打印機訪問限制在單個子網中。
12.4.9 Using the Samba Client(使用 Samba 客户端)
The Samba client program smbclient can print to and access remote Windows shares. This program comes in handy when you are in an environment where you must interact with Windows servers that don’t offer a Unix-friendly means of communication.
Samba客户端程序smbclient可以打印和訪問遠程的Windows共享。
當你處於一個無法提供Unix友好通信方式的Windows服務器環境中時,這個程序非常有用。
To get started with smbclient use the -L option to get a list of shares from a remote server named SERVER:
要開始使用smbclient,可以使用-L選項從一個名為SERVER的遠程服務器獲取共享列表。s
$ smbclient -L -U username SERVER
You do not need -U username if your Linux username is the same as your username on SERVER .
After running this command, smbclient asks for a password. To try to access a share as a guest, press ENTER; otherwise, enter your password on SERVER. Upon success, you should get a share list like this:
如果您的Linux用户名與服務器上的用户名相同,則無需使用-U用户名。
運行此命令後,smbclient會要求輸入密碼。如果要嘗試以訪客身份訪問共享,請按回車鍵;否則,請在服務器上輸入您的密碼。
成功後,您應該會得到一個類似於以下的共享列表:
Sharename Type Comment
--------- ---- -------
Software Disk Software distribution
Scratch Disk Scratch space
IPC$ IPC IPC Service
ADMIN$ IPC IPC Service
Printer1 Printer Printer in room 231A
Printer2 Printer Printer in basement
Use the Type field to help you make sense of each share and pay attention only to the Disk and Printer shares (the IPC shares are for remote management). This list has two disk shares and two printer shares. Use the name in the Sharename column to access each share.
使用“類型”字段來幫助您理解每個共享,並只關注磁盤和打印機共享(IPC共享用於遠程管理)。
此列表有兩個磁盤共享和兩個打印機共享。使用“共享名稱”列中的名稱來訪問每個共享。s
12.4.10 Accessing Files as a Client(以客户端身份訪問文件)
If you need only casual access to files in a disk share, use the following command. (Again, you can omit the -U username if your Linux username matches your username on the server.)
如果您只需要臨時訪問磁盤共享中的文件,請使用以下命令。
(如果您的Linux用户名與服務器上的用户名相同,可以省略-U用户名。)
$ smbclient -U username '\\SERVER\sharename'
Upon success, you will get a prompt like this, indicating that you can now transfer files:
成功後,您將會得到如下提示,表示您現在可以傳輸文件了:
smb: \>
In this file transfer mode, smbclient is similar to the Unix ftp, and you can run these commands:
在這種文件傳輸模式下,smbclient與Unix的ftp類似,您可以運行以下命令:
o get file Copies file from the remote server to the current local directory.
o put file Copies file from the local machine to the remote server.
o cd dir Changes the directory on the remote server to dir .
o lcd localdir Changes the current local directory to localdir .
o pwd Prints the current directory on the remote server, including the server and share names.
o !command Runs command on the local host. Two particularly handy commands are !pwd and !ls to determine directory and file status on the local side.
o help Shows a full list of commands.
o get 文件 從遠程服務器複製文件到當前本地目錄。
o put 文件 從本地機器複製文件到遠程服務器。
o cd 目錄 在遠程服務器上切換目錄到dir。
o lcd 本地目錄 切換當前本地目錄到localdir。
o pwd 打印遠程服務器上的當前目錄,包括服務器和共享名稱。
o !命令 在本地主機上運行命令。特別有用的命令是!pwd和!ls,用於確定本地一側的目錄和文件狀態。
o help 顯示完整的命令列表。
Using the CIFS Filesystem(使用 CIFS 文件系統)
If you need frequent, regular access to files on a Windows server, you can attach a share directly to your system with mount. The command syntax is shown below. Notice the use of SERVER:sharename rather than the normal \SERVER\sharename format.
如果需要頻繁、定期訪問 Windows 服務器上的文件,可以使用掛載將共享直接附加到系統上。
命令語法如下所示。注意使用的是 SERVER:sharename 而不是正常的 \SERVER\sharename 格式。
# mount -t cifs SERVER:sharename mountpoint -o user=username,pass=password
In order to use mount like this, you must have the Common Internet File System (CIFS) utilities available for Samba. Most distributions offer these as a separate package.
要使用這樣的掛載,必須為 Samba 安裝通用互聯網文件系統(CIFS)實用程序。
大多數發行版都將其作為一個單獨的軟件包提供。
12.5 NFS Clients(NFS 客户端)
The standard system for file sharing among Unix systems is NFS; there are many different versions of NFS for different scenarios. You can serve NFS over TCP and UDP, with a large number of authentication and encryption techniques. Because there are so many options, NFS can be a big topic, so we’ll just stick to the basics of NFS clients.
Unix系統之間進行文件共享的標準系統是NFS;對於不同的場景,有許多不同版本的NFS。
您可以使用TCP和UDP來提供NFS服務,並且有許多身份驗證和加密技術可供選擇。
由於選項很多,NFS可能是一個龐大的主題,因此我們只會討論NFS客户端的基礎知識。
To mount a remote directory on a server with NFS, use the same basic syntax as for mounting a CIFS directory:
要使用NFS在服務器上掛載遠程目錄,使用與掛載CIFS目錄相同的基本語法:
# mount -t nfs server:directory mountpoint
Technically, you don’t need the -t nfs option because mount should figure this out for you, but you may want to investigate the options in the nfs(5) manual page. (You’ll find several different options for security using the sec option. Many administrators on small, closed networks use host-based access control. However, more sophisticated methods, such as Kerberos-based authentication, require additional configuration on other parts of your system.)
從技術上講,您不需要-t nfs選項,因為mount應該會自動識別,但是您可能希望查看nfs(5)手冊頁面中的選項。
(您將發現使用sec選項進行安全性設置的幾個不同選項。
許多小型封閉網絡上的管理員使用基於主機的訪問控制。
但是,更復雜的方法,如基於Kerberos的身份驗證,需要在系統的其他部分進行額外的配置。)
When you find that you’re making greater use of filesystems over a network, set up the automounter so that your system will mount the filesystems only when you actually try to use them in order to prevent problems with dependencies on boot. The traditional automounting tool is called automount, with a newer version called amd, but much of this is now being supplanted by the automount unit type in systemd.
當您發現自己在網絡上更多地使用文件系統時,請設置自動掛載器,以便在您實際嘗試使用它們時,您的系統僅在需要時掛載文件系統,以避免引導時的依賴問題。
傳統的自動掛載工具稱為automount,新版本稱為amd,但是現在大部分已被systemd中的automount單元類型取代。
12.6 Further Network File Service Options and Limitations(進一步的網絡文件服務選項和限制)
Setting up an NFS server to share files to other Linux machines is more complicated than using a simple NFS client. You need to run the server daemons (mountd and nfsd) and set up the /etc/exports file to reflect the directories that you’re sharing. However, we won’t cover NFS servers primarily because shared storage over a network is often made much more convenient by simply purchasing an NAS device to handle it for you. Many of these devices are Linux based, so they’ll naturally have NFS server support. Vendors add value to their NAS devices by offering their own administration tools to take the pain out of tedious tasks such as setting up RAID configurations and cloud backups.
設置一個NFS服務器以便與其他Linux機器共享文件比使用簡單的NFS客户端要複雜得多。
您需要運行服務器守護進程(mountd和nfsd)並設置/etc/exports文件以反映您要共享的目錄。
然而,我們不會涉及NFS服務器,主要是因為通過網絡共享存儲通常可以通過購買NAS設備來更方便地處理。
許多這些設備都是基於Linux的,因此它們自然會有NFS服務器支持。
供應商通過提供自己的管理工具來增加NAS設備的價值,以減少設置RAID配置和雲備份等繁瑣任務的痛苦。
Speaking of cloud backups, another network file service option is cloud storage. This can be handy when you need the extra storage that comes with automatic backups and you don’t mind an extra hit on performance. It’s especially useful when you don’t need the service for a long time or don’t need to access it very much. You can usually mount Internet storage much as you would NFS.
説到雲備份,另一個網絡文件服務選項是雲存儲。
當您需要額外的存儲空間和自動備份,並且不介意對性能造成額外的影響時,這可能會很方便。
當您不需要長時間使用該服務或不需要頻繁訪問時,它尤其有用。您通常可以像掛載NFS一樣掛載互聯網存儲。
Although NFS and other file-sharing systems work well for casual use, don’t expect great performance. Readonly access to larger files should work well, such as when you’re streaming audio or video, because you’re reading data in large, predictable chunks that don’t require much back-and-forth communication between the file server and its client. As long as the network is fast enough and the client has enough memory, a server can supply data as needed.
儘管NFS和其他文件共享系統在日常使用中效果良好,但不要期望有很好的性能。
只讀訪問較大的文件應該效果良好,例如在流式傳輸音頻或視頻時,因為您正在以大塊、可預測的數據讀取方式讀取數據,這不需要文件服務器和客户端之間的大量來回通信。
只要網絡足夠快且客户端具有足夠的內存,服務器就可以根據需要提供數據。
Local storage is much faster for tasks involving many small files, such as compiling software packages and starting desktop environments. The picture becomes more complicated when you have a larger network with many users accessing many different machines, because there are tradeoffs between convenience, performance, and ease of administration.
對於涉及許多小文件的任務(例如編譯軟件包和啓動桌面環境),本地存儲速度更快。
當您擁有一個較大的網絡,有許多用户訪問許多不同的機器時,情況變得更加複雜,因為在方便性、性能和管理易用性之間存在權衡。