gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:19:07 30 4
gpt4 key购买 nike

我想在用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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com