在 Python 中创建一个临时 FIFO(命名管道)? [英] Create a temporary FIFO (named pipe) in Python?

查看:29
本文介绍了在 Python 中创建一个临时 FIFO(命名管道)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Python 中创建临时 FIFO(命名管道)?这应该有效:

How can you create a temporary FIFO (named pipe) in Python? This should work:

import tempfile

temp_file_name = mktemp()
os.mkfifo(temp_file_name)
open(temp_file_name, os.O_WRONLY)
# ... some process, somewhere, will read it ...

但是,由于 Python Docs 11.6 和可能会被移除,因为它已被弃用.

However, I'm hesitant because of the big warning in Python Docs 11.6 and potential removal because it's deprecated.

EDIT:值得注意的是,我已经尝试过 tempfile.NamedTemporaryFile(以及扩展 tempfile.mkstemp),但是 os.mkfifo 抛出:

EDIT: It's noteworthy that I've tried tempfile.NamedTemporaryFile (and by extension tempfile.mkstemp), but os.mkfifo throws:

OSError -17: 文件已经存在

OSError -17: File already exists

当您在 mkstemp/NamedTemporaryFile 创建的文件上运行它时.

when you run it on the files that mkstemp/NamedTemporaryFile have created.

推荐答案

os.mkfifo() 将失败并出现异常 OSError: [Errno 17] File exists 如果文件已经存在,所以这里不存在安全问题.使用 tempfile.mktemp() 的安全问题是竞争条件,攻击者有可能在您自己打开文件之前创建同名文件,但由于 os.mkfifo() 如果文件已经存在则失败,这不是问题.

os.mkfifo() will fail with exception OSError: [Errno 17] File exists if the file already exists, so there is no security issue here. The security issue with using tempfile.mktemp() is the race condition where it is possible for an attacker to create a file with the same name before you open it yourself, but since os.mkfifo() fails if the file already exists this is not a problem.

但是,由于 mktemp() 已被弃用,因此您不应使用它.您可以使用 tempfile.mkdtemp() 代替:

However, since mktemp() is deprecated you shouldn't use it. You can use tempfile.mkdtemp() instead:

import os, tempfile

tmpdir = tempfile.mkdtemp()
filename = os.path.join(tmpdir, 'myfifo')
print filename
try:
    os.mkfifo(filename)
except OSError, e:
    print "Failed to create FIFO: %s" % e
else:
    fifo = open(filename, 'w')
    # write stuff to fifo
    print >> fifo, "hello"
    fifo.close()
    os.remove(filename)
    os.rmdir(tmpdir)

我应该明确指出,仅仅因为 mktemp() 漏洞被避免了,还有其他常见的安全问题需要考虑;例如攻击者可以在您的程序执行之前创建 fifo(如果他们有合适的权限),如果错误/异常处理不当,这可能会导致您的程序崩溃.

I should make it clear that, just because the mktemp() vulnerability is averted by this, there are still the other usual security issues that need to be considered; e.g. an attacker could create the fifo (if they had suitable permissions) before your program did which could cause your program to crash if errors/exceptions are not properly handled.

这篇关于在 Python 中创建一个临时 FIFO(命名管道)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