2013-07-02 109 views
0

以前我写过一个脚本,它将以前访问过的目录记录到sqlite3数据库中。我写了一些快捷方式来快速搜索和浏览历史。现在我正在考虑用我的bash命令做同样的事情。在数据库中记录bash历史记录

当我在bash中执行命令时,如何获得命令名?我是否必须更改bash的源代码中负责编写bash-history的部分?一旦我有我的命令历史数据库,我可以在其中进行智能搜索。

+1

不太清楚bash的内置历史是什么,但如果你真的想要这个,切换到zsh,你可以拥有更多的权力和控制权。 – Kevin

回答

2

Bash已经将您的所有命令记录到纯文本文件〜/ .bash_history中。

使用上/下箭头浏览内容,或按control-r进行搜索。

+0

原问题的作者提到。 – daveloyall

1

fc请看:

FC:FC [-e参数] [-lnr] [第一] [最后]或FC -s ​​[PAT =代表] [命令] 显示或执行来自历史列表的命令。

fc is used to list or edit and re-execute commands from the history list. 
FIRST and LAST can be numbers specifying the range, or FIRST can be a 
string, which means the most recent command beginning with that 
string. 

Options: 
    -e ENAME select which editor to use. Default is FCEDIT, then EDITOR, 
     then vi 
    -l list lines instead of editing 
    -n omit line numbers when listing 
    -r reverse the order of the lines (newest listed first) 

With the `fc -s [pat=rep ...] [command]' format, COMMAND is 
re-executed after the substitution OLD=NEW is performed. 

A useful alias to use with this is r='fc -s', so that typing `r cc' 
runs the last command beginning with `cc' and typing `r' re-executes 
the last command. 

Exit Status: 
Returns success or status of executed command; non-zero if an error occurs. 

你可以调用它去插入到表中的文本,但为什么,如果它已经被Bash保存烦恼呢?使用

$ history > history.log 

或冲洗历史(因为它是被保持在由BASH存储器)::

0

为了得到完整的历史或者使用历史命令和处理其输出

$ history -a 

然后过程〜/ .bash_history

1

对不起,这么晚来到这个问题!

我倾向于在我工作的地方运行很多shell,结果长时间运行的shell历史记录会一直混合或丢失。我终于受够了,我开始记录到数据库:)

我还没有完全制定出整合,但这里是我的设置:

  1. 重新编译的bash与SYSLOG功能。由于bash版本4.1这个代码全部到位,它只需要在config-top.h中启用,我相信。
  2. 安装新的bash并配置您的系统日志客户端以记录user.info消息
  3. 安装rsyslog和rsyslog-pgsql插件以及postgresql。我遇到了一些问题,如果遇到问题或在这里问问,可以在debian测试PM中安装它:)
  4. 配置用户消息以馈入数据库。

在所有这些命令的结尾,所有的命令都应该被记录到名为systemevents的表中。你一定会想建立的索引上几个字段,如果你经常使用shell作为查询可以开始采取永远:)

这里有几个指标的我设置:

指标: “systemevents_pkey” PRIMARY KEY,B树(ID) “systemevents_devicereportedtime_idx” B树(devicereportedtime) “systemevents_fromhost_idx” 散列(fromhost) “systemevents_priority_idx” B树(优先级) “systemevents_receivedat_idx” B树(receivedat)

fromhost,receivedat ,和德维cereportedtime特别有帮助!

从短短的一段时间我一直在使用它,这真是太神奇了。它让我能够在最近的任何服务器上找到命令!不要再失去一个命令!如果您有多个用户,也可以将它与停机时间/其他问题关联起来。

我正计划编写我自己的rsyslog插件,以使数据库中的历史记录格式更加有用。我更新时,当我:)

祝你好运!

1

您可以使用Advanced Shell History工具将您的shell历史写入sqlite3,并使用提供的ash_query工具从命令行查询数据库。

[email protected]:~$ ash_query -Q 
Query Description 
CWD  Shows the history for the current working directory only. 
DEMO  Shows who did what, where and when (not WHY). 
ME  Select the history for just the current session. 
RCWD  Shows the history rooted at the current working directory. 

您可以编写自己的自定义查询,并使其可从命令行使用。

这个工具给你很多的额外的历史信息之外的命令 - 你退出代码,开始和停止时间,当前的工作目录,TTY等

充分披露 - 我是作者和维护者。