Section 11.4. smbclient


11.4. smbclient

smbclient is a basic part of the Samba suite and a very versatile tool. It can be used for browsing shares on servers, testing configurations, debugging, accessing shared printers, backing up shared data, and automating administrative tasks in shell scripts. And unlike the native filesystem support we have previously discussed, smbclient is portable to all Unix variants that support Samba.

In Chapter 2, we showed you how to use smbclient to test your Samba installations, and we've already covered smbclient's printing functionality in Chapter 7. In this section, we focus mostly on running smbclient as an interactive shell, using its ftp-like commands to access shared directories on the network. A complete reference to the tool can be found in Appendix A.

11.4.1. Listing Shares and Workgroups

The -L option can be used with smbclient to list the resources on a single computer. Assuming that the Samba server is configured to take the role of the master browser, we can also obtain a list of the computers in the domain or workgroup. The following command attempts to anonymously (-N option) enumerate the shares and browse list from the server maple.plainjoe.org:

 $ smbclient -L maple.plainjoe.org -N Anonymous login successful Domain=[VALE] OS=[Unix] Server=[Samba 3.0.22]         Sharename       Type      Comment         ---------       ----      -------         netlogon        Disk      NETLOGON Service         profile$        Disk      User roaming profiles         print$          Disk      Print Drivers         public          Disk      Public access file share         software        Disk      Software Repository         C$              Disk      Administrative share         IPC$            IPC       IPC Service (Samba 3.0.22)         hp2100          Printer   HP LaserJet 2100 Series PCL 6 Anonymous login successful Domain=[VALE] OS=[Unix] Server=[Samba 3.0.22]         Server               Comment         ---------            -------         ELM                  Samba 3.0.22         HAMMER               XP Development box         MAPLE                Samba 3.0.22         Workgroup            Master         ---------            -------         AD                   SPUD         GLASS                CRYSTAL         VALE                 MAPLE 

The first section of output contains the enumerated file and printer shares on maple. This list includes only shares with a name that does not exceed 12 characters in length.[*] The three hosts listed in the Server column of section 2 are the ones in maple's browse list. Remember from Chapter 8 that each browse master maintains a list of servers in its workgroup. The workgroups and master browsers known by maple are listed in the final section.

[*] This length limitation was removed in Samba 3.0.23.

Running the same command against the Windows XP host hammer generates an ACCESS_DENIED error when enumerating the shares:

 $ smbclient -L hammer -N Anonymous login successful Domain=[VALE] OS=[Windows 5.1] Server=[Windows 2000 LAN Manager]         Sharename       Type      Comment         ---------       ----      ------- Error returning browse list: NT_STATUS_ACCESS_DENIED 

Chapter 8 described anonymous browsing as a casualty of the security war. The solution is to provide credentials when connecting to the server. The -U option allows you to specify a username other than your Unix account name when connecting. Without the parameter (and unless you explicitly ask for an anonymous login using the -N option), smbclient obtains the username from either the USER or LOGNAME environment variables:

 $ smbclient -L hammer -U lizard Password: <enter password for lizard> Domain=[VALE] OS=[Windows 5.1] Server=[Windows 2000 LAN Manager]         Sharename       Type      Comment         ---------       ----      -------         public          Disk         IPC$            IPC       Remote IPC         Users           Disk         ADMIN$          Disk      Remote Admin         C$              Disk      Default share 

smbclient makes use of the same mechanisms for retrieving passwords as the Linux mount.cifs tool. For noninteractive sessions, you can specify a password using the PASSWD environment variable or point to a file containing the password using the PASSWD_FD or PASSWD_FILE environment settings. You can also specify a credentials file using the -A (or --authentication-file) command-line option. Finally, you can also specify the password on the command line by appending it to the username with the % character.

11.4.2. An Interactive smbclient Session

A common use for smbclient is to create an ftp-like shell to access SMB resources on the network. To begin a session, smbclient must be provided with the UNC of a resource (which you can find using the -L option) on the command line. Forward slashes are accepted by smbclient for the share's UNC, which makes entering the UNC on the command line easier. Backslashes can also be used, but they must be quoted or escaped, and it is somewhat more difficult to type '\\elm\public' or \\\\elm\\public. You can optionally follow the UNC path with a password to avoid being prompted.

 $ smbclient //elm/public Domain=[VALE] OS=[Unix] Server=[Samba 3.0.22] Password: <enter password> smb: \> 

