如何在 ssh 循环中使用 EXPECT

如何在 ssh 循环中使用 EXPECT

我们的 Linux 设置没有为无密码身份验证配置 keygen。因此我应该只EXPECT在 shell 脚本中使用无密码身份验证。

   /usr/bin/expect<<EOF >> ${LOG_FILE}

set timeout 60
spawn   sftp ${EWS_USER}@${EWS_HOST}:${TGT_DIR}
expect "*?assword:"
send "$password\r"
expect "sftp>"
send "put $local_dir/$line\r"
expect "sftp>"
send "bye\r"
expect EOF
EOF

        filename=$(basename "$line")
        # echo "File Name: $filename"
        #Calculate the MD5Sum locally.
        local_md5sum=$(md5sum "$line")
        #echo "Local MD5Sum: ${local_md5sum}"
        #Calculate the MD5sum in remote machine
        remote_md5sum=$(ssh ${EWS_USER}@${EWS_HOST} "cd '$TGT_DIR' ; find -name '$filename'  -exec md5sum {} \;" < /dev/null)
        #echo "Remote MD5Sum: ${remote_md5sum}"

LOCAL_SUM=`echo ${local_md5sum} | awk {'print $1'}`
REMOTE_SUM=`echo ${remote_md5sum} | awk {'print $1'}`
echo $LOCAL_SUM
echo $REMOTE_SUM
if [ "${LOCAL_SUM}" != "${REMOTE_SUM}" ]
then
        echo "SFTP Successfull"
else
        echo "SFTP Unsuccessfull"
fi

我知道如何EXPECT在以下场景中使用:

sftp ${EWS_USER}@${EWS_HOST} << EOF >> ${LOG_NAME}
put ${LOCAL_DIR}/${line} ${TGT_DIR}/${line}
EOF

但知道如何在下面的场景中使用 EXPECT 来使连接无密码吗?

remote_md5sum=$(ssh ${EWS_USER}@${EWS_HOST} "cd '$TGT_DIR' ; find -name '$filename'  -exec md5sum {} \;" < /dev/null)

答案1

expectfor 的使用ssh方式与 for 完全相同sftp,最复杂的部分是如何从输出中提取校验和。这可能会沿着以下方向运行

#!/usr/bin/env expect
#
# remote host sftp and then checksum a file. assumes linux coreutils
# available on both ends

if {[llength $argv] == 0} {
    puts stderr "Usage: $argv0 somefiletoxfer"
    exit 64
}

set local_file [lindex $argv 0]
set local_sum [lindex [split [exec md5sum $local_file] " "] 0]
set file_basename [lindex [split $local_file "/"] end]

set match_max 9999    ;# in the event of much output spam from sftp or ssh
set timeout 60

# these could also be read from $argv
set EWS_USER todofixme
set EWS_HOST todofixme
set TGT_DIR todofixme

set password hunter2

spawn sftp ${EWS_USER}@${EWS_HOST}:${TGT_DIR}
expect -ex "assword:"
send "$password\r"
expect -ex "sftp>"
send "put $local_file\r"
expect -ex "sftp>"
send "bye\r"
expect EOF

spawn ssh ${EWS_USER}@${EWS_HOST}
expect -ex "assword:"
send "$password\r"
send "md5sum ${TGT_DIR}/$file_basename\r"
expect -re {md5sum [^\n]+\n([A-Za-z0-9=_-]+) }
set remote_sum $expect_out(1,string)
send "exit\r"
expect EOF

if {$local_sum ne $remote_sum} {
    puts stderr "a failure prompts this dispatch" 
    puts stderr "for thy checksums do mismatch"
    puts stderr "local  >$local_sum<"
    puts stderr "remote >$remote_sum<"
    exit 1
}

puts $remote_sum
exit 0

相关内容