将控制字符发送到 Java 中的外部进程 [英] sending control charactors to external process in Java
问题描述
我使用以下命令连接到 ubuntu 中的/bin/bash":
I am connecting to "/bin/bash" in ubuntu using:
process = Runtime.getRuntime().exec(cmd);
这里的 cmd 是一个字符串,其中包含我从进程中读取和写入的不同命令.
现在我遇到了一种情况,我使用 ssh 登录到远程机器,在读取写入信息到 ext 进程时,要从远程机器注销,我必须发送控制字符,如:
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 + ]
以优雅地注销会话并返回到我的本地机器.假设 cmd 是 String 类型,我如何将这个 CTRL
字符写入进程?
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?
推荐答案
Control-] 在 ASCII 中相当于 035 八进制.在 Java 中,您可以将其表示为\035".
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();
它也等价于十进制值 29,所以如果你可以写一个值为 29 的字节,那么它也能工作.
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();
我认为 Control-]
与远程程序有关.你说的是telnet?但是写exit\n"也会关闭远程bash.
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();
显然,您也可以关闭 OutputStream
,它会关闭远程进程的 STDIN.
You can also, obviously, close the OutputStream
which closes the STDIN of the remote process.
os.close();
这篇关于将控制字符发送到 Java 中的外部进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!