SMB Client Commands Through Shell Script

I worked out a solution to this, and sharing for future references.

#!/bin/bash
cd /home/username
smbclient //link/to/server$ password -W domain -U username << SMBCLIENTCOMMANDS
recurse
prompt
mput backupfiles
exit
SMBCLIENTCOMMANDS

This will enter the commands between the two SMBCLIENTCOMMANDS statements into the smb terminal.


smbclient accepts the -c flag for this purpose.

 -c|--command command string
       command string is a semicolon-separated list of commands to be executed instead of
       prompting from stdin.
       -N is implied by -c.

       This is particularly useful in scripts and for printing stdin to the server, e.g.
       -c 'print -'.

For instance, you might run

$ smbclient -N \\\\Remote\\archive -c 'put /results/test-20170504.xz test-20170504.xz'

smbclient disconnects when it is finished executing the commands.


I would take a different approach using autofs with smb. Then you can eliminate the smbclient/ftp like approach and refactor your shell script to use other functions like rsync to move your files around. This way your credentials aren't stored in the script itself as well. You can bury them somewhere on your fs and make it read only by root an no one else.

Tags:

Unix

Shell

Smb