After connecting to the share, smbclient displays the smb: \> prompt and waits for a command to be entered. Commands are similar to those with which you might be familiar in ftp and are also somewhat similar to Unix shell commands. To retreive a list of smbclient commands, use the help command:

 smb: \> help ?              altname   archive    blocksize     cancel case_sensitive cd        chmod      chown         del dir            du        exit       get           getfacl hardlink       help      history    lcd           link lowercase      ls        mask       md            mget mkdir          more      mput       newer         open print          prompt    put        pwd           q queue          quit      rd         recurse       reget rename         reput     rm         rmdir         setmode stat           symlink   tar        tarmode       translate volume         vuid      logon      listconnect   showconnect ! 

Some commands in the previous list are synonyms for other commands. For example, the ? command is a synonym for help. You can give this command the name of another command as an argument to get a concise reminder of what the command does and how to use it:

 smb: \> help ls HELP ls:         <mask> list the contents of the current directory 

The term <mask> refers to a file-matching pattern as commonly found in Unix shells and utilities. For example, the following command lists all files ending in doc in the current directory on the remote system. The columns show the filename followed by the file's MS-DOS attributes, size, and time of last modification.

 smb: \> ls *doc   ms-ProfPol-wp.doc          A      131  Tue Jun 18 09:12:34 2006   smbclient.doc              A    33969  Mon Jun 10 20:22:24 2006   smbmount.doc               A     7759  Mon Jun 10 20:20:00 2006             48590 blocks of size 524288. 40443 blocks available 

As with any other Unix utility, smbclient maintains a working directory on the local host, which can be modified with the lcd command, and a working directory on the remote SMB share, which can be changed using cd. For example, to change to the trans directory in the SMB/CIFS share, execute the following command. The smb: \> prompt changes to reflect the remote working directory.

 smb: \> cd trans smb: \trans\> 

To change your current directory on the local system, use the lcd command:

 smb: \trans\> lcd /data/snd the local directory is now /data/snd 

Most of smbclient's commands perform operations on remote files and directories. There is no command for listing the contents of the local directory. However, smbclient does allows a shell escape. Any command preceded by an exclamation point (!) is interpreted as a shell command and is run in a subshell on the local system. Therefore, to display the contents of the current local working directory, invoke the ! ls command.

 smb: \trans\> !pwd && ls -l /data/snd total 16 drwxrwxr-x    2 lizard  users   4096 Jan 10 14:46 data -rw-rw-r--    1 lizard  users    131 Jan 10 02:22 releasenotes.html 

The put and get commands transfer files to and from the remote server. For example, the following command uploads the file releasenotes.html to \\elm\public\trans:

 smb: \trans\> put releasenotes.html putting file releasenotes.html as \trans\releasenotes.html   (127.9 kb/s) (average 10.7 kb/s) 

Unlike ftp, smbclient does not have ascii and binary commands to set the type of the file that is being transferred. All files are transferred byte for byte with no modification of the original file. The only place where this is an issue is when dealing with ASCII text files. Unix systems used the carriage return (CR) character to delimit lines of text. while DOS and Windows systems use a combination of carriage return and line feed (LF) for the same purpose.

Before transferring a text file from a Unix system to a Windows system, you might want to use the GNU unix2dos command to reformat newlines in the file to match the carriage return/line feed (CRLF) standard:

 $ unix2dos text_file > text_file.txt 

A complementary dos2unix command can handle the reverse conversion. In the long run, it is probably easier to provide users with a text editor that is capable of handling both file formats.


