编写一个shell脚本本机A使用expect远程登录远端服务器B然后传输远端服务器B某个目录下的包含backconf文件或文件夹到本机Assh客户端未设置 免密登录
#!/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
AI 优化版
原文地址:https://www.cveoy.top/t/topic/gdqW 著作权归作者所有。请勿转载和采集!