2016-07-06 5 views
2

JavaのRuntime.getRuntime()。exec()をに設定しようとしています。ssh-keygen linuxユーティリティを使用して公開鍵を秘密鍵から抽出します。秘密鍵から公開鍵を抽出するためのJavaのssh-keygenコマンド

私は、端末上でこのコマンドを実行すると、それは完璧に動作し、私はRSA秘密鍵

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

から公開鍵を抽出することができるよしかし、私はJavaを使用して同じコマンドを実行すると、それは作成されません。 public.txtファイル。それでもエラーは発生しません。

私はなぜそれが不思議ですか?

+0

は、シェルは実行する前に、リダイレクトを行いますプログラム。 Javaの 'Runtime.exec()'はリダイレクトを行いません。 (1) 'Process.getInputStream()'から読み込んで自分自身にファイルに書き込むか、 (2) 'ProcessBuilder'と' .redirectOutput() 'を使ってリダイレクトを行います。または(3) '.exec(String ...)'オーバーロードを使用して実行します。 'sh 'を' -c'で置き換え、シェルが次に解析して扱うコマンドライン全体を(単一の引数として)! –

+0

サンプルを共有できますか? – sunny

答えて

0

そうでもない答え私はテストする時間が、基本的なオプションを持っていないので:shell_を_toあなたは `> file`などでコマンドを入力すると

// 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(); 
関連する問題