2016-07-06 94 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();