Перейти к содержимому

Bash history где лежит

  • автор:

История команд Linux

В терминале Linux, кроме всего прочего, есть одна замечательная вещь. Это история команд Linux. Все команды, которые вы вводите во время работы сохраняются и вы можете найти и посмотреть их в любой момент. Также можете вернуться на несколько команд чтобы не набирать недавно выполненную команду заново.

В этой небольшой статье мы рассмотрим как пользоваться историей команд Linux, как ее настроить, а также рассмотрим полезные приемы, которые могут помочь вам в работе.

История команд Linux

Большинство задач, связанных с историей команд, мы будем выполнять либо с помощью команды history, либо с помощью оболочки. В истории хранится последняя 1000 команд, которые вы выполняли. Чтобы посмотреть всю историю для этого терминала просто запустите команду history без параметров:

Для дополнительных действий с историей вам могут понадобиться опции. Команда history linux имеет очень простой синтаксис:

$ history опции файл

В качестве файла можно указать файл истории. По умолчанию история для текущего пользователя хранится в файле

/.history, но вы можете задать, например, файл другого пользователя. А теперь рассмотрим опции:

  • -c — очистить историю;
  • -d — удалить определенную строку из истории;
  • -a — добавить новую команду в историю;
  • -n — скопировать команды из файла истории в текущий список;
  • -w — перезаписать содержимое одного файла истории в другой, заменяя повторяющиеся вхождения.

Наиболее полезной для нас из всего этого будет опция -c, которая позволяет очистить историю команд linux:

Так вы можете посмотреть только последние 10 команд:

А с помощью опции -d удалить ненужное, например, удалить команду под номером 1007:

Если вы хотите выполнить поиск по истории bash, можно использовать фильтр grep. Например, найдем все команды zypper:

history | grep zypper

На самом деле работать с историей еще более просто с помощью оболочки, возможно, вы уже используете многие ее функции, но о некоторых точно не знаете. Рассмотрим их:

Чтобы показать предыдущую команду просто нажмите стрелку вверх, так можно просмотреть список раньше выполненных команд.

Вы можете выполнить последнюю команду просто набрав «!!». Также можно выполнить одну из предыдущих команд указав ее номер «!-2»

Чтобы выполнить поиск по истории прямо во время ввода нажмите Ctrl+R и начните вводить начало команды.

Если вы знаете, что нужная команда была последней, которая начиналась на определенные символы, например, l, то вы можете ее выполнить, дописав «!l»:

Если нужная команда последняя содержала определенное слово, например, tmp, то вы можете ее найти, использовав «!?tmp»:

Если вы не хотите, чтобы выполняемая команда сохранилась в истории просто поставьте перед ней пробел.

Таким образом, вы можете очень быстро отыскать нужную команду, если помните как она была написана. История команд bash хранит очень много команд и этого вполне достаточно для комфортной работы.

Настройка истории Linux

Linux — очень настраиваемая и гибкая система, поэтому настроить здесь можно все, в том числе и историю. По умолчанию выводится только номер команды, но вы можете выводить и ее дату. Для этого нужно экспортировать переменную HISTORYFORMAT вместе нужным форматом:

export HISTTIMEFORMAT=’%F %T ‘ $ history

Для форматирования можно использовать такие модификаторы:

  • %d – день;
  • %m – месяц;
  • %y – год;
  • %T – штамп времени;
  • %F — штамп даты.

Вы можете указать какие команды не стоит отображать, например, не будем выводить ls -l, pwd и date:

export HISTIGNORE=’ls -l:pwd:date:’

Также можно отключить вывод одинаковых команд:

Существует два флага, ignoredups и ignorespace. Второй указывает, что нужно игнорировать команды, начинающиеся с пробела. Если вы хотите установить оба значения, используйте флаг ignoreboth. Используйте переменную HISTSIZE, чтобы установить размер истории:

По умолчанию история сохраняется для каждого терминала отдельно. Но если вы хотите чтобы все ваши команды немедленно синхронизировались между всеми терминалами, то это очень просто настроить. Добавьте такую переменную:

