Java中的ssh-keygen命令从私钥中提取公钥

时间:2016-07-06 20:49:54

标签: java ssh ssh-keygen

我尝试使用Java的Runtime.getRuntime()。exec()来使用ssh-keygen linux实用程序从私钥中解压缩公钥。

当我在终端上运行此命令时,它运行完美,并且我能够从RSA私钥中提取公钥

ssh-keygen -y -f /home/useraccount/private.txt > /home/useraccount/public.txt

但是当我使用Java运行相同的命令时,它不会创建public.txt文件。它也不会抛出任何错误。

Process p = Runtime.getRuntime().exec("ssh-keygen -y -f /home/useraccount/private.txt > /home/useraccount/public.txt");
p.waitFor();

我想知道为什么会这样?

1 个答案:

答案 0 :(得分:0)

不是真正的答案,因为我不需要时间测试,但基本选项:

// example code with no exception handling; add as needed for your program

String cmd = "ssh-keygen -y -f privatefile";
File out = new File ("publicfile"); // only for first two methods

//// use the stream ////
Process p = Runtime.exec (cmd);
Files.copy (p.getInputStream(), out.toPath());
p.waitFor(); // just cleanup, since EOF on the stream means the subprocess is done

//// use redirection ////
ProcessBuilder b = new ProcessBuilder (cmd.split(" "));
b.redirectOutput (out);
Process p = b.start(); p.waitFor();

//// use shell ////
Process p = Runtime.exec ("sh", "-c", cmd + " > publicfile");
// all POSIX systems should have an available shell named sh but 
// if not specify an exact name or path and change the -c if needed 
p.waitFor();