Happy New Year to all!
In this post I would like to share how you can restore an open file in linux.
Prehistory
A man entered the debian channel dedicated to jabber and said that they had hacked it with jabber-bot and executed the command:
$ rm -rf /*
since this was not done under the root, there should be no special problems, but the bot configuration files are removed. The bot remained running and the task was to restore the files opened by it and try to raise everything as quickly as possible with the same settings.
Restore file
First of all, we need to make sure that we have the
lsof application and mount the
procfs in
/ proc .
In this note, I will assume that in the system where the open files will be restored, all the necessary applications are installed, root access is available, everything is mounted as needed.
First we need to find the open file using the lsof program:
$ sudo lsof | grep filename
Example:
$ sudo lsof | grep /home/anton/.xsession-errors kwin 2031 4002 anton 2w REG 253,3 4486557 1835028 /home/anton/.xsession-errors
We are interested in these values:
- Process Number (pid)
- File descriptor
Here I will highlight what is needed in bold:
kwin 2031 4002 anton 2 w REG 253.3 4486557 1835028 /home/anton/.xsession-errors
Then restore it (you can also save it elsewhere):
$ sudo cp /proc/2031/fd/2 /home/anton/.xsession-error
That's all, so you can restore the open file, but which for some reason was deleted.
')
UPD1 : I was asked how to find and restore all open files with a specific application.
Suppose we know 1 file to be restored, we found it using
$ sudo lsof | grep /home/anton/.xsession-errors kwin 2031 anton 2w REG 253,3 4486557 1835028 /home/anton/.xsession-errors
We know that 2031 is the pid of the process that holds your file. We need to find all the files that keep this process open:
$ sudo lsof -p 2031
We see all open applications by this process, it remains for us only to select the deleted ones:
$ sudo lsof -p 2031 | grep deleted
Then just restore all the files as described above.
UPD2 : Why do I use
grep to search for files instead of a parameter that works faster?
I use grep because I can see if the file was deleted or not, I find it more convenient (IMHO)
UPD3 : You can also view all open process files via the
ls command , the
deleted marks will be, for example:
$ ls -lia /proc/2031/fd/