有没有办法通过网络完全控制终端。例如,我有一个用 C 编写的服务器和客户端,我想向服务器(在这种情况下服务器是一台 linux 计算机)发送一个类似rm file
或的命令并将终端输出返回给客户端。cd directory
我目前正在使用ls
usingpopen()
但它无法更改目录或执行其他复杂命令。有没有更好的方法来做到这一点,也许使用fork()
pipe()
和其他功能来使用任何命令并从终端获取完整输出。
3 回答
What you ask for is done by SSH.
For example, I have a server and client written in C, I want to send a command like rm file or cd directory to the server (server in this case is a linux computer) and get the terminal output back to the client.
I strongly discourage to implement such a functionality yourself. The odds are high, that your own approach will have several security issues.
SSH is the de-facto standard for remote terminals, has strong encryption, real world tested authentication and strong maintenance support. Also there are excellent open source implementations, like OpenSSH.
Not sure what your exact set-up is, but why not just fork off a shell on the remote side? You can then do anything that can be done from the commandline.
If a real, interactive connection is an option, look into pty's ("pseudo-ttys"). It's how real terminal applications work.
如果您可以从中获得输出,ls
那么您就走在了正确的道路上。
接下来是能够发送输入,与输出没有太大区别。您可以使用该命令cat
同时检查输入和输出是否正确。
然后,只需运行您喜欢的 shell 命令,例如bash
,您就可以将命令写入输入流并读取每个命令的输出。
请注意,这cd
不是程序;它是一个 shell 命令,所以你必须运行一个 shell 才能让它有任何意义。重定向和您似乎想要做的其他复杂性也是如此。
PS:请注意,这可能是一个严重的安全问题,您应该认真考虑已经制作的替代方案,例如 ssh,正如其他人所说。