如何获取命令和输出登录shell?

时间:2015-04-09 22:00:54

标签: bash shell

我们需要记录命令及其输出。例如,如果我运行以下命令。我需要将其记录到文本文件中。

cat script.sh
find / -name sshd_config -print
/etc/ssh/sshd_config

cat log.out - 应该如下所示

<server_name>$ find / -name sshd_config -print
/etc/ssh/sshd_config

如果我在脚本中使用set-x,我可以记录命令,但它提供了太多信息。是否有其他方法可以在脚本中使用?

2 个答案:

答案 0 :(得分:1)

我很好奇并且跟进:这是一个expect脚本,它使shell脚本看起来像是交互式的:

#!/usr/bin/env expect

set script [lindex $argv 0]
if { ! [file readable $script]} {
    error "cannot read $script"
}

set fid [open $script r]
set lines [split [read -nonewline $fid] \n]
close $fid

set shebang [lindex $lines 0]
if {[string match {#!*} $shebang]} {
    spawn -noecho {*}[string range $shebang 2 end]
} else {
    spawn -noecho $env(SHELL)
}

foreach line $lines { 
    # skip blank lines
    if {[string trim $line] eq ""} continue
    # skip comments
    if {[string match {#*} [string trim $line]]} continue
    send -- "$line\r" 
}

# send Ctrl-D to end shell session
send -- \x04
expect eof

保存为interactivize,然后:

$ cat test.sh
date
getent passwd $USER
echo Hello World
$ interactivize test.sh
date
getent passwd $USER
echo Hello World
[myprompt]$ date
Thu Apr  9 18:29:31 EDT 2015
[myprompt]$ getent passwd $USER
jackman:x:1001:1001:Glenn Jackman:/home/jackman:/usr/local/bin/fish
[myprompt]$ echo Hello World
Hello World
[myprompt]$ exit
exit

答案 1 :(得分:0)

如果您需要进行安全审核,我会查看GateOne

它支持完整录制命令和输出,有关简短演示,请参阅:https://youtu.be/gnVohdlZXVY?t=3m13s

相关问题