export PROMPT_COMMAND=»$history -a; history -c; history -r;»

Для тестирования работы вы можете набирать эти команды прямо в терминале и сразу видеть результат, но для сохранения добавьте нужные строки в ваш

export PROMPT_COMMAND=»$history -a; history -c; history -r;» $ export HISTCONTROL=ignoredups $ export HISTTIMEFORMAT=’%F %T ‘

Готово, теперь осталось сохранить изменения и перезапустить ваши терминалы. Теперь ваша история будет выводить дату, игнорировать дубли и синхронизироваться между терминалами.

Выводы

В этой статье мы рассмотрели что такое история команд linux, как с ней работать, как применяется команда history linux и какие настройки можно использовать для более комфортной работы. Если у вас остались вопросы, спрашивайте в комментариях!

Torvalds Tuesday: Bash History

For today’s post on Linux artifacts, I’m going to zero in on bash history. I’ll just begin by saying if you spend a lot of time analyzing Windows hosts, bash history will seem like a blessing. Only for a moment, and then it’s gone when you realize the downfall to bash history. That being said, bash history is an important artifact that deserves is own focus as it can help detail so much about our attackers.

For the purposes of this post, I’m doing analysis on a Debian 8.5 VM I have. Your miles may vary as I, for one example, rely on package manager-specific logs. This does not exclude other distributions, it just means the artifacts may be different. Other examples should also work well and may not depend on the type of Linux distribution.

Bash history, or the GNU History library, keeps track of commands issued by the user line-by-line. History has made it relatively simply to repeat commands, change arguments for a previous command, or recall previous commands to quick fix errors (I’m paraphrasing much from the man page of history).

Bash history is read when the shell starts, and is written at exit — generally. Despite the simplicity of being a history of lines from a shell, it’s behavior can be customized. Bash has quite a few environment variables that can achieve this. A few key variables include:

  • HISTCONTROL — A colon-separated list of values controlling how commands are saved on the history list.
  • HISTFILE — The name of the file in which command history is saved; again, the default for this value is

There are other options available. I’d highly recommend checking out man bash on a test system to learn how variables can manipulate history files. If you find yourself performing live analysis on a system, I recommend dumping environment variables to see if the history file is being manipulated at all.

Do You Have the Time?

As I’ve alluded to, bash history contains one downfall. Timestamps are not included in bash history by default. However, this is easily solved! You can set a time format using the environment variable HOSTTIMEFORMAT and will find timestamps appended. See the screenshot below:

Now, before we throw a party that bash includes timestamps, do you notice any issues with the timestamps above? That’s right, every command prior to the most recent session gets marked with the same timestamp. The takeaway here is that enabling timestamps on bash history is not much of a retrospective step; more of a proactive step.

I’d highly recommend checking out Hal Pomeranz’s post on bash history. Hal did an awesome job analyzing bash history artifacts, when history files may not be written, and possible anti-forensic techniques. DFIR analysts who are analyzing Linux systems should be aware of these methods! Thanks Hal for sharing that awesome information with us!

Accessing Bash History

On a live system, the Bash history can be displayed by simply typing history . In return, you’ll get a list of previous commands preceded by numerical order. As you can imagine, if your bash history is untouched and the max file size allows it, you may go all the way back to when the user account was first used.

If you’re performing remote or dead forensics, bash history files are typically located under each user profile. They are aptly named .bash_history , and contain an ASCII list of commands issued by that particular user. Again, the file name is dependent on no alternate file designated by the HISTFILE variable (and of course history actually being record).

Pinpointing Bash History

As discussed above, unfortunately default bash history does not include timestamps by default. They can be enabled, but as the example above showed, dates previous to the current session will stamped with a single timestamp relative to the last session. However, that does not mean we are entirely in the dark about when things happened!

The goal with most investigations is to answer the question of what happened when. By coupling bash history with some other support files, we can actually begin to define time periods to an artifact with no time keeping. Here are a few examples:

