[英]Why is C stdout not returning “ls” command content?
我一直在研究反向 shell(不用於惡意用途),並開始學習如何使用 popen function 並使用 stdout 獲取 Z78E6221F6393D13566811DB398F14CE6DZ。 我已經開始測試它,它工作正常,直到我嘗試使用終端命令“ls”。 誰能指出(我假設是)我的錯誤並告訴我如何解決它?
這是 C 程序的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
while (1){
char* command = (char *) malloc(15*sizeof(char));
char* output = (char *) malloc(2048);
printf(">> ");
scanf("%s", command);
FILE* cmd = popen(command, "r");
fputs(output, stdout);
pclose(cmd);
if (strlen(output) != 0){
printf("\n%s\n", output);
}
}
}
這是我提供的程序的輸入代碼,它的結果是:
>> cd /Users/
sh: /Users/: is a directory //output from previous command
>> >> ls //also why did the program print '>>' twice?
>>
另一個問題:為什么程序打印>>
兩次?
該代碼似乎缺少popen()
(實際上是cmd
)和output
變量之間的連接。 例如,您可以使用fread()
從cmd
“文件”讀取到output
。
調用scanf("%s", ...)
將一次只掃描一個以空格分隔的單詞。 您的程序首先運行cd
,然后在下一次迭代中運行/Users/
。
該代碼通過在while
循環中重復分配緩沖區command
和output
而不free
它們來泄漏 memory。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.