SSH+EXPECT远程执行命令及本地保存结果

#!/usr/bin/expect


if {$argc < 4} {
    #do something
    send_user "usage: $argv0 <remote_host> <remote_port> <remote_user> <remote_pwd>"
    exit
}


set timeout 15 


set remote_host [lindex $argv 0] 
set remote_port [lindex $argv 1]
set remote_user [lindex $argv 2]
set remote_pwd  [lindex $argv 3]
set cmd_prompt "]#|~]?"


#开启进程,执行ssh
spawn ssh -p ${remote_port} ${remote_user}@${remote_host}


expect {
   -re "Permission denied, please try again." {
     send_user "Error:Permission denied.\n"
     exit
   }
   -re "Connection refused" {
     send_user "Error:Connection refused.\n"
     exit
   }
   timeout {
     exit
   }
   eof {
     exit
   }
   -re "Are you sure you want to continue connecting (yes/no)?" {
     send "yes\r"
     exp_continue
   }
   -re "assword:" {
     send "$remote_pwd\r"
     exp_continue
   }
   -re $cmd_prompt {
     send "\r"
   }
}


#设置保存的文件名及打开文件
set ofile "info_$remote_host"
set output [open $ofile "w"]
#expect -re $cmd_prompt { send "ls -ltr /tmp\r" }
#output cpu load
expect -re $cmd_prompt {
  #执行远程命令
  send {top -bn1|grep load|awk '{printf "cpu:%.2f%%\n", $(NF-2)}'}
  send "\r"
  #对结果进行正则匹配并进行捕获并保存到变量
  expect -re "\r\n(.*)\r\n(.*)$cmd_prompt"
  set outcome $expect_out(1,string)
  #驱动下一个expect匹配,如果没有则停在命令提示符
  send "\r"
  #将结果保存到文件
  puts $output $outcome
}


#output memory
expect -re $cmd_prompt {
  send {free -m | awk 'NR==2{printf "mem:%d,%d\n", $3,$2}'}
  send "\r"

  expect -re "\r\n(.*)\r\n(.*)$cmd_prompt"
  set outcome $expect_out(1,string)
  send "\r"
  puts $output $outcome
}


#output disk
expect -re $cmd_prompt {
  send {df -h | awk '$NF=="/"{printf "disk:%s,%s\n", $3, $2}'}
  send "\r"

  expect -re "\r\n(.*)\r\n(.*)$cmd_prompt"
  set outcome $expect_out(1,string)
  send "\r"
  puts $output $outcome
}


#关闭文件
close $output


expect {
  -re $cmd_prompt {
    send "exit\r"
  }
}


expect eof

expect输出结果正则匹配捕获时的注意点:

----------------------------
normal unix command
----------------------------
server $ ls -ltr
output
.
.
.
output
server $

----------------------------
expect script
----------------------------
server $ ls -ltr\r
\n
output(.*)
.
.
.

output\r

\n

server(.*) $

expect文档:https://linux.die.net/man/1/expect

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值