我们可以利用 file(1) 实用程序附带的 libmagic.so 库。它可以检测所有可执行文件,如 ELF、bash/python/perl 脚本等
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "magic.h"
int
main(int argc, char **argv)
{
struct magic_set *ms;
const char *result;
char *desired;
size_t desired_len;
int i;
FILE *fp;
ms = magic_open(MAGIC_RAW);
if (ms == NULL) {
(void)fprintf(stderr, "ERROR opening MAGIC_NONE: out of memory\n");
return -1;
}
if (magic_load(ms, NULL) == -1) {
(void)fprintf(stderr, "ERROR loading with NULL file: %s\n", magic_error(ms));
return 11;
}
if (argc > 1) {
if (argc != 2) {
(void)fprintf(stderr, "Usage: ./a.out </path/to/file>\n");
} else {
if ((result = magic_file(ms, argv[1])) == NULL) {
(void)fprintf(stderr, "ERROR loading file %s: %s\n", argv[1], magic_error(ms));
return -1;
} else {
if (strstr(result, (const char *)"executable")) {
printf("%s: is executable\n", argv[1], result);
}
}
}
}
magic_close(ms);
return 0;
}
$ gcc test.c -I/path/to/magic.h /usr/lib/libmagic.so.1
./a.out /bin/ls
./a.out a.out
./a.out test.c