I write this program that checks if a file is executable, and if so, to check if it is an ELF binary or a shell script.
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
int Search_in_File(char *fname, char *str);
int main(int argc, char **argv)
{
if(argc < 2){
printf("The path to the file is\n");
return 1;
}
struct stat fileStat;
if(stat(argv[1],&fileStat) < 0){
printf("error\n");
return 1;
}
if(S_ISREG(fileStat.st_mode)){
if(fileStat.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
{
printf("The file is executable ");
Search_in_File(argv[1], "#!");
Search_in_File(argv[1], "ELF");
}
else
{
printf("The file is not executable.\n");
}
}
else
printf("Not a file\n");
return 0;
}
int Search_in_File(char *fname, char *str) {
FILE *fp;
char temp[512];
if((fp = fopen(fname, "r")) == NULL) {
return(-1);
}
while(fgets(temp, 512, fp) != NULL) {
if((strstr(temp, str)) != NULL) {
if(strcmp(str, "#!")==0)
printf("shell type.");
else if(strcmp(str, "ELF")==0)
printf(" ELF.");
}
}
printf("\n");
if(fp) {
fclose(fp);
}
return(0);
}