Python中传递的Unix套接字凭证 [英] Unix socket credential passing in Python

查看:132
本文介绍了Python中传递的Unix套接字凭证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中完成Unix套接字凭证的传递?

How is Unix socket credential passing accomplished in Python?

推荐答案

有关此主题的Internet搜索结果很少.我想我会在这里发布问题并回答对这个主题感兴趣的其他人.

Internet searches on this topic came up with surprisingly few results. I figured I'd post the question and answer here for others interested in this topic.

以下客户端和服务器应用程序演示了如何在Linux上使用标准python解释器完成此操作.不需要扩展,但是由于使用了嵌入式常量,因此代码是Linux特定的.

The following client and server applications demonstrate how to accomplish this on Linux with the standard python interpreter. No extensions are required but, due to the use of embedded constants, the code is Linux-specific.

服务器:

#!/usr/bin/env python

import struct
from socket import socket, AF_UNIX, SOCK_STREAM, SOL_SOCKET

SO_PEERCRED = 17 # Pulled from /usr/include/asm-generic/socket.h

s = socket(AF_UNIX, SOCK_STREAM)

s.bind('/tmp/pass_cred')
s.listen(1)

conn, addr = s.accept()

creds = conn.getsockopt(SOL_SOCKET, SO_PEERCRED, struct.calcsize('3i'))

pid, uid, gid = struct.unpack('3i',creds)

print 'pid: %d, uid: %d, gid %d' % (pid, uid, gid)

客户:

#!/usr/bin/env python

from socket import socket, AF_UNIX, SOCK_STREAM, SOL_SOCKET

SO_PASSCRED = 16 # Pulled from /usr/include/asm-generic/socket.h

s = socket(AF_UNIX, SOCK_STREAM)

s.setsockopt(SOL_SOCKET, SO_PASSCRED, 1)

s.connect('/tmp/pass_cred')

s.close()

不幸的是,python的套接字模块未导出SO_PEERCRED和SO_PASSCRED常量,因此必须手动输入它们.尽管这些值不太可能更改,但仍有可能.使用此方法的任何应用程序都应考虑这一点.

Unfortunately, the SO_PEERCRED and SO_PASSCRED constants are not exported by python's socket module so they must be entered by hand. Although these value are unlikely to change it is possible. This should be considered by any applications using this approach.

这篇关于Python中传递的Unix套接字凭证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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