scp shell脚本无需密码输入

scp 以及其他需要交换命令的工具在脚本中要实现智能化就会有问题,这些可以用 expect 来解决

先看一个 expect 例子的小应用,顾名思义,except 可以根据 stdout 来匹配,一旦匹配上了,就可以输入自己的命令。比如

expect -c 'expect "\n" {send "press ENTER"}'


expect 就会等待你的输入,一旦你的输入是回车,那么就会打印"ENTER"
查看下面脚本,可以传输本地的目录到远程节点目录,而不需要交互输入密码。
#!/bin/bash

# Function : transfer directory from localhost to remote node
# args 		 : ip password local_dir remote_dir
# Author   : firefoxbug
# Date     : 2013/06/25

if [ $# -ne 4 ]
then
	echo "[ERROR] usage : ./send_dir ip password source_dir dst_dir"
	exit 1
fi
ip=$1
port="22"
passwd=$2
local_dir=$3
remote_dir=$4

/bin/rpm -qa|/bin/grep -q expect
if [ $? -ne 0 ];then
	echo "please install expect"
	exit
fi

expect -c "
	spawn scp -r -P $port $local_dir root@$ip:$remote_dir
	expect {
		\"*assword\" {set timeout 300; send \"$passwd\r\";}
		\"yes/no\" {send \"yes\r\"; exp_continue;}
	}
	expect eof"

脚本执行

./send_dir ip password source_dir dst_dir

对于普通的 ssh ,返回下面的结果

[root@firefoxbug volcano]# ssh 223.4.238.138
reverse mapping checking getaddrinfo for ip223.hichina.com [223.4.238.138] failed - POSSIBLE BREAK-IN ATTEMPT!
root@223.4.238.138's password:

如果未经验证则返回下面结果。
[root@firefoxbug volcano]# ssh 223.4.238.138
The authenticity of host '223.4.238.138 (223.4.238.138)' can't be established.
RSA key fingerprint is 7b:e5:f3:61:07:01:93:2c:01:6c:2e:77:39:88:a5:bb.
Are you sure you want to continue connecting (yes/no)?

expect 就能根据正则匹配来自动输入。

标签:Linux, Shell