Recover open files but deleted from linux file system

    Happy New Year to all!
    In this note, I would like to share how you can restore an open file in linux.

    Background


    A man went to the channel dedicated to debian in jabber and said that they had cracked his jabber-bot and executed the command:
    $ rm -rf /*

    since this was not done under root, there shouldn’t be any special problems, but the bot’s configuration files were deleted. The bot remained running and the task was to restore the files it opened 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 installed and procfs is mounted in / proc .
    In this note, I will consider that in the system where the open files will be restored, all the necessary applications are installed, there is root access, everything is mounted as needed.

    First of all, 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 in bold what you need:
    kwin 2031 4002 anton  2 w REG 253.3 4486557 1835028 /home/anton/.xsession-errors

    Next, 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 an open file, but which for some reason has been deleted.

    UPD1 : I was asked how to find and restore all open files by a specific application.
    Suppose we know 1 file that needs 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, we just have to select the remote ones:
    $ sudo lsof -p 2031 | grep deleted

    Then we simply restore all the files as described above.

    UPD2 : Why am I using grep to search for files instead of a parameter that works faster?
    I use grep since the file is visible there or not, I think it is more convenient (IMHO)

    UPD3 : You can also see all open process files through the ls command , deleted marks will be, example:
    $ ls -lia /proc/2031/fd/

    Also popular now: