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

#!/usr/bin/expect


if {$argc < 4} {
    #do something
    send_user "usage: $argv0    "
    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

你可能感兴趣的:(Others)