- Empty or Delete a log files in Linux or UNIX
- How to clear the contents of a log file from the command line
- Delete a log files in Linux or UNIX using truncate
- Other commands to empty or delete a large file content in Linux
- How do I clear log file using dd on Linux or Unix?
- How to empty or truncate a file in Linux using echo/printf
- Say hello to logrotate tool
- Conclusion
- Заметаем следы вместе с хакерами. Чистим логи и историю Bash на взломанных Linux системах
- Шаг 1. Скомпрометируйте цель
- Шаг 2. Создайте легко удаляемый скрытый каталог
- Шаг 3. Удалите историю Bash
- Шаг4. Очистите файлы журнала
- Шаг 5. Используйте специальный инструмент для наилучшего сокрытия следов
- Заключение
- How to Clear Systemd Journal Logs
- Clearing systemd journal logs
- 1. Clear journal log older than x days
- 2. Restrict logs to a certain size
- 3. Restrict number of log files
- Automatically clearing old log files [Requires intermediate knowledge of command line]
Empty or Delete a log files in Linux or UNIX
How to clear the contents of a log file from the command line
Say you want to clear the contents of a log file named /var/log/messages, run:
# >/var/log/messages
The following is compatible with various Linux or Unix shells:
: > /var/log/messages
Verify file size:
# ls -l /var/log/messages
If you really wanted to delete or remove a file type the following rm command:
# rm /var/log/message
Delete a log files in Linux or UNIX using truncate
Use the truncate command to shrink or extend the size of each FILE to the specified size. So a proper way to clear log file named www.cyberciti.biz_access.log is to run the following command:
# cd /var/log/nginx/
# ls -lh www.cyberciti.biz_access.log
# truncate -s 0 www.cyberciti.biz_access.log
# ls -lh www.cyberciti.biz_access.log
Clear the contents of a file named /var/log/nginx/www.cyberciti.biz_access.log from the command line
Other commands to empty or delete a large file content in Linux
Try the cat command:
cat /dev/null > www.cyberciti.biz_access.log
Or the cp command:
# cp /dev/null /var/log/nginx/php_error.log
How do I clear log file using dd on Linux or Unix?
Type dd command as follows:
# dd if=/dev/null of=/path/to/log/file
# dd if=/dev/null of=/var/log/lighttpd/error_log
How to empty or truncate a file in Linux using echo/printf
One more method is to use the echo command:
# echo -n «» > /path/to/java/appserver.log
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Say hello to logrotate tool
A better approach is to use logrotate tool. It is designed to ease administration of systems that generate large numbers of log files. It allows automatic rotation, compression, removal, and mailing of log files. Each log file may be handled daily, weekly, monthly, or when it grows too large. See my previous logrotate help page:
Conclusion
This page showed how to empty or delete a large log file contents in Linux and Unix like systems. There are other methods too as discussed in the comments section below.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
my log files /var/log deleted is it creates any problem
/var/log is directory, if you delete the same just recreate directory using mkdir command:
mkdir /var/log
How would you specify to delete log that are over a certain age. ie 2days old or something like that. Thanks for the help.
One way is to setup new cronjob for that. Then google: “tmpwatch delete files older”
There are 2 options, either use log logrotate or use find command to get list of 2 days old files and empty them. You can find information about logrotate and about find command here only. Use search box to get information
Thank you for pointing me in the right direction. I’ve been doing some more research and had another question if you wouldn’t mine throwing in some input.
I want to remove apache logs after about a month. So I was going to set something up like this that I found online.
This is an example of a /etc/logrotate.d/httpd
/var/log/httpd/*.log <
daily
rotate 30
missingok
notifempty
sharedscripts
postrotate
/bin/kill -HUP `cat /var/run/httpd.pid 2>/dev/null` 2> /dev/null || true endscript
>
Now from what I understand this will rotate the log daily meaning create a new log everyday. The 30 means that it will hold 30 of these logs before deleting them (or compressing if I put that option in there)
Also, before I go and set this up, I want to test it on 1 websites log incase I mess things up. Would it be ok to replace the line
/var/log/httpd/*.log
with
/var/log/httpd/”website”*.log to that affect to test in one website before doing all of them?
Does it sound like I’m on the right track or am I completely lost 🙂 thanks again for your input.
simply wirte rm file.log and press enter
Use the following command:
suppose your file name is message.log then use:
This will empty the file without having deleting it.
Hallo, i have same use command as your suggest.
echo ”> message.log
but, if one folder contain much log like that, how i can clean up directly using echo command without delete it (rm)
Hi Ajeet,
Can you tell me please how it works ?
echo “” ->print the blank space
and that blank space is redirected to message.log file
or in other word your file conatins replaced by blank space without
Please could anybody help me how to delete the log files of DHCP server. and how to identify them.
Источник
Заметаем следы вместе с хакерами. Чистим логи и историю Bash на взломанных Linux системах
Последним этапом деятельности любого хакера является заметание следов.
Автор: DRD_, Cyber Weapons Lab
Последним этапом деятельности любого хакера является заметание следов. Киберпреступник удаляет следы своей деятельности и логи, чтобы избежать обнаружения. Данный этап особенно важен, если злоумышленник в будущем планирует снова получить доступ к целевому устройству.
Для демонстрации основ заметания следов, сначала скомпрометируем цель, а затем изучим несколько методов, используемых для удаления истории Bash и очистки логов после взлома Linux систем.
Шаг 1. Скомпрометируйте цель
Первое, что нам следует сделать, — взломать цель. Используя некорректную обработку сервером команд ОС, можно применить внедрение команд, для получения оболочки. Затем нашу новую оболочку необходимо обновить до полностью интерактивной. Данная процедура значительно упростит работу. После этого мы сможем повысить наши привилегии до root, чтобы наилучшим образом использовать преимущества системы и оставаться незамеченными.
Шаг 2. Создайте легко удаляемый скрытый каталог
Получив root-доступ, мы можем создать скрытый каталог для работы и хранить в нем любые скрипты или файлы. С одной стороны, подобные манипуляции обманут лишь самого начинающего администратора, но дополнительный уровень защиты определенно не повредит. Во-первых, давайте найдем все доступные для записи каталоги с помощью следующей команды:
С помощью команды mkdir можно создать скрытый каталог, добавив точку к имени:
Зададим команду перечисления содержимого /dev/shm. Как видим, ничего не появилось:
Каталог появляется лишь тогда, когда мы используем переключатель -a для вывода списка всех файлов и каталогов:
Для удаления каталога после завершения работы на машине, используйте команду rmdir :
Шаг 3. Удалите историю Bash
Команды записываются в переменную среды HISTFILE, обычно это .bash_history. Воспользуемся echo для определения местоположения:
Используем команду unset для удаления переменной:
Повторив процедуру снова, видим, что ничего не появляется:
Чтобы история команд не сохранялась, также можно ее отправить в /dev/null. Для этого установите переменную:
Или сделайте то же самое с командой экспорта:
История теперь будет отправлена в /dev/null (то есть никуда):
Установите количество команд, которые будут сохраняться во время текущего сеанса, равным 0, используя переменную HISTSIZE:
В качестве альтернативы используйте команду экспорта:
Измените количество строк, разрешенных в файле истории, с помощью переменной HISTFILESIZE. Установите данное значение на 0:
Или с экспортом:
Для изменения параметров оболочки также можно использовать команду set. Чтобы отключить опцию истории, используйте следующую команду:
Снова включите ее:
Точно так же для изменения параметров оболочки можно использовать команду shopt. Чтобы отключить историю, используйте следующую команду:
Снова включите ее:
Во время выполнения команд на целевой системе иногда получается избежать их сохранения в истории, запустив команду с начального пробела:
Данный метод работает не всегда и зависит от системы. Также можно просто очистить историю с помощью переключателя -c :
Чтобы убедиться, что изменения записаны на диск, используйте переключатель -w :
Данные действия очистят историю только для текущего сеанса. Чтобы окончательно убедиться, что история очищается при выходе из сеанса, пригодится следующая команда:
Также можно использовать команду kill для выхода из сеанса без сохранения истории:
Шаг4. Очистите файлы журнала
Конечно, можно просто удалить журнал с помощью команды rm :
Но скорее всего, данная процедура вызовет многочисленные красные флажки. Поэтому лучше сделать файл пустым, чем стирать его полностью. Используем команду truncate, чтобы уменьшить размер файла до 0:
Обратите внимание, функция усечения присутствует не всегда и не во всех системах.
То же самое можно сделать, отображая в файл “ничего”:
А также использовать > сам по себе для очистки файла:
Мы также можем отправить его в /dev/null:
Или использовать команду tee :
Также можно использовать команду dd, чтобы ничего не записывать в файл журнала:
Команда shred может быть использована, чтобы поверх перезаписать файл с бессмысленными двоичными данными:
Дополнительно добавив -zu, вы обрежете файл и перезапишете его нулями:
Шаг 5. Используйте специальный инструмент для наилучшего сокрытия следов
Перейдите в каталог с возможностью записи и используйте chmod, чтобы сделать его исполняемым:
Затем запустите его:
Нам предоставляется настраиваемая подсказка с несколькими вариантами на выбор. Выберем первый, чтобы очистить логи:
Также можно отключить Bash и историю авторизации с помощью опции 2:
Если вам нужно срочно все очистить, просто добавьте в команду now:
Заключение
Отмечу, что существуют и другие способы удаления следов атаки. Можно использовать Metasploit , сценарии оболочки или осуществить сокрытие следов на взломанной Windows системе. Тем не менее информации, приведенной в статье, вполне достаточно для сокрытия активности на базовом Linux компьютере.
Источник
How to Clear Systemd Journal Logs
This quick tutorial shows you two ways to clear systemd journal logs from your Linux system.
The systemd journal is systemd’s own logging system. It is equivalent to the syslog in the init system. It collects and stored kernel logging data, system log messages, standard output and error for various systemd services.
A Linux machine with systemd writes the logs to /var/log/journal directory. If you remember the Linux directory structure, /var is where the system logs are stored.
You can either manually view the log files using less command or use the journalctl command. To view all the latest logs, use the command with reverse option.
The thing with logging is that over the time, it starts to grow big. And if you check the disk space in Linux, you’ll see that sometimes, it takes several GB of space.
Let me show you how to clean systemd journal logs and free up disk space on your Linux system.
Clearing systemd journal logs
First check the space taken by journal logs with the du command:
You can also use the journalctl command for the same task:
Both of the command should give approximately the same result:
Now that you know how much space the journal logs take, you can decide if you want to clear the logs or not. If you decide to clear the journal logs, let me show you a couple of ways of doing it.
You can of course use the rm command to delete the files in the log folder but I won’t advise that. The journalctl command gives you the proper way of handling old logs.
First thing you should do is to rotate journal files. This will mark the currently active journal logs as archive and create fresh new logs. It’s optional but a good practice to do so.
Now you have three ways to clear old journal logs. You delete logs older than a certain time or you delete older log files so that total log size is limited to the predefined disk space or you limit number of log files. Let’s see how to use all three methods.
1. Clear journal log older than x days
Keep in mind that logs are important for auditing purpose so you should not delete all of them at the same time. Let’s say you want to keep the log history of just two days. To delete all entries older than two days, use this command:
Here’s what the output may look like:
You can also change the provide time frame in hours like 2h, in minutes like 2m, in seconds like 2s. If you want bigger time units, you can 2weeks, 2months as well.
2. Restrict logs to a certain size
Another way is to restrict the log size. With this, it will delete the journal log files until the disk space taken by journal logs falls below the size you specified.
This will reduce the log size to around 100 MB.
You can specify the size in GB with G, MB with M, KB with K etc.
3. Restrict number of log files
The third way is to limit the number of log files. The journalctl usually has log files for the system and for the users. As the logs get old they are archived in various files.
You can limit the number of archive log files. Let’s say you want to have only five log files.
It will remove the older archive log files leaving only the specified number of log files.
Automatically clearing old log files [Requires intermediate knowledge of command line]
What you just did will clean the log files for now. In a month the logs will increase again. You can manually clean them with one of the methods described above. But that is a tedious task and you may not remember to do that regularly.
The good thing is that you can configure systemd to automatically handle old log files.
The journalctl has configuration file at /etc/systemd/journald.conf. There are settings which are commented out. The commented lines basically indicate the default value of those settings parameters (even if they are commented out).
You can change some of these default settings to automatically clean the log files.
You would want to change the following settings:
Setting | Description |
---|---|
SystemMaxUse | Max disk space logs can take |
SystemMaxFileSize | Max size of an INDIVIDUAL log file |
SystemMaxFiles | Max number of log files |
Please note that you should be careful while editing configuration files. You must be comfortable using a terminal-based text editor like Vim, Emacs or Nano so that you don’t make silly mistakes while editing the conf file.
I advise to make a backup of the configuration file first:
Now, you should uncomment (remove the # at the beginning of the line) the setting you want to use. For example, I want to restrict the maximum disk space taken by the log files to 250 MB.
You’ll have to use Vim or some other terminal based editor in order to edit this configuration file. Here’s what it looks like me after editing the file.
Keep in mind that after editing the configuration file, you should load the changes:
The journald.conf file can be used to tweak the journalctl settings even further. You can even set the levels of log (info, debug, error etc) you want to see. It’s up to you if you want to change those settings as well.
I hope you like this tip to clear systemd journal log files. If you have any questions or suggestions, please leave a comment below.
Источник