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

The Geek Diary

CONCEPTS | BASICS | HOWTO

  • OS
    • Linux
    • CentOS/RHEL
    • Solaris
    • Oracle Linux
    • Linux Services
    • VCS
  • Database
    • oracle
    • oracle 12c
    • ASM
    • mysql
    • MariaDB
    • Data Guard
  • DevOps
    • Docker
    • Shell Scripting
  • Interview Questions
  • 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. “comm” Command in Linux with Examples
  2. How to Change the Default Timeout Settings for Telnet Session in CentOS/RHEL
  3. How to list all modules and check if they are enabled or disabled in CentOS/RHEL 8
  4. What is the difference between the -i and -U options used in rpm command in Linux
  5. Linux OS Service ‘ldap’
  6. Installing CentOS / RHEL 7 (step by step with screen shots)
  7. Beginners guide to vi editor (command line reference)
  8. How to install and Configure VNC (TigerVNC) server in CentOS / RHEL 7
  9. Common Error Messages from Command xfs_repair in Linux
  10. How to make ethtool settings persistent across reboots in CentOS / RHEL 6,7

You May Also Like

Primary Sidebar

Recent Posts

  • Failed to start LSB: Bring up/down networking – On restarting network service CentOS/RHEL (DHCP client)
  • How To Add Timestamps To dmesg Kernel Boot Log in CentOS/RHEL
  • How to disable ICMP redirects on CentOS/RHEL
  • What are Oracle Key Vault Roles
  • Archives
  • Contact Us
  • Copyright

© 2021 · The Geek Diary