• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer navigation

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • Solaris
    • Oracle Linux
    • VCS
  • Interview Questions
  • Database
    • oracle
    • oracle 12c
    • ASM
    • mysql
    • MariaDB
  • DevOps
    • Docker
    • Shell Scripting
  • Big Data
    • Hadoop
    • Cloudera
    • Hortonworks HDP

How to automate sftp file transfers using expect utility

by admin

You can always configure passwordless ssh in order to transfer files using sftp without user being asked for a password. But if its not allowed to configure a passswordless ssh, there is a way to automate sftp file transfers. It can be achieved by using ‘expect‘ command provided by the tcl shell.

For the expect utility to work we need to install the “expect” package. To do so use the below command :

# yum install expect

Below is an example script that automates remote access with a batch file.

#!/bin/bash

if (( $# < 3 )); then
    echo "Usage: $0 [remote addr] [password] [batch file]"
    echo
    echo -e "tremote addr : [loginid]:[host addr]n"
    exit
fi

REMOTE=$1
PASS=$2
BATCH=$3
expect -c "
spawn sftp -o "batchmode no" -b "$BATCH" $REMOTE
expect -nocase "password:" {send "$PASSr"; interact}
"

Here,

spawn - to initiate the sftp process
expect - it expects a particular string ( here it is "password:" prompt )
send - sends the password when the expect utility gets the required prompt.

Here's an example how to run the script which run the commands in testjob.bat on remote.example.com after log in as root with a password 'password'

# bash ./test.sh root@remote.example.com password testjob.bat

Filed Under: Linux

Some more articles you might also be interested in …

  1. CentOS / RHEL : How to configure vsftpd to use ports other than the default ports 20 and 21
  2. Wallch (Wallpaper Changer) – Rotate Ubuntu Desktop Wallpapers
  3. CentOS / RHEL 7 : How to configure kdump
  4. CentOS / RHEL : How to exclude kernel or other packages from getting updated using YUM Versionlock Plugin
  5. findmnt: command not found
  6. Understanding the /etc/fstab file in Linux
  7. How to Change Default Port of Apache On RHEL/CentOS 7
  8. Linux OS Service ‘anacron’
  9. How to disable timeout in ssh during login prompt (login session inactivity) in Linux
  10. Rpm: Error While Loading Shared Libraries: Libz.so.1: Cannot Open Shared Object File: No Such File

You May Also Like

Primary Sidebar

Recent Posts

  • fprintd-delete Command Examples in Linux
  • fprintd-delete: command not found
  • foreman: command not found
  • foreman Command Examples in Linux

© 2023 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright