在Java中向外部进程发送控制字符

发布于 2024-12-20 23:54:21 字数 322 浏览 1 评论 0原文

我正在使用以下方式连接到 ubuntu 中的“/bin/bash”:

process = Runtime.getRuntime().exec(cmd);

这里 cmd 是一个字符串,其中包含我从进程中读取和写入的不同命令。
现在我遇到了一种情况,我使用 ssh 登录到远程机器,并在读取写入信息到 ext 进程时,为了从远程机器注销,我必须发送控制字符,例如:

CTRL + ]为了优雅地注销会话并返回到我的本地计算机。假设cmd是String类型,我如何将这个CTRL字符写入进程?

I am connecting to "/bin/bash" in ubuntu using:

process = Runtime.getRuntime().exec(cmd);

Here cmd is a String with different commands that i read and write from process.
Now i have come across a situation, where i login to remote machiens using ssh and while reading writing information to ext process, for loggin out from remote machine, i have to send control character like:

CTRL + ] in order to logout the session gracefully and come back to my local machine. Assuming the cmd is a String type, how can i write this CTRL chracter to the process?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

昇り龍 2024-12-27 23:54:21

ASCII 中的 Control-] 相当于八进制的 035。在 Java 中,您可以将其表示为“\035”。

Writer writer = new OutputStreamWriter(process.getOutputStream());
writer.write("\035");
writer.flush();

它也相当于十进制值 29,因此如果您可以写入值为 29 的字节,那么也可以。

OutputStream os = process.getOutputStream();
os.write(29);
os.flush();

我假设 Control-] 与远程程序有关。你说的是telnet吗?然而,写入“exit\n”也会关闭远程 bash。

Writer writer = new OutputStreamWriter(process.getOutputStream());
writer.write("exit\n");
writer.flush();

显然,您还可以关闭OutputStream,从而关闭远程进程的STDIN。

os.close();

Control-] in ASCII is equivalent to 035 octal. In Java you can represent this as "\035".

Writer writer = new OutputStreamWriter(process.getOutputStream());
writer.write("\035");
writer.flush();

It is also equivalent to decimal value of 29 so if you can write a byte with a value of 29 then that will work as well.

OutputStream os = process.getOutputStream();
os.write(29);
os.flush();

I assume Control-] has to do with the remote program. You are talking about telnet? However writing "exit\n" will also close the remote bash.

Writer writer = new OutputStreamWriter(process.getOutputStream());
writer.write("exit\n");
writer.flush();

You can also, obviously, close the OutputStream which closes the STDIN of the remote process.

os.close();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文