shell脚本中使用expect实现自动交互

需求:

每天凌晨监控远程服务器上指定目录下文件是否生成,已生成则拉取到本地服务器指定目录下

实现方案:

shell脚本实现,配置crontab定时任务。
shell脚本中sftp登录远程服务器时自动输入密码等操作需用用到expect语法,需安装expect
expect安装参考:https://blog.csdn.net/nichosx/article/details/89428259
#!/bin/bash
remote_ip="113.4.186.2"
remote_password="123456"
remote_user="test"
remote_file_dir="/home/test/hx_file"
local_file_dir="/home/weblogic/download/hx_file"

/usr/bin/expect << EOF
spawn sftp ${remote_user}@${remote_ip}
expect {
  "*(yes/no)?"
  {send "yes\r";exp_continue}
  "*password:"
  {send "${remote_password}\r"}
}
expect "sftp>"
send "cd ${remote_file_dir}\r"
expect "sftp>"
send "cd ${remote_file_dir}\r"
expect "sftp>"
send "lcd ${local_file_dir}\r"
expect "sftp>"
send "get *\r"
expect "sftp>"
send "exit\r"
EOF

echo "文件已下载"

expect安装:

posted @ 2024-08-01 11:29  EPIHPANY  阅读(93)  评论(0)    收藏  举报