Context with additional logs

Another neat little artifact on systems is the file /var/log/apt/history.log . This file is a record — a history of its own — of package installations. Here’s a quick snippet from one of my Debian VMs:

In the example above, you can clearly see I installed zlib1g-dev and libssl-dev between 18:07:00 and 18:07:27 on September 16, 2016. Let me pull the same contents from my .bash_history file:

Now, we’ve got some additional context. Based on the timestamps we can assign — thanks to the apt history log — it looks as though the user (me in this case) was attempting to compile and install something, and was downloading dependencies as the script ran into errors. I can see that potentially there’s a file called bootstrap.sh related to this install.

Now, let’s think about if this was an attacker. A few questions come to mind:

  • What did the attacker install?
  • I should search the system for the file boostrap.sh , and see exactly what that file does.
  • Notice that the attacker ran make and then sudo make install . If they are successfully executing sudo commands, then I can assume they have the password for the account (which is part of the sudoers group) and/or have enabled sudo privileges. This naturally will lead me to also examine the root account.
  • Do the installed dependencies tell me anything about the specific program? In this example, I believe I was installing AFFlib .

Context with file timestamps

Another method to attach timestamps to bash history is to find an action that affected a system timestamp, and look at that file’s attributes. Consider the following example:

Using the touch command, I created an empty file named .secret_file . This file is hidden from a normal user, but the attacker may know it was there. Now, let’s look at at the metadata for this file:

Notice that we’ve got timestamps for the file around today, 2016–12–27, at approximately 20:02 CST. As the file is still zero bytes in size and all three timestamps are identical, I can make a safe bet that this entry was around this time. Let’s look at .bash_history for the next few lines:

Now, let’s look at the metadata for the file .secret_file2 :

Awesome! Using these two artifacts, I can paint an approximate 5-minute window that my attacker was on the host. It also looks like there was some SCP activity to a known bad IP address. If I wanted to get my network forensic team involved, I could throw them this timeframe and ask for related traffic. All that from an artifact with no timestamps!

Context with network traffic

In the previous example, I discussed handing off indicators to the network forensics team to assist with analysis. In other cases, we can start with network data to timestamp our bash history. Consider the syntax from the following commands:

  • wget [OPTION]… [URL]…
  • curl [options…] <url>

These commands are typically used to download files from the Internet. If we’ve got recorded evidence of this activity, we could use our network traffic to identify that time and pinpoint our history.

Context with other users

When analyzing bash history files, don’t forget that files are unique to users. If you see an attacker change to a root account or another user, you need to pull those histories as well. Unfortunately, as mentioned, we can’t simply overlay the histories and watch the attacker walk through the host. Instead, we can correlate artifacts and use the timestamps we can identify to determine account activity.

Context with other hosts

In this last example, consider an attacker who has high enough privileges that they can move laterally around multiple systems. We can utilize the authentication logs from the remote system to pinpoint timestamps on our local infected host. While yes, this is basically log correlation, we are unfortunately having to utilize another host to perform it.

Also keep in mind that if we see lateral movement, our infected host list should be growing quickly.

Wrap-Up

If anyone finds themselves performing Linux forensics, I hope that bash history is still intact and is available for examination. Remember that the lack of timestamps doesn’t have to mean a useless artifact, it just means we have to do a bit more digging and correlation.

A Complete Guide to Linux Bash History

A Complete Guide to Linux Bash History

Developers, sysadmins, and DevOps engineers spend a lot of time at the Linux command line. And, invariably, we make tpyos typos. Other times, we just need to run the same command again or determine what commands were previously executed on a system. In all of those cases, knowing how to work with bash history helps.

In this article, we’ll take a closer look at what bash history is, how bit works, and how you can use it to become a more efficient when you’re working at the Linux command line. You can follow along with the commands in this article using almost any modern *nix operating system with bash.

#What is bash history?

The term bash history refers to the commands, files, and shortcuts that allow you to view, modify, and delete bash commands that have been run on a system.

