Linux smbclient Command with Practical Examples

LinuxLinuxBeginner
Practice Now

Introduction

In this lab, we will explore the Linux smbclient command and its practical applications. The smbclient utility is a powerful tool that allows Linux systems to interact with Windows file shares (SMB/CIFS shares). SMB (Server Message Block) is a network protocol that Windows uses for file sharing, and smbclient allows Linux users to access these shares.

We will start by installing smbclient on our Ubuntu 22.04 system, learn the basic syntax of the command, and then demonstrate how to connect to Windows shares, navigate directories, and transfer files.

By the end of this lab, you will be able to:

  • Install and configure the smbclient utility
  • Connect to Windows shares from Linux
  • Navigate and list files on Windows shares
  • Transfer files between Linux and Windows systems

Linux Commands Cheat Sheet


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("Linux")) -.-> linux/BasicSystemCommandsGroup(["Basic System Commands"]) linux(("Linux")) -.-> linux/BasicFileOperationsGroup(["Basic File Operations"]) linux(("Linux")) -.-> linux/FileandDirectoryManagementGroup(["File and Directory Management"]) linux(("Linux")) -.-> linux/SystemInformationandMonitoringGroup(["System Information and Monitoring"]) linux(("Linux")) -.-> linux/PackagesandSoftwaresGroup(["Packages and Softwares"]) linux/BasicSystemCommandsGroup -.-> linux/echo("Text Display") linux/BasicSystemCommandsGroup -.-> linux/help("Command Assistance") linux/BasicFileOperationsGroup -.-> linux/ls("Content Listing") linux/BasicFileOperationsGroup -.-> linux/cp("File Copying") linux/FileandDirectoryManagementGroup -.-> linux/cd("Directory Changing") linux/FileandDirectoryManagementGroup -.-> linux/mkdir("Directory Creating") linux/SystemInformationandMonitoringGroup -.-> linux/service("Service Managing") linux/PackagesandSoftwaresGroup -.-> linux/apt("Package Handling") subgraph Lab Skills linux/echo -.-> lab-422922{{"Linux smbclient Command with Practical Examples"}} linux/help -.-> lab-422922{{"Linux smbclient Command with Practical Examples"}} linux/ls -.-> lab-422922{{"Linux smbclient Command with Practical Examples"}} linux/cp -.-> lab-422922{{"Linux smbclient Command with Practical Examples"}} linux/cd -.-> lab-422922{{"Linux smbclient Command with Practical Examples"}} linux/mkdir -.-> lab-422922{{"Linux smbclient Command with Practical Examples"}} linux/service -.-> lab-422922{{"Linux smbclient Command with Practical Examples"}} linux/apt -.-> lab-422922{{"Linux smbclient Command with Practical Examples"}} end

Installing smbclient on Ubuntu 22.04

The smbclient package is a command-line tool that enables Linux systems to interact with SMB/CIFS file shares commonly used in Windows environments. In this step, we'll install this package on our Ubuntu system.

Let's first update the package index to ensure we get the latest version:

sudo apt update

You should see output similar to this:

Hit:1 http://archive.ubuntu.com/ubuntu jammy InRelease
Get:2 http://security.ubuntu.com/ubuntu jammy-security InRelease [110 kB]
Get:3 http://archive.ubuntu.com/ubuntu jammy-updates InRelease [114 kB]
Get:4 http://archive.ubuntu.com/ubuntu jammy-backports InRelease [99.8 kB]
Fetched 324 kB in 1s (324 kB/s)
Reading package lists... Done

Now, let's install the smbclient package:

sudo apt install -y smbclient

The output will look something like this:

Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  libsmbclient
Suggested packages:
  samba-common
The following NEW packages will be installed:
  libsmbclient smbclient
0 upgraded, 2 newly installed, 0 to remove and 0 not upgraded.
Need to get 479 kB of archives.
After this operation, 1,711 kB of additional disk space will be used.
Get:1 http://archive.ubuntu.com/ubuntu jammy/main amd64 libsmbclient amd64 2:4.15.5+dfsg-1ubuntu2 [222 kB]
Get:2 http://archive.ubuntu.com/ubuntu jammy/main amd64 smbclient amd64 2:4.15.5+dfsg-1ubuntu2 [257 kB]
Fetched 479 kB in 0s (1,030 kB/s)
Selecting previously unselected package libsmbclient.
(Reading database ... 26536 files and directories currently installed.)
Preparing to unpack .../libsmbclient_2%3a4.15.5+dfsg-1ubuntu2_amd64.deb ...
Unpacking libsmbclient (2:4.15.5+dfsg-1ubuntu2) ...
Selecting previously unselected package smbclient.
Preparing to unpack .../smbclient_2%3a4.15.5+dfsg-1ubuntu2_amd64.deb ...
Unpacking smbclient (2:4.15.5+dfsg-1ubuntu2) ...
Setting up libsmbclient (2:4.15.5+dfsg-1ubuntu2) ...
Setting up smbclient (2:4.15.5+dfsg-1ubuntu2) ...
Processing triggers for man-db (2.10.2-1) ...
Processing triggers for libc-bin (2.35-0ubuntu3) ...

