繁体   English   中英

期望重定向输出适中

[英]expect redirect outputs giberish

我有backup.sh

#!/bin/bash
expect backup.exp

backup.exp

#!/usr/bin/expect -f
#exp_internal 1
#log_user 0
set timeout 29

puts "----------------- [exec date +%Y.%m.%d\ %H:%M:%S] ------ exp start -----"
spawn -noecho ssh andrej@10.11.22.17

expect {
  timeout { send_user "\n--- failed to get expected string---\n"; exit 1 }
  eof { send_user "\nSSH failure\n"; exit 1 }
  " andrej $ "
}    

send "sudo bash\r"
send "ls -lh\r"

send exit\r
send exit\r
interact

puts "----------------- [exec date +%Y.%m.%d\ %H:%M:%S] ------ exp ende ------"

当我跑步时

bash backup.sh >> backup.templog 2>&1

我懂了

----------------- 2015.09.02 18:48:29 ------ exp start -----
Last login: Wed Sep  2 18:48:24 2015 from 10.11.22.16
^[]0;andrej@centos7c:~/andrej^G^[[?1034h^[[01;32mandrej@centos7c ^[[01;34m18:48 andrej $ ^[[00msudo bash
^[]0;root@centos7c:/home/andrej/andrej^G^[[?1034h^[[01;31mroot@centos7c ^[[01;34m18:48 andrej $ ^[[00mls -lh
total 16K
-rw-rw-r--. 1 andrej andrej 13K Jun 30 19:04 iptables.sh
drwxrwxr-x. 2 andrej andrej   6 Jun 17 22:46 ^[[0m^[[01;34mmount^[[0m
^[]0;root@centos7c:/home/andrej/andrej^G^[[01;31mroot@centos7c ^[[01;34m18:48 andrej $ ^[[00mexit
exit
^[]0;andrej@centos7c:~/andrej^G^[[01;32mandrej@centos7c ^[[01;34m18:48 andrej $ ^[[00mexit
logout
Connection to 10.11.22.17 closed.
----------------- 2015.09.02 18:48:39 ------ exp ende ------   

但是当我这样做

bash backup.sh

,我得到了我需要的漂亮输出:

----------------- 2015.09.02 18:52:09 ------ exp start -----
Last login: Wed Sep  2 18:48:39 2015 from 10.11.22.16
andrej@centos7c 18:52 andrej $ sudo bash
root@centos7c 18:52 andrej $ ls -lh
total 16K
-rw-rw-r--. 1 andrej andrej 13K Jun 30 19:04 iptables.sh
drwxrwxr-x. 2 andrej andrej   6 Jun 17 22:46 mount
root@centos7c 18:52 andrej $ exit
exit
andrej@centos7c 18:52 andrej $ exit
logout
Connection to 10.11.22.17 closed.
----------------- 2015.09.02 18:52:20 ------ exp ende ------

在执行脚本时输出到日志文件时,如何摆脱多余的烦恼? 我在服务器和客户端中都使用centos 7.1。 如果您有任何建议,请帮助我。 非常感谢你。

改写了一个,但是解决了几个问题:

  • Expect具有2种内置方法来获取当前日期timestamptimestamp (特定于预期)和clock (来自Tcl)
  • 我关闭输出( log_user 0
  • 重要时,我会更改提示并使用锚定的正则表达式进行匹配
  • 我仅输出ls -lh命令的结果,我怀疑这是您的目标。
#!/usr/bin/expect -f
#exp_internal 1
set timeout 29

proc separator {msg} {
    puts [format "----------------- %s ------ %s -----" [timestamp -format "%Y.%m.%d %T"] $msg]
}

separator "exp start"

log_user 0

spawn -noecho ssh andrej@10.11.22.17

expect {
  timeout { send_user "\n--- failed to get expected string---\n"; exit 1 }
  eof { send_user "\nSSH failure\n"; exit 1 }
  " $ "
}    

send "sudo bash\r"
expect " $ "

send "PS1='$'\r"
expect -re {\$$}

send "ls -lh\r"
expect -re {(.+)\r\n\$$}

puts $expect_out(1,string)

send "exit\r"
expect " $ "

send "exit\r"
expect eof

separator "exp ende"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM