目录

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

Figure 12-1. Normal rsync copy

图 12-1. 正常 rsync 复制

Figure 12-2. Effect of trailing slash in 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服务器,请执行以下步骤:

  1. Create an smb.conf file.
  2. Add file-sharing sections to smb.conf.
  3. Add printer-sharing sections to smb.conf.
  4. Start the Samba daemons nmbd and smbd.
  5. 创建一个smb.conf文件。
  6. 在smb.conf中添加文件共享部分。
  7. 在smb.conf中添加打印机共享部分。
  8. 启动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.

对于涉及许多小文件的任务(例如编译软件包和启动桌面环境),本地存储速度更快。

当您拥有一个较大的网络,有许多用户访问许多不同的机器时,情况变得更加复杂,因为在方便性、性能和管理易用性之间存在权衡。


Xander
198 声望51 粉丝