Bash has two bulitin commands for working with bash history:

  • history — Allows you to list commands and modify your bash history.
  • fc — Allows you to list, edit, and execute commands from your bash history.

Because the term "bash history" often implies the history command, we’ll focus on the mechanics of the history command instead of fc for most of this article.

In addition to these two bulitin commands, there are a variety of files (like

/.bash_history ), expansions (like !! ), and keyboard shortcuts (like the ↑ and ↓ keys) that help you work with bash history.

In the sections below, we’ll explore how these aspects of bash history work.

#How does bash history work?

By default, history stores commands in RAM until you log out of the terminal. Once you log out, commands are written to disk in the

/.bash_history file. The history buffer is limited to 1,000 command entries and the history file is limited to 2,000 entries.

You can modify the default behavior of the history command by setting environment variables, which we’ll review in more detail shortly.

#Working with Bash history: The basics

The easiest way to get started working with bash is to run the history command with no options. You should see output similar to this:

The numbers next to the commands indicate the order they were entered into the history (the oldest command being 1). You can also use the ↑ and ↓ keys on your keyboard to scroll through your bash history.

We can limit the output to the last N commands with the command history N . For example, history 2 will return the 2 most recent commands.

You can pipe history into grep or less to make it easier to filter the output.

You can delete a specific entry with the history -d N where N is the number of the command or a range of numbers. For example, history -d 2-4 deletes commands 2, 3, and 4 from our history.

To clear the history buffer (i.e., the commands saved in RAM for the current terminal session) use the command history -c .

The bash history saved to disk is in the $HISTFILE which is

/.bash_history by default. You can clear that file with a command such as:

#Configuring bash history settings with .bashrc

In some cases, you may want to modify how bash history works on your Linux system. Adding Linux environment variables to your

/.bashrc file can help you do just that. Here are some common use cases for customizing bash history using

As we go, remember that changes to a user’s

/.bashrc file take into effect after logging out and logging back into your shell. Alternativelly, you may run .

/.bashrc or source

/.bashrc to reload bash settings.

#Exclude commands from bash history

You may want to exclude commands from bash history to avoid noise in the output or for security reasons. On many Linux distros, you can prevent a command from being included in bash history by adding a space before you execute the command.
Commands with a space in front of them are not stored in bash history

However, that may not hold true on all distros. Whether or not leading spaces are ignored depends on the $HISTCONTROL environment variable. If $HISTCONTROL is set to ignoreboth or ignorespace , commands with a leading space are not saved to history.

To exclude commands from your bash history with

/.bashrc , you can use the $HISTIGNORE environment variable. $HISTIGNORE allows you to define a colon separated list of command patterns that will not be saved to your bash history. For example, to ignore any sudo commands or any commands where echo is followed by a w , add this to your

#Immediately persist commands to .bash_history

It’s common for users to have multiple terminals open for the same user account, and this is where things can get tricky. By default, the history command will only show commands from the current terminal session and the commands that are saved to the

/.bash_history file are the commands from the last session to log out.
Two Linux terminals showing different output after the root user executes the history command

To immediately persist commands to your

/.bash_history file, you can add this to

#Add date and timestamps to bash history output

Often, knowing when you ran a command is an important part of knowing which command you need now. Adding timestamps to your bash history output can help make this easier.

To include timestamps with your bash history, add this to your

%F adds the date in YYYY-MM-DD format and %T adds a HH:MM:SS timestamp. Here is an example of what history command output looks like with this bash environment variable set.
Bash history with timestamps

Note that the space after the %F and %T is useful for formatting the output. Without the spacing, the date, timestamp, and command would all run together.

#Modify bash history buffer and file size

If the default values of 1,000 command entries in the history buffer and 2,000 entries in the history file isn’t what you want, you can change the $HISTSIZE (buffer) and $HISTFILESIZE (file) environment variables.

For example, to set both to 11,000 entries, modify the default values to read:

#Useful bash history keyboard shortcuts

In addition to the history command, there are several keyboard shortcuts that make working with bash history easy. Here are some of the most useful:

