测试环境 centos7 python3.6.5
首先使用c创建内存,这里的方法是:作为参数读一个二进制数据文件进去,把文件的内容作为共享内存的内容
定义块
#include <stdio.h>
#include <sys/shm.h>
#include <string.h>
int main(int argc, char *argv[])
{
int id = 0;
char *data = NULL;
FILE *fp = NULL;
int totle_len = 0;
int len = 0;
char buf[1024] = {0};
if (argc < 2)
{
printf("args too less\n");
return 0;
}
id = shmget(123559, 21 * 1024 * 1024, IPC_CREAT | 0777);
if (id < 0)
{
printf("get id failed\n");
return 0;
}
data = shmat(id, NULL, 0);
if (data == NULL)
{
printf("shamt failed\n");
return 0;
}
fp = fopen(argv[1], "rb");
if (fp == NULL)
{
printf("open %s failed\n", argv[1]);
return 0;
}
while (totle_len <= 12 + 20 * 1024 * 1024)
{
len = fread(buf, 1, 1024, fp);
if (len <= 0)
{
break;
}
memcpy(data + totle_len, buf, len);
totle_len += len;
}
fclose(fp);
return 0;
}
使用python读取:
from ctypes import *
import numpy as npimport codecs
import datetime
SHM_SIZE = 1024*1024*20
SHM_KEY = 123559
OUTFILE="httpd_cdorked_config.bin"
try:
rt = CDLL('librt.so')
except:
rt = CDLL('librt.so.1')
shmget = rt.shmget
shmget.argtypes = [c_int, c_size_t, c_int]
shmget.restype = c_int
shmat = rt.shmat
shmat.argtypes = [c_int, POINTER(c_void_p), c_int]
shmat.restype = c_void_p
shmid = shmget(SHM_KEY, SHM_SIZE, 0o666)
if shmid < 0:
print ("System not infected")
else:
begin_time=datetime.datetime.now()
addr = shmat(shmid, None, 0)
f=open(OUTFILE, 'wb')
rate=int.from_bytes(string_at(addr,4), byteorder='little', signed=True) #这里数据文件是小端int16类型
len_a=int.from_bytes(string_at(addr+4,4), byteorder='little', signed=True)
len_b=int.from_bytes(string_at(addr+8,4), byteorder='little', signed=True)
print(rate,len_a,len_b)
f.write(string_at(addr+12,SHM_SIZE))
f.close()
#print ("Dumped %d bytes in %s" % (SHM_SIZE, OUTFILE))
print("Success!",datetime.datetime.now()-begin_time)
块的大小和块号可以设置,注意读取的时候 二进制文件的数据格式要保持一致否则读不出来正确的东西