安装Apache Server
apache server下载地址:
https://archive.apache.org/dist/httpd/
https://www.apachelounge.com/download/win64/
步骤:
1.下载并解压文件到C:\Apache24路径。
2.打开命令行,cd到C:\Apache24\bin目录下,执行httpd.exe -k install命令安装apache服务
3.打开conf/httpd.conf文件修改配置
监听8080端口
配置管理员邮箱
配置域名
4.在命令行窗口执行httpd指令启动服务器
在浏览器访问:localhost:8080,如果显示It works!表示安装成功。
如果端口被占用,则使用netstat -ano命令查看占用端口的进程的pid,并结束该进程,或者修改监听端口的配置。
如果是msi安装文件则直接安装后,打开bin/ApacheMonitor.exe即可。
相关目录介绍:
1.bin:执行文件目录
2.cgi-bin:cgi文件目录
3.conf:配置
4.error:错误
5.htdocs:网站根目录
6.icons:图标
7.logs:日志
8.manual:手册
9.modules:模块(动态库)文件目录
配置开启CGI功能
1.解除处理CGI程序的注释
2.增加CGI设置项:Options Indexes ExecCGI
Hello CGI
开发环境说明:win7、VS2012
1.编写C/C++程序源码
#include <stdio.h>
void main(){
printf("Context-type:text/html; \n\n");
printf("<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">");
printf("<html><head>");
printf("<title>Hello CGI</title>");
printf("</head><body>");
printf("<p>Hello CGI</p>");
printf("</body></html>");
}
2.编译源码,把生成的exe文件复制到cgi-bin目录下,并修改后缀名为.cgi。
3.在浏览器中访问cgi文件
http://localhost:8080/cgi-bin/hello.cgi
注意:
1.输出的内容将会作为网页源码显示,所以输出的内容要符合html标准。
2.在控制台输出的”\n”不网页上显示是不起到换行的作用的,可以通过输出”<br />”来实现换行。
3.在logs目录可以查看相关日志信息。
错误:
1.Premature end of script headers: hello.cgi
hello.cgi输出的内容过早结束脚本头。检查输出内容是否符合html标准。
实现远程控制电脑
1.在htdocs目录下添加一个cmd.html文件,用于提交命令,源码如下:
<form method="post" action="http://localhost:8080/cgi-bin/cmd.cgi">
<input type="text" size="35" name="cmd" value="tasklist" />
<input type="submit" name="submit" value="执行" />
</form>
2.C程序源码
思路
(1).获取从html中表单提交过来的参数并替换部分字符串,如+需要换成空格,%2F换成/。
(2).执行相关命令,并把结果输出内存中的文件对象。
(3).把执行结果显示到网页。
#define _CRT_SECURE_NO_WARNINGS //忽略安全警告
#include
#include "string.h"
#include "strlib.h"
void main(){
printf("Context-type:text/html; \n\n");
printf("");
// 打印环境变量
printf("
%s
", getenv("Path"));
// 获取提交的参数
char params[256] = {0};
gets(params);//获取输入
printf("
params=%s
",params);
CString str;
strInitWithStr(&str,params);
// 替换&符号为空字符
strReplaceAllChar(&str, '&', '\0');
// 替换+符号为空格符
strReplaceAllChar(&str, '+', ' ');
// %2F换成斜杠
strReplaceAllStr(&str, "%2F", " /");
// 查找cmd
char* pCmd = strFind(str.data,"cmd=");
printf("
data=%s
",str.data);
if (pCmd) //如果发现cmd参数
{
printf("发现命令\"%s\"。
", pCmd+4,str.length, str.size);
// 执行命令,并打印输出
FILE* pipe = _popen(pCmd+4, "r"); // 第一个参数是指令字符串,第二个参数是模式(r:读,w:写)
// _popen函数用于执行一条指令并把结果输出到内存中的文件对象
if (!pipe)
{
printf("该命令无输出。
");
return ;
}
printf("
");
// 把执行结果输出到网页
char ch = 0;
while(!feof(pipe)){
ch = fgetc(pipe);
// 把'\n'换行符换成网页中的换行符
if (ch == '\n')
{
printf("
");
}
else{
putchar(ch);
}
}
}else{
printf("未发现命令。
");
}
printf("");
}
3.编译生成exe执行文件,复制exe文件到cgi-bin目录下,并修改后缀名为cgi。如:cmd.exe --> cmd.cgi。
4.在浏览器中访问http://localhost:8080/cmd.html,提交命令。