2016-07-06 97 views
2

我想使用ssh-keygen linux实用程序从私钥中使用Java的Runtime.getRuntime().exec()到提取公钥。在Java中的ssh-keygen命令从私钥中提取公钥

当我运行在终端命令,它的工作完美无瑕,我能够从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(); 

我想知道为什么?

+0

当你输入用'> file'等命令_TO一个shell_,shell就运行前的重定向该程序。 Java'Runtime.exec()'不执行重定向。 (1)从'Process.getInputStream()'中读取并自己写入文件; (2)使用'ProcessBuilder'和'.redirectOutput()'来做重定向;或(3)使用'.exec(String ...)'重载运行例如''sh'带'-c'和(作为单个参数!)shell然后解析和处理的整个命令行。 –

+0

你能分享一个样本吗? – sunny

回答

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();