我想编写一个java程序,打开一些在每个终端“cd go / to / a / specitic / folder”中执行的终端。 (我不想执行批处理/脚本/ shell文件。)
如果这些可能是平台独立的话会很棒。目前我正在使用mac。
我在网上搜索了一个洞周末,并尝试使用netbeans进行x次尝试,但没有一个积极的结果。我发现一次接近尝试http://www.coderanch.com/t/532229/java/java/Writing-terminal-Java-program。
我尝试的最佳代码是:
public class NewClass1 {
public static void main(String[] args) {
try {
Desktop.getDesktop().open(new File("/Applications/Utilities/Terminal.app"));
} catch (IOException ex) {
Logger.getLogger(StartDevelop.class.getName()).log(Level.SEVERE, null, ex);
}
// opens a terminal but no comments / parameters could be used
}
}
另一个尝试是通过以下方式更改主要部分中的所有代码:
ProcessBuilder builder = new ProcessBuilder(
"/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal");
builder.redirectErrorStream(true);
try {
String command = "ls -lai";
Process process = builder.start();
BufferedReader read = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String s;
while ((s = read.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e1) {
// TODO Auto-generated catch block
System.out.println(e1);
}
//open a terminal but command is executed in terminal
和另一种选择:
try {
String command = "ls -lai";
Process process = Runtime.getRuntime().exec(command);
BufferedReader read = new BufferedReader(new InputStreamReader(process.getInputStream()));
String s;
while ((s = read.readLine()) != null) {
System.out.println(s);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
System.out.println(e1);
}
// works with output in netbeans
// but no terminal is opening
我还尝试使用输出编写器:
BufferedWriter outWrite = new BufferedWriter(
new OutputStreamWriter(process.getOutputStream(), command));
outWrite.flush();
outWrite.newLine();
但没有效果。
提前致谢。
答案 0 :(得分:1)
库皮,
你需要“SSH for Java”。
它提供的不仅仅是你需要的。
以下是其他Java SSH库的列表,其中包括:http://linuxmafia.com/ssh/java.html。
我建议使用Ganymed SSH因为它被广泛使用并且在BSD许可下(你不需要开源代码)。
也许您希望更好地控制登录/密码信息。在Java代码中对登录名和密码进行硬编码是一个坏主意,原因有两个:
- 密码不应以明文形式存储(每个获得程序的人都可以访问您的服务器。即使是编译过的Java类也会包含明确的登录名和密码字符串。这不是您想要的)
- 如果密码被更改,您不想更改Java程序
您可以在要连接的主机上生成密钥对,然后交换密钥。关于此here的更多信息 。因此,不会询问您配置的主机的登录名和密码。
祝你好运。答案 1 :(得分:0)
简短回答:你不能。
答案很长:问题是,即使你成功调用了终端,你也需要知道每个终端的tty是什么,这意味着你需要知道它的stdin是什么......操作系统没有做一些奇怪的机制,这使得终端甚至不使用文件描述符0,1和2用于stdin,stdout和stderr。
即使你能做到这一点,你也需要能够写入tty。
答案 2 :(得分:0)
如果您不需要对终端窗口进行交互式访问,则可以动态创建shell脚本并使用xterm运行脚本。
示例:
xterm -e path-to-script.sh
要在执行后保持应用程序打开,请使用-hold
选项。
简约示例:
echo "echo hello;/bin/bash" > /tmp/tmp123.sh; chmod +x /tmp/tmp123.sh;xterm -hold -e /tmp/tmp123.sh
为了完整性,这就是在Windows上完成的方法(用您要执行的命令替换echo hello
):
start cmd /C echo hello
要在执行后保持窗口打开,请使用/K
选项而不是/C
。