To verify that smbclient has been installed correctly, run:

smbclient --version

You should see output showing the version of smbclient that was installed:

Version 4.15.5-Ubuntu

Now that we have installed smbclient, we can start using it to interact with SMB/CIFS shares.

Understanding smbclient Basics

Now that we have installed smbclient, let's understand its basic usage and syntax before connecting to actual SMB shares.

Command Syntax

The basic syntax for the smbclient command is:

smbclient //server/share -U username%password [options]

Where:

  • //server/share is the UNC (Universal Naming Convention) path to the SMB share
  • -U username%password specifies the username and password for authentication
  • [options] are additional parameters you can provide

Creating a Local Directory for Practice

Let's create a directory where we can store files that we might want to transfer to or from SMB shares:

mkdir -p ~/project/smb-files

Let's create a sample file in this directory that we can use later:

echo "This is a test file for SMB transfer" > ~/project/smb-files/test.txt

Exploring smbclient Help

To see all the available options for smbclient, use the help command:

smbclient --help

This will display a lengthy help text with all the available options. Here's a snippet of what you might see:

Usage: smbclient [OPTION...] service <password>
  -M, --message=HOST                           Send message
  -I, --ip-address=IP                          Use this IP to connect to
  -E, --stderr                                 Write messages to stderr instead of stdout
  -L, --list=HOST                              Get a list of shares available on a host
  -T, --tar=<c|x>IXFvgbNan                     Command line tar
  -D, --directory=DIR                          Start from directory
...

Common smbclient Commands

When you're connected to an SMB share with smbclient, you can use various commands to navigate and operate on files. Here are some common commands:

  • ls or dir: List files and directories
  • cd directory: Change to a different directory
  • get file [localfile]: Download a file from the share
  • put file [remotefile]: Upload a file to the share
  • mget files...: Download multiple files
  • mput files...: Upload multiple files
  • mkdir directory: Create a directory
  • rmdir directory: Remove a directory
  • rm file: Delete a file
  • help or ?: Display help
  • quit or exit: Exit smbclient

Now that we understand the basics of smbclient, in the next step, we'll see how to connect to an actual SMB share.

Setting Up a Test SMB Environment

In a real-world scenario, you would connect to an actual Windows or Samba server. However, for this lab, we'll simulate an SMB environment using a local Samba server. This approach allows us to practice smbclient commands without requiring access to an external server.

Installing Samba Server

First, let's install the Samba server package:

sudo apt install -y samba

You should see output indicating the installation process:

Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  attr python3-dnspython python3-gpg python3-ldb python3-markdown python3-pygments python3-samba samba-common samba-common-bin samba-dsdb-modules samba-libs samba-vfs-modules tdb-tools
Suggested packages:
  bind9 bind9utils ctdb ldb-tools ntp | chrony python-markdown-doc python-pygments-doc
The following NEW packages will be installed:
  attr python3-dnspython python3-gpg python3-ldb python3-markdown python3-pygments python3-samba samba samba-common samba-common-bin samba-dsdb-modules samba-libs samba-vfs-modules tdb-tools
0 upgraded, 14 newly installed, 0 to remove and 0 not upgraded.
Need to get 10.1 MB of archives.
After this operation, 51.3 MB of additional disk space will be used.
...

Creating a Samba Share

Now, let's create a simple Samba share configuration. First, let's back up the original configuration file:

sudo cp /etc/samba/smb.conf /etc/samba/smb.conf.backup

Create a directory to share:

mkdir -p ~/project/samba-share

Let's create a test file in this shared directory:

echo "This is a test file in our Samba share" > ~/project/samba-share/shared-test.txt

Now, let's create a simplified Samba configuration:

sudo bash -c 'cat > /etc/samba/smb.conf << EOF
[global]
   workgroup = WORKGROUP
   server string = Samba Server
   log file = /var/log/samba/log.%m
   max log size = 50
   security = user
   map to guest = bad user

[testshare]
   path = /home/labex/project/samba-share
   browseable = yes
   read only = no
   guest ok = yes
   force user = labex
EOF'

Add the current user to Samba users and set a password for testing:

sudo smbpasswd -a labex

