#!/usr/bin/expect

本机A的IP地址

set local_ip "192.168.1.10"

远程服务器B的IP地址

set remote_ip "192.168.1.20"

远程服务器B的用户名和密码

set remote_user "username" set remote_password "password"

远程服务器B的目录

set remote_directory "/path/to/directory"

登录远程服务器B

spawn ssh $remote_user@$remote_ip expect { "(yes/no)?" { send "yes\n" exp_continue } "password:" { send "$remote_password\n" exp_continue } "$remote_user@*" { # 登录成功后执行命令 send "cd $remote_directory\n" send "tar -czvf backconf.tar.gz backconf\n" send "exit\n" } }

从远程服务器B下载文件

spawn scp $remote_user@$remote_ip:$remote_directory/backconf.tar.gz $local_ip:/path/to/save/ expect { "(yes/no)?" { send "yes\n" exp_continue } "password:" { send "$remote_password\n" exp_continue } eof }

解压文件

spawn tar -xzvf /path/to/save/backconf.tar.gz -C /path/to/extract/ expect eof

删除远程服务器B上的压缩文件

spawn ssh $remote_user@$remote_ip rm $remote_directory/backconf.tar.gz expect { "(yes/no)?" { send "yes\n" exp_continue } "password:" { send "$remote_password\n" exp_continue } eof