1.问题描述:
- 检查用户权限:存在权限配置上的差异。
- 检查SSH服务配置:SSH配置,可能存在一些差异。检查
/etc/ssh/sshd_config
文件,确保其中没有禁用密码验证或限制了登录用户的权限。 - 检查防火墙设置:防火墙可能会阻止SSH连接。防火墙设置允许SSH连接。
- 尝试其他认证方式:如果密码认证不起作用,可以尝试使用公钥认证。在JSch中,你可以使用
addIdentity
方法添加私钥文件路径,然后使用publickey
验证方式进行连接。 - 更新JSch库:如果以上方法都不起作用
- 查看日志:查看
/var/log/auth.log
会提供有关认证失败的详细信息,有助于确定问题的根本原因。
2.代码配置
import com.jcraft.jsch.*; public class JSchExample { public static void main(String[] args) { String host = "your-remote-host"; String user = "your-username"; String password = "your-password"; try { JSch jsch = new JSch(); jsch.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password,aes128-ctr"); jsch.setConfig("KexAlgorithms", "aes128-ctr"); jsch.setConfig("HostKeyAlgorithms", "ssh-rsa"); Session session = jsch.getSession(user, host, 22); session.setPassword(password); session.connect(); // 进行其他操作... session.disconnect(); } catch (JSchException e) { e.printStackTrace(); } } }
3.还有一种这种不建议不太安全
import com.jcraft.jsch.*; public class JSchExample { public static void main(String[] args) { String host = "your-remote-host"; String user = "your-username"; String password = "your-password"; try { JSch jsch = new JSch(); jsch.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password,diffie-hellman-group1-sha1"); jsch.setConfig("KexAlgorithms", "diffie-hellman-group1-sha1"); jsch.setConfig("HostKeyAlgorithms", "ssh-rsa"); Session session = jsch.getSession(user, host, 22); session.setPassword(password); session.connect(); // 进行其他操作... session.disconnect(); } catch (JSchException e) { e.printStackTrace(); } } }
4.如果以上都不行启用终极大法
修改路径:/etc/ssh下的sshd_config 在结尾添加: KexAlgorithms +diffie-hellman-group1-sha1 然后重启sshd:service sshd restart 如果还不行可以修改:ssh_config 也是添加 :KexAlgorithms +diffie-hellman-group1-sha1 java代码按下面方式编写: Session session = null; JSch jsch = new JSch(); try { session = jsch.getSession(username, host, port); session.setPassword(password); session.setTimeout(5 * 60 * 1000); session.setConfig("StrictHostKeyChecking", "no");//是否验证主机秘钥 Properties sshConfig = new Properties(); sshConfig.put("kex", "diffie-hellman-group1-sha1"); session.connect(); } catch (Exception e) { throw new Exception("连接linux服务器时出错:" + e.getMessage()); }