酆都城主

博客园 首页 联系 订阅 管理

运维一段时间的内网服务器,每次需要远程传输文件时,就需要输入服务器的密码,很是麻烦,就结合expect自己写了个脚本。

1、expect

expect是一种自动交互语言,能实现在shell脚本中为scp和ssh等自动输入密码自动登录

源码安装参考Linux expect源码安装 

 2、expect 结合scp脚本实现实例

 1 #!/bin/expect -d
 2         set timeout 20
 3         set file_name_expect [lindex $argv 0]
 4         puts $file_name_expect
 5         spawn scp  $file_name_expect   root@192.168.4.12:/usr/local/tmp
 6         expect {
 7                 "yes/no" {  #Are you sure you want to continue connecting (yes/no)?
 8                         send "yes\n"
 9                         expect "password" { send "123456\n" }  #root@192.168.4.12's password
10                         }
11                 "password" {  send "123456\n"  }
12 
13                 }
14 expect eof
15 exit

 

 第1行使用expect来解释执行脚本(路径根据自己安装的路径修改)  -d 显示调试信息

第2行设置超时时间,默认是10秒。10秒后没有expect内容出现退出

第3行从命令行中获取参数值并赋值

第4行输出打印

第5行spawn是进入expect环境后才可以执行的expect内部命令,主要的功能是给ssh运行进程加个壳,用来传递交互指令。

第6~13行 从进程接收字符串, 根据匹配(expect)到的字符串"yes/no","password",向交互界面发送(send)信息

posted on 2020-08-24 16:45  酆都城主  阅读(1206)  评论(0编辑  收藏  举报