为什么我的期望脚本中会出现单引号和意外行为?

时间:2017-02-13 03:22:28

标签: expect

我正在尝试编写一个脚本,将sftp文件发送到我的亚马逊开发者帐户。这是脚本:

#!/usr/bin/expect --
#
#
set timeout -1
#log_user 1

if {[llength $argv] < 3 } {
        puts "usage: sftp-to-amazon.exp <APPCODE> <APPNAME> <SFTP_USER>"
        puts ""
        puts "This script will sftp binary files to the amazon sftp server for the given APPCODE."
        puts "and APPNAME.  APPNAME is like Dragnet_AMZ_1951_V4."
        puts "You can get the APPCODE from the Amazon Developers Console."
        exit 1
}

set appcode [lindex $argv 0]
set appname [lindex $argv 1]
set sftp_user [lindex $argv 2]


puts "App code is $appcode app name is $appname sftp_user is $sftp_user"

stty -echo
send_user "Enter password for $sftp_user: "
expect_user -re "(.*)\n"
set sftp_pass $expect_out(1,string)

set sftp_host 'dar.amazon-digital-ftp.com'

puts "/usr/bin/sftp -o 'StrictHostKeyChecking no' ${sftp_user}@${sftp_host}"
if [ catch "spawn /usr/bin/sftp -o 'StrictHostKeyChecking no' $sftp_user@$sftp_host" reason ] {
        puts "failed to spawn line 115 /usr/bin/sftp $sftp_user@$sftp_host : $reason\n"
        set success 0
        exit 1
}
expect  -re "$sftp_user@$sftp_host's password: $" {
        puts "Sending password"
        send "$sftp_pass\r"
}

puts "Script complete."

当我运行脚本时,我得到了这个输出:

$ ./sftp-to-amazon.exp M1S3R61WOY9B0 ONETWO VM3H65THINGBATFA7
App code is M1S3R61WOY9B0 app name is ONETWO sftp_user is VM3H65THINGBATFA7
Enter password for VM3H65THINGBATFA7: /usr/bin/sftp -o 'StrictHostKeyChecking no' VM3H65THINGBATFA7@'dar.amazon-digital-ftp.com'
spawn /usr/bin/sftp -o 'StrictHostKeyChecking no' VM3H65THINGBATFA7@'dar.amazon-digital-ftp.com'
command-line: line 0: Bad configuration option: 'stricthostkeychecking
Couldn't read packet: Connection reset by peer
Script complete.

当我跑...

/usr/bin/sftp -o 'StrictHostKeyChecking no' VM3H65THINGBATFA7@'dar.amazon-digital-ftp.com'

...从命令行自行运行它可以正常工作。

1 个答案:

答案 0 :(得分:1)

因为单引号在expect(Tcl)中没有特殊含义。

if [ catch "spawn /usr/bin/sftp -o 'StrictHostKeyChecking no' $sftp_user@$sftp_host" reason ] {
#                                  ^..................... ..^
#                                  two separate words with literal quote chars

Tcl相当于shell的单引号是花括号。你需要

if [ catch "spawn /usr/bin/sftp -o {StrictHostKeyChecking no} $sftp_user@$sftp_host" reason ] {
#                                  ^........................^
#                                  one word