When prompted, enter a simple password like password (you'll need to type it twice):

New SMB password:
Retype new SMB password:
Added user labex.

Restart the Samba service to apply the changes:

sudo service smbd restart

Now we have a local Samba share called testshare set up on our system. We can use smbclient to connect to it as if it were a remote Windows share.

Connecting to SMB Shares with smbclient

Now that we have our test SMB environment set up, let's connect to the share using smbclient.

Listing Available Shares

First, let's list all available shares on our local machine:

smbclient -L localhost -U labex

When prompted, enter the password you set for the Samba user (e.g., password):

Enter WORKGROUP\labex's password:

You should see output similar to this:

        Sharename       Type      Comment
        ---------       ----      -------
        testshare       Disk
        IPC$            IPC       IPC Service (Samba Server)
Reconnecting with SMB1 for workgroup listing.

        Server               Comment
        ---------            -------
        UBUNTU               Samba Server

        Workgroup            Master
        ---------            -------
        WORKGROUP            UBUNTU

This shows our newly created testshare share is available.

Connecting to the Share

Now, let's connect to the testshare share:

smbclient //localhost/testshare -U labex

Enter the password when prompted:

Enter WORKGROUP\labex's password:

Upon successful connection, you'll see the smbclient prompt:

Try "help" to get a list of possible commands.
smb: \>

Now that we're connected to the share, let's explore some basic commands:

To list files in the current directory:

smb: \> ls

You should see the test file we created earlier:

  .                                   D        0  Tue Nov 30 12:00:00 2022
  ..                                  D        0  Tue Nov 30 12:00:00 2022
  shared-test.txt                     N       37  Tue Nov 30 12:00:00 2022

                8467839 blocks of size 4096. 3524491 blocks available

Creating a Remote Directory

Let's create a new directory on the SMB share:

smb: \> mkdir test-directory

List the contents again to verify the directory was created:

smb: \> ls

You should see the new directory:

  .                                   D        0  Tue Nov 30 12:01:00 2022
  ..                                  D        0  Tue Nov 30 12:00:00 2022
  shared-test.txt                     N       37  Tue Nov 30 12:00:00 2022
  test-directory                      D        0  Tue Nov 30 12:01:00 2022

                8467839 blocks of size 4096. 3524491 blocks available

Changing Directories

Let's change to the directory we just created:

smb: \> cd test-directory

Verify we're in the new directory:

smb: \test-directory\> ls

The output should show an empty directory:

  .                                   D        0  Tue Nov 30 12:01:00 2022
  ..                                  D        0  Tue Nov 30 12:01:00 2022

                8467839 blocks of size 4096. 3524491 blocks available

To go back to the parent directory:

smb: \test-directory\> cd ..

Getting Help Within smbclient

To see the available commands within smbclient:

smb: \> help

You'll see a list of all available commands:

?              allinfo        altname        archive        backup
blocksize      cancel         case_sensitive cd             chmod
chown          close          del            dir            du
echo           exit           get            getfacl        geteas
hardlink       help           history        iosize         lcd
link           lock           lowercase      ls             l
mask           md             mget           mkdir          more
mput           newer          notify         open           posix
posix_encrypt  posix_open     posix_mkdir    posix_rmdir    posix_unlink
print          prompt         put            pwd            q
queue          quit           readlink       rd             recurse
reget          rename         reput          rm             rmdir
showacls       setea          setmode        stat           symlink
tar            tarmode        timeout        translate      unlock
volume         vuid           wdel           logon          listconnect
showconnect    tcon           tdis           tid            utimes
logoff         ..             !

When you're done exploring, you can exit the smbclient session:

smb: \> quit

In the next step, we'll learn how to transfer files between the Linux system and SMB shares.

Transferring Files with smbclient

In this final step, we'll learn how to transfer files between our Linux system and the SMB share.

Reconnecting to the Share

Let's connect again to our SMB share:

smbclient //localhost/testshare -U labex

Enter the password when prompted:

Enter WORKGROUP\labex's password:

You should see the smbclient prompt:

Try "help" to get a list of possible commands.
smb: \>

Uploading Files to the Share

Let's upload the test file we created earlier to the SMB share. First, we need to check our current local directory:

smb: \> !pwd

This runs the pwd command on your local system and should display:

/home/labex/project

We need to change to the directory where our test file is located:

smb: \> lcd ~/project/smb-files

Verify we're in the correct directory:

smb: \> !ls

You should see:

test.txt

Now, let's upload the file to the SMB share:

smb: \> put test.txt

You should see a message indicating the file was transferred:

putting file test.txt as \test.txt (38.5 kb/s) (average 38.5 kb/s)

Verify the file was uploaded:

smb: \> ls

You should see:

  .                                   D        0  Tue Nov 30 12:02:00 2022
  ..                                  D        0  Tue Nov 30 12:00:00 2022
  shared-test.txt                     N       37  Tue Nov 30 12:00:00 2022
  test-directory                      D        0  Tue Nov 30 12:01:00 2022
  test.txt                            N       33  Tue Nov 30 12:02:00 2022

                8467839 blocks of size 4096. 3524491 blocks available

Downloading Files from the Share

Now, let's download a file from the SMB share to our local system. First, let's create a new directory to store the downloaded files:

smb: \> !mkdir -p ~/project/smb-downloads

Change to that directory:

smb: \> lcd ~/project/smb-downloads

Now, download the file:

smb: \> get shared-test.txt

You should see a message indicating the file was transferred:

getting file \shared-test.txt of size 37 as shared-test.txt (37.0 KiloBytes/sec) (average 37.0 KiloBytes/sec)

Verify the file was downloaded:

smb: \> !ls

You should see:

shared-test.txt

Using mget and mput for Multiple Files

The mget and mput commands allow you to transfer multiple files at once. Let's try creating a few more files on our local system:

smb: \> !cd ~/project/smb-files && touch file1.txt file2.txt file3.txt

Now, let's upload all .txt files at once:

smb: \> lcd ~/project/smb-files
smb: \> mput *.txt

For each file, you'll be asked for confirmation. Type Y to confirm each transfer:

mput test.txt? Y
putting file test.txt as \test.txt (38.5 kb/s) (average 38.5 kb/s)
mput file1.txt? Y
putting file file1.txt as \file1.txt (0.0 kb/s) (average 19.2 kb/s)
mput file2.txt? Y
putting file file2.txt as \file2.txt (0.0 kb/s) (average 12.8 kb/s)
mput file3.txt? Y
putting file file3.txt as \file3.txt (0.0 kb/s) (average 9.6 kb/s)

If you want to transfer all files without confirmation, you can turn off prompting:

smb: \> prompt
smb: \> mput *.txt

Similarly, to download multiple files:

smb: \> lcd ~/project/smb-downloads
smb: \> mget *.txt

When you're done, exit the smbclient session:

smb: \> quit

Non-Interactive Commands

You can also use smbclient to execute commands without entering the interactive shell. For example, to list the contents of a share:

smbclient //localhost/testshare -U labex -c 'ls'

Enter the password when prompted, and you'll see the directory listing:

Enter WORKGROUP\labex's password:
  .                                   D        0  Tue Nov 30 12:03:00 2022
  ..                                  D        0  Tue Nov 30 12:00:00 2022
  file1.txt                           N        0  Tue Nov 30 12:03:00 2022
  file2.txt                           N        0  Tue Nov 30 12:03:00 2022
  file3.txt                           N        0  Tue Nov 30 12:03:00 2022
  shared-test.txt                     N       37  Tue Nov 30 12:00:00 2022
  test-directory                      D        0  Tue Nov 30 12:01:00 2022
  test.txt                            N       33  Tue Nov 30 12:03:00 2022

                8467839 blocks of size 4096. 3524491 blocks available

To download a file in a single command:

smbclient //localhost/testshare -U labex -c 'get test.txt /home/labex/project/test-download.txt'

This command downloads the test.txt file from the share and saves it as test-download.txt in your project directory.

You now have a good understanding of how to use smbclient to connect to SMB shares, navigate directories, and transfer files. These skills are essential when working in mixed Windows/Linux environments.

Summary

In this lab, we explored the smbclient command in Linux, which provides an essential tool for connecting Linux systems to Windows (SMB/CIFS) file shares. We covered several key aspects of working with smbclient:

  1. Installation: We installed the smbclient package on Ubuntu 22.04, which included its dependencies.

  2. Command Basics: We learned about the basic syntax and commands available in smbclient, including how to connect to shares and navigate within them.

  3. Setting Up a Test Environment: We created a test SMB environment using a local Samba server to practice our commands without requiring access to an external Windows server.

  4. Connecting to Shares: We connected to our test SMB share and explored navigation commands such as ls, cd, and mkdir.

  5. Transferring Files: We learned how to upload files to an SMB share using put and download files using get. We also explored multiple file transfers with mput and mget.

The skills you've gained from this lab are directly applicable to real-world scenarios where you need to interact with Windows systems or servers from Linux environments. Whether you're transferring files between systems, automating backups, or integrating Linux systems into Windows networks, smbclient provides a powerful command-line interface for these tasks.

For more complex or frequent file operations, you may want to explore mounting SMB shares directly into your Linux filesystem using the mount command with the cifs filesystem type, which builds upon the concepts we've learned here.

Linux Commands Cheat Sheet