Python 只需调用uname 系统调用来获取该信息,它总是会返回有关当前运行内核的信息。在不修改源的情况下覆盖返回值会很棘手。
您可以使用函数插入来完成此操作,例如如here 所述。这需要修改镜像以同时包含包装库和必要的环境设置,或者需要您在 Docker 运行命令行上传递一些额外的参数。
这是一个简单的例子。我从一个香草图像开始,并在 Python 中调用 os.uname():
$ docker run -it --rm fedora python3
Python 3.6.2 (default, Sep 1 2017, 12:03:48)
[GCC 7.1.1 20170802 (Red Hat 7.1.1-7)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.uname()
posix.uname_result(sysname='Linux', nodename='fd2d40cb028b', release='4.13.15-100.fc25.x86_64', version='#1 SMP Tue Nov 21 22:45:32 UTC 2017', machine='x86_64')
>>>
我希望 release 字段改为显示 1.0.0。我首先为uname 系统调用创建一个包装器:
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <string.h>
#include <sys/utsname.h>
/* Function pointers to hold the value of the glibc functions */
static int (*real_uname)(struct utsname *name) = NULL;
/* wrapping write function call */
int uname(struct utsname *name) {
int res;
real_uname = dlsym(RTLD_NEXT, "uname");
res = real_uname(name);
if (res == 0) {
memset(name->release, 0, _UTSNAME_RELEASE_LENGTH);
strncpy(name->release, "1.0.0", 5);
}
return res;
}
然后我编译共享库:
$ gcc -fPIC -shared -o wrap_uname.so wrap_uname.c -ldl
现在我可以将其注入 docker 映像并预加载共享库。关键添加是 -v 注入库和 -e LD_PRELOAD 导致链接器预加载它:
$ docker run -it --rm \
-v $PWD/wrap_uname.so:/lib/wrap_uname.so \
-e LD_PRELOAD=/lib/wrap_uname.so fedora python3
如您所见,这给了我们想要的结果:
Python 3.6.2 (default, Sep 1 2017, 12:03:48)
[GCC 7.1.1 20170802 (Red Hat 7.1.1-7)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.uname()
posix.uname_result(sysname='Linux', nodename='dd88d697fb65', release='1.0.0', version='#1 SMP Tue Nov 21 22:45:32 UTC 2017', machine='x86_64')
>>>