期待重定向输出giberish

时间:2015-09-02 16:59:16

标签: bash redirect expect

我有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 ------

在执行脚本时输出到日志文件时如何摆脱额外的giberish?我在服务器和客户端都使用centos 7.1。 如果您有任何想法请帮助我。非常感谢你。

1 个答案:

答案 0 :(得分:0)

重写a但要解决几个问题:

  • expect有2个内置方法来获取当前日期时间:timestamp(特定于期望)和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"