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

标签 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代码中调用脚本?

提前谢谢您。

最佳答案

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

chmod +x eth0script.sh

关于c - 如何在C中的cgi编程中调用外部bash shell脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28956261/

相关文章:

c - 在函数中初始化的结构如何使用这些值?

linux - Gnu Plot 中百分比的位置和大小不正确

perl - Perl 中的 "CGI::param called in list context"警告

bash - 如何防止命令出现在 Bash 历史记录中?

mysql - CGI语言选择

c - 如何在 ubuntu 上编译内核 3.14(从 kernel.org 下载)

c - 是否有必要检查无符号 8 位整数的字节顺序?

我不能将 4294967295 存储在 unsigned int 中吗? Int 在我的机器上是 4 个字节

java - 启动Mule进行远程调试,无需修改wrapper.conf

linux - 尾部-f + grep?