Linux имя временного файла

Creating temporary files in bash

Are there objectively better ways to create temporary files in bash scripts? I normally just name them whatever comes to my mind, such as tempfile-123, since it will be deleted when the script is over. Is there any disadvantage in doing this other than overwriting a possible tempfile-123 in current folder? Or is there any advantage in creating a temporary file in a more careful way?

Don’t use temporally files. Use temporally directories instead. And don’t use mktemp. See here why: codeproject.com/Articles/15956/…

@ceving That article is simply wrong, at least when applied to the shell command mktemp (as opposed to the mktemp library call). As mktemp creates the file itself with a restrictive umask, the attack given only works if the attacker is operating under the same account as the attackee. in which case the game is already lost. For best practices in the shell-scripting world, see mywiki.wooledge.org/BashFAQ/062

7 Answers 7

The mktemp(1) man page explains it fairly well:

Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win. A safer, though still inferior, approach is to make a temporary directory using the same naming scheme. While this does allow one to guarantee that a temporary file will not be subverted, it still allows a simple denial of service attack. For these reasons it is suggested that mktemp be used instead.

In a script, I invoke mktemp something like

mydir=$(mktemp -d "$$(basename $0).XXXXXXXXXXXX") 

which creates a temporary directory I can work in, and in which I can safely name the actual files something readable and useful.

mktemp is not standard, but it does exist on many platforms. The «X»s will generally get converted into some randomness, and more will probably be more random; however, some systems (busybox ash, for one) limit this randomness more significantly than others

By the way, safe creation of temporary files is important for more than just shell scripting. That’s why python has tempfile, perl has File::Temp, ruby has Tempfile, etc…

