简体   繁体   中英

How to call external bash shell script inside cgi programming in C

I want to call an external shell script inside the cgi program written in c.

I used system() command inside the cgi code. The code is

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include<stdlib.h>

#define MAXLEN 1024
#define CONFIG_FILE "/home/usr/webserver/properties.cfg"


char *trim (char * s)
{

  char *s1 = s, *s2 = &s[strlen (s) - 1];
  while ( (isspace (*s2)) && (s2 >= s1) )
  s2--;
  *(s2+1) = '\0';
  while ( (isspace (*s1)) && (s1 < s2) )
  s1++;

  strcpy (s, s1);
  return s;
  }

  void parse_config ()
  {
   char *s, buff[1024];

   int i,j;
   FILE *fp = fopen (CONFIG_FILE, "r");
   if (fp == NULL)
   {
     printf("reached");
     return;
   }

     /* Read next line */
   while ((s = fgets (buff, sizeof buff, fp)) != NULL)
 {

/* Skip blank lines and comments */
if (buff[0] == '\n' || buff[0] == '#')
  continue;

/* Parse name/value pair from line */
char name[MAXLEN], value[MAXLEN],arr[]={0} ;
char new_str[MAXLEN+1] = {0};   
s = strtok (buff, "=");
if (s==NULL)
  continue;
else
  strncpy (name, s, MAXLEN);
s = strtok (NULL, "=");
if (s==NULL)
  continue;
else
  strncpy (value, s, MAXLEN);
trim (value); 
i= strlen(value);
if(value[0]!='"')
strncpy(new_str,value,MAXLEN);

else
strncpy(new_str, &value[1], i-2);

printf("<tr><td>%s</td><td><input type = \"text\" name =%s value=%s>",name,name,value);
printf("</td> </tr>");


}

 fclose (fp);
}


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

  char *test="hello";
  char *data;
  char ADDRESS;
    system("/home/usr/webserver/eth0script.sh"); 
  printf("Content-Type: text/html\n\n");
  printf("<html>\n");
  printf("<head>\n");
  printf("</head>\n");
  printf("<body>\n");


  printf("<form action =\"/cgi-bin/final.cgi\" method =\"POST\">");
  printf("<table style=\"width:100%\">");
  parse_config ();
  printf(" </table>");
  printf("<input type =\"submit\" name = \"submit\" value = \"submit\"></form>");
  printf("</body>\n");
  printf("</html>\n");
  return 0;
  }

The cgi code and shell script is in same folder.

The script is

 #! /bin/bash
 sed -i "s/\b\DEFAULT_INTERFACE=\b.*/DEFAULT_INTERFACE=$(ifconfig -a |   awk '/eth/ {print $1}')/g" /home/usr/webserver/properties.cf

How I call the script inside the cgi code ??

Thank you in advance.

I tested your code and I can call the shell script eth0script.sh using system() with no problems. Don't forget to make the script executable to avoid "Permission denied":

chmod +x eth0script.sh

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM