监控 某个目录下文件的创建,给据创建的文件进行执行命令

接触 linux c 时间不长, 多的不说了,好多大神写的都好的很,在这里就淡淡的记录一下,直接上代码:

  

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/inotify.h>

#include "inite.h"


extern int StartProgram(const char *program);

int MonitorFolder(const char *dir)
{
	int init_fd = 0;
	int watch_fd = 0;
	init_fd = inotify_init();
  
  	if ( init_fd < 0 ) {
   		perror( "inotify_init() Error! \n" );
  	}
  
  	watch_fd = inotify_add_watch( init_fd , dir, IN_CREATE );

  	while (1) {
  		
  		int length=0;
  		int i = 0;
  		char buffer[BUF_LEN];
  		 
  		length = read( init_fd , buffer, BUF_LEN );
		if ( length < 0 ) {
    		perror( "read ....." );
  		}
  			
   		while ( i < length ) { 		
  			struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ];
     		if ( event->len ) {
       			if ( event->mask & IN_CREATE ) {
           			if ( event->mask & IN_ISDIR ) {
        	      	 	//printf( "The directory %s was created.\n",  event->name);
        	   		}else {
        	      		if(strstr(event->name,STOP_SYSTEM)){
							StartProgram("ls -l / > lsl.log");
						}
        	      		else if(strstr(event->name,STOP_SLSYSTEM)){
							StartProgram("ps -aux > ps.log");
						}
        	      		else if(strstr(event->name,STOP_JACKHISYSTEM)){
							StartProgram("ps -e > pse.log");
						}
        	      		else if(strstr(event->name,START_IMPLANT)){
							StartProgram("date  > date.log");
						}
        	      		else if(strstr(event->name,STOP_IMPLANT)){
							StartProgram("tar -cf tmp.tar ./*");
						}
        	      		else if(strstr(event->name,RESTART_IMPLANT)){
							StartProgram("ftp 192.168.1.122 > ll.log");
						}
					}
				}
			}
    		i = EVENT_SIZE event->len;
			
	//		sleep(1);
  		}			
 	}
  		
  	( void ) inotify_rm_watch( init_fd, watch_fd );
  	( void ) close( init_fd );
  		
  	return 0;
}

int main(int argc, char **argv) {

	if (argc != 2) {  
    	  printf("Usage: %s <file/dir>\n", argv[0]);  
    	  return -1;  
  	}

  	strcpy(Directory,argv[1]);
  	
	MonitorFolder(Directory);
	return 0;
}

  

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <ctype.h>

pthread_mutex_t mut;
pthread_t thread[2];
char dir[100]={0};

void *Execl_Sh(void *);
 
void *Execl_Sh(void *tmp)
{
	if(system(dir) < 0)
		return
		
}

void thread_create()
{
    int temp = 0;
	memset(&thread,0,sizeof(thread));
	
	if(temp=pthread_create(&thread[0],NULL,Execl_Sh,NULL)!=0)
          printf("create Execl_Sh failed!\n");
	else
          printf("create Execl_Sh successed!\n");
}

int StartProgram(const char *program)
{
	strcpy(dir,program);
	thread_create();	
	pthread_join(thread[0],NULL);
	return 0;
}

  

原文地址:https://www.cnblogs.com/nobileamir/p/2568810.html