It seems the most safe and most cross-platform way to use mktemp is in combination with basename , like so mktemp -dt «$(basename $0). XXXXXXXXXX» . If used without basename you might get an error like this mktemp: invalid template, `/tmp/MOB-SAN-JOB1-183-ScriptBuildTask-7300464891856663368.sh.XXXXXXXXXX’, contains directory separator.

@i4niac: you need to quote that $0 , there are spaces a plenty in the land of OS X. mktemp -dt «$(basename «$0″).XXXXXX»

Читайте также:  What is root localhost in linux

Also it may be nice to remove the tempdir at the end of the script execution: trap «rm -rf $mydir» EXIT

It will create a temporary file inside a folder that is designed for storing temporary files, and it will guarantee you a unique name. It outputs the name of that file:

You might want to look at mktemp

The mktemp utility takes the given filename template and overwrites a portion of it to create a unique filename. The template may be any filename with some number of ‘Xs’ appended to it, for example /tmp/tfile.XXXXXXXXXX. The trailing ‘Xs’ are replaced with a combination of the current process number and random letters.

Is there any advantage in creating a temporary file in a more careful way

The temporary files are usually created in the temporary directory (such as /tmp ) where all other users and processes has read and write access (any other script can create the new files there). Therefore the script should be careful about creating the files such as using with the right permissions (e.g. read only for the owner, see: help umask ) and filename should be be not easily guessed (ideally random). Otherwise if the filenames aren’t unique, it can create conflict with the same script ran multiple times (e.g. race condition) or some attacker could either hijack some sensitive information (e.g. when permissions are too open and filename is easy to guess) or create/replacing the file with their own version of the code (like replacing the commands or SQL queries depending on what is being stored).

You could use the following approach to create the temporary directory:

However it is still predictable and not considered safe.

As per man mktemp , we can read:

Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win.

So to be safe, it is recommended to use mktemp command to create unique temporary file or directory ( -d ).

It does improve the answer indeed. My upvote was already yours, though. Can’t vote more. One suggestion I have is to explain what $ and $$ expand to, or link to some documentation about it.

@jpbochi $ is the file name of the script that is currently running and $$ is its process id. Generally, I don’t think this solution is a good approach because it can leave hidden files and folders in various directories the script is being executed from. The temporary files and folders can be deleted afterward, but if the script is halted (using CTRL-C ), then the they will remain. It’s better practice to use mktemp because it creates temporary files in the system’s temporary folder.

Читайте также:  Pop os linux установка

mktemp is probably the most versatile, especially if you plan to work with the file for a while.

To somewhat expand on previous answers here, you want to run mktemp and make sure you also clean up afterwards. The usual way to do that is with trap , which lets you set up a hook that can be run when your script is interrupted.

Bash also provides the EXIT pseudo-signal so that you can set up a trap to be run when your script exits successfully, and ERR which triggers if your script produces an error. (See also What does set -e mean in a bash script? for some unobvious consequences.)

t=$(mktemp -d -p temporary.XXXXXXXXXXXX) || exit trap 'rm -rf "$t"; exit' ERR EXIT # HUP INT TERM : # use "$t" to your heart's content . 

You might want to set up additional signals besides ERR and EXIT ; obviously, kill -9 cannot be trapped (which is why it should not be used, except in emergencies). HUP (signal 1) and INT (signal 2) are generated when your script’s session is hung up, or the user presses ctrl-C, respectively. TERM (signal 15) is the default signal sent by kill , and requests the script to be terminated.

mktemp -p replaces mktemp -t which is regarded as obsolete. The -d option says to create a directory; if you only need a single temporary file, obviously, that’s not necessary.

Источник

Linux имя временного файла

Команда mktemp позволяет задействовать одноименную утилиту, предназначенную для создания временных файлов и директорий. Разумеется, все временные файлы создаются по умолчанию в предназначенной для них директории /tmp и имеют уникальные имена. Эти имена выводятся с помощью стандартного потока вывода утилиты. Сама утилита является достаточно гибкой: пользователь может задать суффикс для имени создаваемого файла или директории, а также указать шаблон имени с целью создания файла или директории с произвольным именем в рамках текущей директории. Файлы или директории создаются с правами чтения и записи лишь для текущего пользователя, причем в случае создания директории добавляется флаг исполнения того, чтобы у текущего пользователя имелась возможность просмотра ее содержимого. После окончания использования файл или директория должны удаляться силами пользователя с помощью команды rm и rmdir соответственно. Как вы наверняка догадались, данная команда может оказаться чрезвычайно полезной при разработке сценариев командной оболочки, осуществляющих обработку данных и их хранение во временных файлах.

Читайте также:  Linux найти только файлы

Базовый синтаксис команды выглядит следующим образом:

$ mktemp [параметры] [шаблон-имени-файла]

Команда может принимать шаблон имени временного файла или директории, а также ряд параметров. Актуальными для обычного пользователя параметрами являются параметр -d, позволяющий создать директорию вместо файла, параметр —suffix, позволяющий задать суффикс имени создаваемого файла, параметр -q, позволяющий скрыть сообщения о возникающих ошибках, а также параметр -u, позволяющий вывести сгенерированное имя временного файла или директории без создания самого элемента файловой системы.

Примеры использования

Создание временного файла

Для создания временного файла достаточно использовать утилиту mktemp без каких-либо параметров:

$ mktemp
/tmp/tmp.WBEWMMjZGR
$ ls -al /tmp/tmp.*
-rw——- 1 alex alex 0 фев 15 17:57 /tmp/tmp.WBEWMMjZGR
$ rm /tmp/tmp.WBEWMMjZGR

Утилита выводит имя созданного временного файла с помощью потока стандартного вывода. В существовании этого файла несложно убедиться с помощью утилиты ls. Для удаления созданного файла достаточно использовать утилиту rm.

Пользователь может задать свой собственный суффикс имени файла, воспользовавшись параметром —suffix:

$ mktemp —suffix=+authentic
/tmp/tmp.kh7t0CBSaF+authentic
$ ls -al /tmp/tmp.*
-rw——- 1 alex alex 0 фев 15 18:03 /tmp/tmp.kh7t0CBSaF+authentic
$ rm /tmp/tmp.kh7t0CBSaF+authentic

Несложно догадаться, что имя суффикса будет добавлено к сгенерированному имени файла.

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

$ mktemp authentic+XXXXXX.tmp
authentic+yBA27G.tmp
$ ls -al *.tmp
-rw——- 1 alex alex 0 фев 15 18:07 authentic+yBA27G.tmp
$ rm authentic+yBA27G.tmp

Как и было сказано ранее, символы X в шаблоне были заменены на произвольные символы, а сам файл был создан в текущей директории.

Создание временной директории

Для создания временной директории в достаточно использовать утилиту с параметром -d:

$ mktemp -d
/tmp/tmp.CatJPSDWmd
$ ls -al /tmp/ | grep tmp.
drwx—— 2 alex alex 6 фев 15 18:10 tmp.CatJPSDWmd
$ rmdir /tmp/tmp.CatJPSDWmd/

Из вывода утилиты ls очевидно, что вместо файла была создана директория (символ d в столбце прав доступа), причем текущему пользователю разрешается просмотр ее содержимого (символ x там же). Для ее удаления должна использоваться команда rmdir, а не rm, как в случае с файлом.

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

$ mktemp -d —suffix=+authentic
/tmp/tmp.u2BD7E2rhr+authentic
$ ls -al /tmp/ | grep tmp.
drwx—— 2 alex alex 6 фев 15 18:16 tmp.u2BD7E2rhr+authentic
$ rmdir /tmp/tmp.u2BD7E2rhr+authentic/

Директория создается с теми же правами доступа и в той же директории — изменяется лишь ее имя.

При создании временных директорий также могут использоваться шаблоны:

$ mktemp -d authentic+XXXXXX
authentic+Ddg61O
$ ls -al | grep authentic
drwx—— 2 alex alex 6 фев 15 18:18 authentic+Ddg61O
$ rmdir authentic+Ddg61O/

Директория создается в текущей директории, причем ее имя соответствует заданному шаблону.

Источник

Оцените статью
Adblock
detector