Shell脚本:人机交互脚本-scp


前面两篇博文中,为大家演示了shell脚本中sussh命令的免验证输入实现:

http://blog.csdn.net/hanlizhong85/article/details/74089997

http://blog.csdn.net/hanlizhong85/article/details/71055940

本文将进一步演示,通过expect工具实现scp命令免密输入的方法。

 

Expect开源软件安装,请参考:

http://blog.csdn.net/hanlizhong85/article/details/71038532

 

scp.sh脚本实现

脚本实现功能:实现远程主机与本地主机之间的文件拷贝,脚本有6个入参:

1个参数:标识远端用户名;

2个参数:标识远端用户名对应的密码;

3个参数:远端主机IP地址;

4个参数:源文件或目录;

5个参数:目的文件或目录;

6个参数:拷贝类型,0标识从远端拷贝数据到本地,为其他值标识从本地拷贝数据到远端。

############################################################

#!/bin/bash

#Createby hanlizhong on 2013.08.10

 

#The first three parameters represent remote host info.

USERNAME=$1

PASSWD=$2

HOSTIP=$3

SRC_FILE=$4

DST_FILE=$5

#TYPE:0--copy remote data to local; other--copy local data to remote

TYPE=$6

 

if [ -z${USERNAME} ] || [ -z ${PASSWD} ] || [ -z ${HOSTIP} ] ||\

 [ -z ${SRC_FILE} ] || [ -z ${DST_FILE} ] || [-z ${TYPE} ]; then

        echo "Input error!"

        exit 1

fi

 

if [${TYPE} == 0 ]; then

        #Here, ${SRC_FILE}must be absolute path.

        CMD_PARA="${USERNAME}@${HOSTIP}:${SRC_FILE}${DST_FILE}"

else

        #Here, ${DST_FILE}must be absolute path.

        CMD_PARA="${SRC_FILE}${USERNAME}@${HOSTIP}:${DST_FILE}"

fi

 

expect -c"

        spawn scp -r ${CMD_PARA}

        expect {

                  "*\(yes/no\)?" {send "yes\\r"; exp_continue }

                  "*password:" { send"${PASSWD}\\r" }

        }

        expect eof

"

############################################################

执行结果:

[root@HLZhanlzh]# ./scp.sh root root "192.168.242.128""/home/hanlzh/log.txt" "/home" 0

spawn scp-r root@192.168.242.128:/home/hanlzh/log.txt /home

root@192.168.242.128'spassword:

log.txt                                                                                                                              100%   0    0.0KB/s  00:00   

[root@HLZhanlzh]#

 


版权声明:本文为hanlizhong85原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。