如何使用 expect 实用程序自动传输 sftp 文件

我们始终可以配置无密码 ssh,以便使用 sftp 传输文件而无需用户输入密码。
但是,如果不允许配置无密码 ssh,则有一种方法可以自动传输 sftp 文件。
它可以通过使用 tcl shell 提供的“expect”命令来实现。

为了使 expect 实用程序起作用,我们需要安装“expect”包。
为此,请使用以下命令:

# yum install expect

下面是使用批处理文件自动进行远程访问的示例脚本。

#!/bin/bash
if (( $# < 3 )); then
    echo "Usage: 
spawn - to initiate the sftp process
expect - it expects a particular string ( here it is "password:" prompt )
send - sends the password when the expect utility gets the required prompt.
[remote addr] [password] [batch file]" echo echo -e "tremote addr : [loginid]:[host addr]n" exit fi REMOTE= PASS= BATCH= expect -c " spawn sftp -o "batchmode no" -b "$BATCH" $REMOTE expect -nocase "password:" {send "$PASSr"; interact} "

其中:

# bash ./test.sh root@remote.example.com password testjob.bat

这是一个示例,如何在以 root 用户身份使用密码“password”登录后运行在 remote.example.com 上运行 testjob.bat 中的命令的脚本

##代码##
日期:2020-09-17 00:13:08 来源:oir作者:oir