【发布时间】:2014-01-31 21:26:19
【问题描述】:
我想在本地计算机上执行 ssh-keygen。但是当我运行下面的代码时,ssh-keygen 只运行到:
Generating public/private rsa key pair.
Enter file in which to save the key (/cygdrive/c/Users/USER/.ssh/id_rsa):
BUILD SUCCESSFUL (total time: 0 seconds)
//ssh-keygen execution stop at here only.
我想要的结果是这样的:
生成公钥/私钥 rsa 密钥对。
输入保存密钥的文件(/cygdrive/c/Users/USER/.ssh/id_rsa)://按回车
Enter passphrase (empty for no passphrase): //按回车
再次输入相同的密码://按回车
//http://commons.apache.org/proper/commons-exec/tutorial.html
import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
public class ApacheRunSSHKEygen {
public static void main(String[] args) throws IOException {
try {
String line = "C:\\ExecuteSSH\\ssh-keygen.exe"; // path to ssh-keygen.exe
CommandLine cmdLine = CommandLine.parse(line);
DefaultExecutor executor = new DefaultExecutor();
//watchdog
executor.setExitValue(1);
ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
executor.setWatchdog(watchdog);
int exitValue = executor.execute(cmdLine); //execute ssh-keygen
}
catch (Exception exc){
System.out.println("error" + exc);/*handle exception*/}
}
}
我的代码实际上有什么问题。如何正确运行 ssh-keygen?提前感谢您的帮助。
【问题讨论】:
-
为什么不在纯 Java 中尝试这样做呢?请参阅this question 获取指导。
-
谢谢你,迈克,但我仍然需要弄清楚这一点。实际上有什么问题。我怀疑问题来自这里 String line = "C:\\ExecuteSSH\\ssh-keygen.exe"; // s 的路径 ssh-keygen.exe CommandLine cmdLine = CommandLine.parse(line); DefaultExecutor 执行者 = 新的 DefaultExecutor();也许代码只允许执行很少的输出行。
-
我建议使用纯 Java 方法,因为脱壳运行其他程序有很多缺点。一方面,您正在编写不可移植的代码。你的代码只能在运行 Cygwin 的 Windows 机器上运行,你的
ssh-keygen.exe在C:\ExecuteSSH中。此外(只是在这里进行理论化)ssh-keygen.exe可能会尝试直接从终端读取以获取密码,绕过标准输入/输出流,因此它会在您必须输入密码时停止。不过,我没有在您的代码中看到您代表用户按<enter>的部分。