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

3
我正在尝试使用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();

我想知道为什么会这样?


当您在shell中键入带有>file等命令时,shell会在运行程序之前执行重定向。Java Runtime.exec()不执行重定向。要么(1)从Process.getInputStream()读取并自己写入文件;(2)使用ProcessBuilder.redirectOutput()进行重定向;或者(3)使用.exec(String...)重载来运行例如sh-c一起作为单个参数的整个命令行,然后shell解析和处理它。 - dave_thompson_085
你能分享一个样例吗? - sunny
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接