我正在尝试使用以下代码从Java运行Unix命令:
// Initialize a ConnBean object, parameter list is ip, username, password
ConnBean cb = new ConnBean("servername", "username","");
// Put the ConnBean instance as parameter for SSHExec static method getInstance(ConnBean) to retrieve a singleton SSHExec instance
SSHExec ssh = SSHExec.getInstance(cb);
// Connect to server
Boolean isConnected = ssh.connect();
String[] commands = new String[]{"sudo echo 'Hello command!.' > ChenTest.txt"};
CustomTask sampleTask = new ExecCommand(commands);
try {
Result result = ssh.exec(sampleTask);
} catch (TaskExecFailException e) {
System.out.println(e);
}
catch (Exception e) {
System.out.println(e);
}
当我调试我的应用程序时,出现“验证失败”的提示。
我知道我的服务器和用户名正确,但是不确定为什么我无法连接。
我在此Unix服务器上有一个密钥。是否需要在代码中添加它以使连接成功?
最佳答案
看起来您正在使用公共密钥而不是密码进行连接。
为此,我认为您需要配置SSHExec才能知道密钥文件所在的位置。
我不是Java专家,但我认为您需要这样的东西:
SSHExec.setOption("keyfile", "/home/user/.ssh/id_dsa.pub");
您的密钥文件将有所不同。