Wednesday, January 1, 2014

automate unix scp command in shell scripts : password less scp with expect shell command

expect is a unix shell command.
This is like a separate shell, as we use it as shebang in the shell script.

you can check the presence of this command by:
which expect

As you know, scp (secury copy) is a tool to copy files/directories from one host to another.

syntax of scp:

scp user@source_host:source_file_path user@destination_host:destination_file_path

(as you know, you can avoid corresponding user/host, if the source/destination host is localhost)

this prompts user to enter the password.

few ways to avoid entering password for scp:
1. generate public/private keys and export them to the required host
2. use expect command

you can get links for first method by google'ng. Here I am going to describe the second method.

script for password less scp with expect command:

#!/usr/bin/expect

# use the scp command
spawn scp <user>@<source_host>:<source_file_path> <user>@<destination_host>:<destination_file_path>

# use the expect to answer the prompts
# we are providing inputs to two propts
# 1. answer for "do you realy want to connect to this host: (yes/no)?"
# 2. "enter password"

expect {
  -re ".*es.*o.*" {
    exp_send "yes\r"
    exp_continue
  }
  -re ".*assword.*" {
    exp_send "<your_password>\r"
  }
}
interact



Note: Please change the following accordingly in the above script:
<user>, <source_host>, <source_file_path>, <destination_host>, <destination_file_path>, <your_password>

No comments:

Post a Comment