在 J2SSH Maverick 1.55 版本中遇到的“Unsupported type: OPENSSH PRIVATE KEY”异常,哪个版本的J2SSH Maverick支持openssh的密钥呢,最好把代码贴出来看看
我在网上搜索了一下,发现 J2SSH Maverick 不支持 OpenSSH 的密钥,并且我没有找到任何版本支持这个特性。
如果要使用 OpenSSH 的密钥来连接远程主机,您可以考虑使用其他 Java SSH 库,如 JSch。
下面是一个使用JSch连接远程服务器的示例代码,您可以使用这个代码来连接远程服务器并使用 OpenSSH 的密钥文件:
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class SSHConnection {
public static void main(String[] args) {
String hostname = "hostname";
int port = 22;
String username = "username";
String privateKeyPath = "/path/to/privatekey.pem";
String passphrase = "passphrase";
try {
JSch jsch = new JSch();
jsch.addIdentity(privateKeyPath, passphrase);
Session session = jsch.getSession(username, hostname, port);
session.connect();
// do something with the session here
// ...
session.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
请注意,在这里使用的是密钥认证,您可能还需要配置其他认证方式,如密码认证,来连接远程服务器。
Maverick 1.7.34 支持
这种错误通常是由于你使用的私钥格式不正确导致的。确保您使用的是OpenSSH私钥格式,而不是其他格式(如PuTTY私钥格式)。如果您使用的是PuTTY私钥格式,可以使用PuTTYgen工具将其转换为OpenSSH格式。
需要使用更高版本的 J2SSH Maverick。
可以使用下面的代码来使用 OpenSSH 私钥登录服务器:
import com.sshtools.j2ssh.*;
import com.sshtools.j2ssh.authentication.*;
import com.sshtools.j2ssh.transport.*;
SshClient ssh = new SshClient();
// Connect to the host
ssh.connect("hostname", new Ssh2Client());
// Create a password authentication instance
PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
pwd.setUsername("username");
pwd.setPassword("password");
// Try the authentication
int result = ssh.authenticate(pwd);
if(result==AuthenticationProtocolState.COMPLETE) {
// Authentication complete, start a session
SessionChannelClient session = ssh.openSessionChannel();
session.startShell();
} else {
// Authentication failed
System.out.println("Authentication failed");
}
如果要使用 OpenSSH 私钥登录,可以使用 SshPrivateKeyFile 类来加载私钥文件,并将其作为参数传递给 PublicKeyAuthenticationClient,如下所示:
SshPrivateKeyFile pkfile = SshPrivateKeyFile.parse(new File("private_key_file"));
PublicKeyAuthenticationClient pk = new PublicKeyAuthenticationClient();
pk.setUsername("username");
pk.setKey(pkfile.toPrivateKey(null));
int result = ssh.authenticate(pk);