Bash history keyboard shortcut Description
↑ key Scroll backwards through bash history
↓ key Scroll forward through bash history
ctrl+R Search for commands in your bash history
ctrl+O Run a command you found using a ctrl+R search
ctrl+G Exit a crtl+R search

#Bash history expansion

If you’ve ever run sudo !! , you’ve already used a bash history expansion command. However, there are plenty of other ways to use expansion commands to work with your bash history. Here is a list of some of the most useful bash history expansions:

Bash history expansion command Description
!! The last command executed in the terminal. This is equivalent to !-1 .
!N The Nth command in your bash command history.
!-N The command N before the most recent command in your bash history.

Here’s a simple example to demonstrate the logic:
Bash history expansion commands

Note that in the example we added a space before our expansion commands so they aren’t included in our bash history.

#Bash history designators

All three of the previous expansion commands are examples of designators. And there are several more powerful designators you can use to work with your bash history.

!<command> will execute the most recent <command> in your bash history. For example, suppose we have these commands in our history output:

!curl will run curl -Lo cherry.html cherryservers.com , !ls will run ls -la , etc.

You can also use ^ designators to substitute parts of the most recent command in your bash history with different content. The general format is:

For example, if the previous command in your history was:

And you wanted to change /path/wrongplace to /path/rightplace instead of typing the entire command again, you could run:

And the output would be similar to:

#Use designators to get arguments from a command

You can use a colon : followed by a specific designator to add arguments from the most recent command in your history to a subsequent command. The table below details some of the common designators:

Designator Description
!:^ Use the 1st argument of the most recent command in your bash history.
!:N Use the Nth argument of the most recent command in your bash history
!:$ Use the last argument of the most recent command in your bash history.
!:* Use all the arguments of the most recent command in your bash history.

Below is an example to visualize the concept:

The colon designator uses arguments from a previous command in your bash history

#Bash history modifiers

Bash history modifiers complement designators by changing the content or execution of the command. You specify modifiers after a command with a colon and a letter (e.g., :h )

Here are some common bash history modifiers and what they do.

Modifier Description
:h Removes the trailing path from a command. Useful for getting a path without a filename.
:t Removes the leading path from a command. Useful for getting a filename without a path
:r Removes an extension from a filename.
:p Prints a command without running it.
:s Enables string substitution comparable to the sed command.

For example, suppose we wanted to list all the .log files in a directory with ls /directory/*.log but instead we ran the command ls /directory/*.txt . We could use the command !:s/txt/log to correct the mistake. End-to-end, it would look similar to this:

#Conclusion

With knowledge of bash history, you can work more efficiently at a Linux terminal. The information we covered here should help you handle most of the common bash history use cases you’ll encounter. For a deeper dive on bash history, we recommend reading the GNU manpage for the bulitin bash history commands and testing different designators and customizations in your own test environment.

For more Linux administration content like this, subscribe to the Cherry Servers blog!

Mantas Levinas

Helping engineers learn �� about new technologies and ingenious IT automation use cases to build better systems ��

Join Cherry Servers Community

Get monthly practical guides about building more secure, efficient and easier to scale systems on an open cloud ecosystem.

Where is the bash history for the root user saved?

I’m not talking about .bash_history from my home directory. I usually prefer to use sudo -i or sudo su and then run commands as root user.

Since, after these commands the history is not saved in the .bash_history file from my home directory, I want to know if this history is saved somewhere or not and if yes, where?

3 Answers 3

Well, when you’re logged in as root, the bash history is saved in /root/.bash_history file, where /root is the default home directory for root user. To prove this, run the following command when you are logged as root:

The $HISTFILE variable points to the file that contains your history.

Source: $HISTFILE

Generally when you log into another user account, the bash history will be saved in a file called .bash_history located in the home directory of that user.

Furthermore, if you want to save the bash history for the root user in another file, let say in .bash_history file from my home directory, you have to edit /root/.bashrc file, and add a new line at the end of file with the following content:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *