如何在C语言中调用cgi编程中的外部bash shell脚本

时间:2015-03-10 04:36:44

标签: c bash cgi sh fastcgi

我想在用c编写的cgi程序中调用外部shell脚本。

我在cgi代码中使用了system()命令。代码是

#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;
  }

cgi代码和shell脚本位于同一文件夹中。

脚本是

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

我如何调用cgi代码中的脚本?

提前谢谢。

1 个答案:

答案 0 :(得分:0)

我测试了你的代码,我可以使用system()调用shell脚本eth0script.sh,没有任何问题。 不要忘记使脚本可执行以避免“权限被拒绝”:

chmod +x eth0script.sh