【问题标题】:How to call external bash shell script inside cgi programming in C如何在 C 中的 cgi 编程中调用外部 bash shell 脚本
【发布时间】:2015-05-11 10:48:59
【问题描述】:

我想在用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()
  • 是的..在主要内部我使用 system()system("/home/usr/webserver/eth0script.sh"); 调用外部脚本;
  • execve 这样的 exec 派生词也应该可以工作。
  • 那么你的问题是什么?
  • 我在 cgi 代码中使用了那个 system() 代码。然后我编译了代码并将编译后的代码放在 cgi-bin 文件夹(apache2 服务器)中。使用 webbrowser 我运行可执行代码。但是那个时候 system() 调用不起作用。

标签: c bash cgi sh fastcgi


【解决方案1】:

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

chmod +x eth0script.sh

【讨论】:

  • 使用 ./cgi-code 正在工作。但是我编译了代码并将可执行文件放在apache2的cgi-bin中。它不起作用
  • 你有没有试过在编译cgi-code后为所有OS用户更改可执行cgi-code和脚本的文件权限? chmod a+x cgi-code
猜你喜欢
  • 2010-11-15
  • 1970-01-01
  • 2014-11-12
  • 1970-01-01
  • 2014-01-17
  • 2015-11-25
  • 1970-01-01
  • 2018-06-06
  • 1970-01-01
相关资源
最近更新 更多