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

查看:1525
本文介绍了在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文档11.6 ,因为已被弃用,可能会被删除。

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

编辑:值得注意的是,我尝试过 tempfile.NamedTemporaryFile (以及扩展名 tempfile.mkstemp ),但 os.mkfifo throws:

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]文件存在如果文件alre ady存在,所以这里没有安全问题。使用 tempfile.mktemp()的安全问题是竞争条件,攻击者可能会在您自己打开之前创建具有相同名称的文件,但由于

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.

但是,由于 os.mkfifo()失败,如果文件已经存在,这不是问题。 c $ c> 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天全站免登陆