IPython: 如何有选择性且安全地清除IPython的历史记录?

48

我一直在学习如何使用paramiko包,结果发现我所有的密码都是明文存储在IPython的%hist中。这不太好。

因此,我需要摆脱%hist中特定部分的内容。话虽如此,我并不想清空整个历史记录。只需删除我不小心输入password =或类似选定术语的部分即可。

谢谢


我不需要的评论:

  • %clear仅清除会话,而不会清除历史记录。
  • 是的。我以后只会使用xSA_keys。

7
请注意,如果您只想删除所有内容,可以使用“ipython历史记录清除”命令清除整个历史记录。 - Wilfred Hughes
6个回答

53

默认情况下,历史记录存储在$(ipython locate)/profile_default/history.sqlite中。您可以删除该文件或对其进行任何操作(安全擦除等)。它是一个sqlite文件,因此您可以使用任何sqlite程序加载它并对其进行查询。

请检查$(ipython locate)/profile_default/和其他$(ipython locate)/profile_xxx,确保您没有任何其他历史记录文件。$(ipython locate)通常为~/.ipython/,但可能会有所不同:

ls $(ipython locate)/profile_*/*.sqlite

哦,$(ipython locate)给了我[TerminalIPythonApp] File not found: u'locate'这个错误,但我可以在~/.ipython/profile_default/history.sqlite.找到它。 - mlissner
对于Windows用户:C:\Users<user>.ipython\profile_default\history.sqlite 此外,如果您没有SQLite客户端,我强烈推荐一个名为“DB Browser for SQLite”的图形化工具。 - sscalvo
只是为了双重确认:这个历史记录是本地机器上的,而不是存储在笔记本内部的,对吗?我有一个笔记本,从中删除了解决方案,如果我分享笔记本,包含解决方案的历史记录将无法恢复,是吗?谢谢! - PatrickT

29

一个解决方案是:

sqlite ~/.ipython/profile_default/history.sqlite

delete from history where source like '%password =%';

4
如果你这样做了,之后你可能希望删除~/.sqlite_history中的sqlite3历史记录。 - Matthew D. Scholefield

9
如果您想从特定会话中删除历史记录,请运行以下命令:
sqlite ~/.ipython/profile_default/history.sqlite

请注意,在某些系统上,您需要运行sqlite3而不是sqlite
SQLite内部:
select * from history;
# session is the first column in history
delete from history where session=XXX;

此外,这里有一条SQLite查询语句可以给出您上一个会话的ID:
select session from history order by -session limit 1;

6

结合@Ovidiu Ghinet答案@Matt被接受的答案:

sqlite $(ipython locate)/profile_*/*.sqlite || sqlite3 $(ipython locate)/profile_*/*.sqlite

然后在sqlite控制台中执行以下命令:

delete from history where source like '%password%';
select * from history; /* confirm that no passwords left        */
.quit                  /* forgot how to exit sqlite console? ;) */

1
我找不到有选择性地清除IPython历史记录的方法,但是我发现可以通过内置函数以非SQLite方式清除数据:

%clear out #它会清除输出历史记录

顺便说一下,你也可以通过 %clear in 清除输入历史记录。


0
如果你想从头开始,只需手动删除以下文件(这对我有用)。

/home/user/.ipython/profile_default/history.sqlite


这不是选择性删除,您会失去所有历史记录中的好东西。 - Ovidiu Ghinet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接