The mget and mput commands transfer a list of files or a set of files matching a DOS-style wildcard pattern. Thus, to copy all files from the remote subdirectory plain, using the wildcard pattern plain/*, enter:

 smb: \trans\> mget plain/* 

By default, smbclient issues prompts to confirm the transfer of each file:

 smb: \trans\> mget plain/* Get file tomm.wav? y Get file toml.wav? y Get file tomh.wav? y Get file snare.wav? n Get file rim.wav? n Get file handclap.wav? y Get file bassdrum.wav? n 

You can toggle this prompting behavior on and off by issuing the prompt command:

 smb: \> prompt prompting is now off 

If you specify the name of a directory to the mget command, smbclient does not copy its contents by default. To transfer the entire directory tree, set the recurse option:

 smb: \> recurse directory recursion is now on 

After disabling prompting and enabling recursive gets, we can copy a directory tree with the mget command. The original folder hierarchy will still be intact on the new system:

 smb: \> mget winadmin  getting file \winadmin\bin\putty.exe of size 380928 as putty.exe (6200.0 kb/s) (average 6200.0 kb/s) getting file \winadmin\bin\dhcpadmn.cnt of size 1849 as dhcpadmn.cnt (180.6 kb/s) (average 5340.1 kb/s) getting file \winadmin\bin\dhcpadmn.exe of size 238352 as dhcpadmn.exe (8313.0 kb/s) (average 6189.5 kb/s) getting file \winadmin\bin\dhcpadmn.hlp of size 56486 as dhcpadmn.hlp (6895.2 kb/s) (average 6242.8 kb/s)  <...remaining output deleted...> 

Directory recursion applies to all commands, so if an ls command is used while directory recursion is on, all files in the directory tree are listed. To turn directory recursion off again, reenter the recurse command. At the same time, you might also wish to toggle prompting back to its initial state:

 smb: \trans\> recurse directory recursion is now off 

Samba 3.0.12 gave smbclient support for MS-DFS (covered in Chapter 6). This means that you can follow MS-DFS referrals by changing directories. This next example connects to an MS-DFS root share named dfs on the server primary:

 $ smbclient //primary/dfs -U Administrator Password: Domain=[COLOR] OS=[Windows 5.0] Server=[Windows 2000 LAN Manager] smb: \> dir   .                       D        0  Mon May  9 15:06:14 2005   ..                      D        0  Mon May  9 15:06:14 2005   printmig.exe            A   215632  Fri Feb 18 09:13:08 2005   spud                    D        0  Fri Apr  1 10:00:00 2005           63881 blocks of size 32768. 4851 blocks available smb: \> cd spud smb: \spud\> ls   .                       D        0  Tue Feb 28 11:35:51 2006   ..                      D        0  Tue Feb 28 11:35:51 2006   ad.plainjoe.org.txt     A      458  Tue Feb 28 11:35:51 2006   dns.log                 A      116  Tue Feb 28 11:34:45 2006           63881 blocks of size 32768. 4851 blocks available 

The showconnect command displays the UNC path of the current working directory. For non-DFS shares, this will always be the original path to which you connected. But for MS-DFS root shares, the path displayed can vary depending on your working directory. In the following output you can see that the directory spud is a referral to the UNC path \\spud\public:

 smb: \spud\> showconnect //spud/public 

You can view the list of servers smbclient has connected to during its current session using the listconnect command. In the following example, entry 0 is the DFS referral already discussed, line 1 refers to the original UNC path specified when launching smbclient, and line 2 is a connection initiated by smbclient itself when checking for MS-DFS support.

 smb: \spud\> listconnect 0:      server=spud, share=public 1:      server=primary, share=dfs 2:      server=primary, share=IPC$ 

There are other smbclient commands that you might find useful. The mkdir command can be used to create a directory, rmdir removes a directory, rm deletes a file, and rename changes a file's name. These behave very similarly to their Unix shell counterparts.

To exit smbclient, use the exit or quit command:

 smb: \trans\> quit 

11.4.3. Backups with smbclient

Another popular use of smbclient is to create and restore backups of SMB/CIFS file shares. smbclient supports the creation of backups using the standard tar format, making them easy to work with and portable among different versions of Unix. Using smbclient on a Unix server to run network backups can result in a more centralized and easily managed solution for providing data integrity, because both SMB shares and NFS filesystems can be backed up on the same system.

You can perform backups in two ways. To back up an entire share, the simplest method is to use the -Tc option on the command line. In this scenario, we are backing up \\hammer\public. The resulting tar filename encodes the date in the form YYYY-MM-DD (e.g., hammer-2006-07-25.tar.gz).

 $ smbclient //hammer/public -A ~/.smbpw -Tc  |\   gzip -9 > hammer-'date +%Y-%m-%d'.tar.gz 

By using the -D option, it is possible to back up an individual directory in the share, rather than the whole share. The following command causes smbclient to change its working directory to the documents directory of the \\hammer\public share before starting the backup:

 $ smbclient //hammer/public -A ~/.smbpw -D documents -Tc  |\   gzip -9 > hammer-'date +%Y-%m-%d'.tar.gz 

It is also possible to use smbclient's tar command in interactive mode, which can be useful when developing noninteractive scripts, to ensure that they are doing the right thing. The tarmode command is used to control the behavior of the tar command when copying files. The following example instructs smbclient to tar all files, including those with the System and Hidden DOS attributes set:

 $ smbclient //hammer/public Password: <enter password> smb: \> cd documents smb: \documents\> tarmode full hidden system quiet smb: \documents\> tar c hammer-2006-07-25.tar 

The previous command backs up only the \\hammer\public\documents subdirectory, using the settings specified in the tarmode command. To have this type of backup run automatically from a script, embed the commands in a -c option:

 $ smbclient //hammer/public -A ~/.smbpw \   -c "cd trans; tarmode full hidden system quiet; \   tar c hammer-'date +%Y-%m-%d'.tar" 

When runing the tar command (or the -T option), it is necessary to specify either the c option to create a backup archive or the x option to extract (restore) one. Other options can be appended to the option string and are explained in the section on smbclient in Appendix A. They allow you to create incremental backups, specify which files to include or exclude from the backup, and specify a few other miscellaneous settings.

An alternative to extracting the tar archive directly to the SMB share is to use the Unix system's tar command to extract it to a directory on the Unix server, and then copy the desired files to a shared directory. This allows a greater amount of control over the restoration process, as when correcting for an accidental file deletion or reverting a set of files to a previous condition.


For example, suppose that we wish to create an incremental backup of a share and reset the archive bit on the files to set things up for the next incremental backup. There are two ways to achieve this. We could run the following interactive commands:

 smb: \> tarmode inc reset quiet smb: \> tar c backup.tar 

Or we could specify the -Tcgaq option on the smbclient command line.

The best strategy for using smbclient for network backups depends on your local configuration. If you have only a few Windows systems sharing a small amount of data, you might create a script containing smbclient -Tc commands to back up each share to a separate tar file, placing the files in a directory that is included with regular backups of the Unix system. If you have huge SMB/CIFS shares on your network, you might prefer to write the backup directly to a tape drive. This can be done with smbclient just as you would with a Unix tar command:

 $ smbclient //homeserver/users -A ~/.smbpw -Tc > /dev/tape 

11.4.4. Programming with smbclient

We'll finish our coverage of smbclient with some general comments about including the tool in your own shell scripts. You've seen that smbclient allows a list of commands to be passed on the command line using the -c option. For instance, we can noninteractively copy the file \\elm\public\files\memo.txt to /data/files using the following single command:

 $ smbclient //elm/public -A ~/. smbpw -c \   "lcd /data/files; cd files; get memo.txt" 

Everything that smbclient needs to know to perform the operation has been specified in the command. There is no password prompting, so a command such as this can easily be placed inside a shell script.

Readers interested in more details on shell scripts should refer to Classic Shell Scripting, by Arnold Robbins and Nelson H. F. Beebe (O'Reilly).


By using smbclient in this manner, it is possible to create customized commands using shell functions, scripts, or aliases. For example, suppose that we wanted a command to print a short listing of files in a shared directory, showing just the names of the files. Using a bash function, we could define a function smbls as follows:

 ## ~/.profile function smbls {     share='echo $1 | cut -d '/' -f '1-4''     dir='echo $1 | cut -d '/' -f '5-''     smbclient $share -c "cd $dir; ls" -A ~/.smbpw | \         grep "^  " | cut -d ' ' -f 3 - | sort } 

After defining this function and importing it into our shell, we can use smbls like this:

 $ smbls //elm.plainjoe.org/public CD-images lectures ms-ProfPol-wp.doc profile-map trans $ smbls //elm.plainjoe.org/public/trans . .. lecture1.mp3 lecture2.mp3 lecture3.mp3 lecture4.mp3 

smbclient subscribes to the Unix philosphy of chaining tools together to achieve one task. This is just one simple example. If you develop a very clever or elaborate solution to a common administrative problem, consider making it available to others in the Samba community using one of the mailing lists covered in Chapter 12!




Using Samba
Using Samba: A File and Print Server for Linux, Unix & Mac OS X, 3rd Edition
ISBN: 0596007698
EAN: 2147483647
Year: 2004
Pages: 135

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net