java 里面的开源 ssh lib
1、Jsch
2、SSHJ
JSCH 里面的概念
1、Linux OpenSSH 验证方式对应的 jsch auth method
在/etc/sshd_config 文件中
1# Authentication: 2PubkeyAuthentication //对应的是 publickey 公钥认证 3PasswordAuthentication yes //对应的是 password 密码验证 4ChallengeResponseAuthentication yes //对应的是 keyboard-interactive 键盘交互 5 6# Kerberos options 7KerberosAuthentication yes //对应的是kerberos 验证 8#KerberosOrLocalPasswd yes 9#KerberosTicketCleanup yes 10#KerberosGetAFSToken no 11 12# GSSAPI options 13GSSAPIAuthentication yes //对应的 gssapi-with-mic 验证 14#GSSAPICleanupCredentials yes 15#GSSAPIStrictAcceptorCheck yes 16#GSSAPIKeyExchange no
OpenSHH 文档中写到
The methods available for authentication are:
GSSAPI-based authentication,host-based authentication,public key authentication,challenge-response authentication, andpassword authentication. Authentication methods are tried in the order specified above, thoughPreferredAuthenticationscan be used to change the default order.
我们在使用jsch 的时候就要注意几点
1//StrictHostKeyChecking 选项可用于控制对主机密钥未知或已更改的计算机的登录。 2session.setConfig("StrictHostKeyChecking", "no"); 3//设置首选的Auth Method 4session.setConfig("PreferredAuthentications","publickey,keyboard-interactive,password");
我们如果使用sshj 就可以这样
1//调用 sshClient 的这个方法,里面可以实现多个验证方式 2public void auth(String username, AuthMethod... methods) 3 throws UserAuthException, TransportException { 4 checkConnected(); 5 auth(username, Arrays.<AuthMethod>asList(methods)); 6 } 7//例子 8 DefaultConfig defaultConfig = new DefaultConfig(); 9 final SSHClient client = new SSHClient(defaultConfig); 10 String host = "127.0.0.1"; 11 String user = "king"; 12 String password = "123456"; 13 client.setTimeout(60000); 14 client.loadKnownHosts(); 15 client.addHostKeyVerifier(new PromiscuousVerifier()); 16 client.connect(host); 17 PasswordFinder pwdf = PasswordUtils.createOneOff(password.toCharArray()); 18 PasswordResponseProvider provider = new PasswordResponseProvider(pwdf); 19 //键盘交互 20 AuthKeyboardInteractive authKeyboardInteractive = new AuthKeyboardInteractive(provider); 21 //密码验证 22 AuthPassword authPassword = new AuthPassword(pwdf); 23 client.auth(user, authKeyboardInteractive, authPassword);
jsch 例子
1 JSch jSch = new JSch(); 2 //设置JSch 的日志,可以看到具体日志信息 3 JSch.setLogger(new Logger() { 4 @Override 5 public boolean isEnabled(int level) { 6 return true; 7 } 8 @Override 9 public void log(int level, String message) { 10 System.out.println("logger:" + message); 11 } 12 }); 13 com.jcraft.jsch.Session session = jSch.getSession("king", "127.0.0.1"); 14 session.setPassword("123456"); 15 //忽略第一次连接时候 hostkey 检查 16 session.setConfig("StrictHostKeyChecking", "no"); 17 //设置首选的身份验证方式 18 session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password"); 19 session.connect(60000); 20 //开启shell,shell 具有上下文交互,执行命令不会马上退出 21 ChannelShell shell = (ChannelShell) session.openChannel("shell"); 22 //开始 exec 类似linux bash -c exec 执行完命令马上退出 23 //ChannelExec exec = (ChannelExec)session.openChannel("exec"); 24 //exec.setCommand(""); 25 shell.setPtyType("dumb"); 26 shell.setPty(true); 27 shell.connect(60000); 28 boolean connected = shell.isConnected(); 29 OutputStream outputStream = shell.getOutputStream(); 30 InputStream inputStream = shell.getInputStream(); 31 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8")); 32 //通过流写入命令 33 outputStream.write("pwd\n cd /home\nls\npwd\n".getBytes()); 34 outputStream.flush(); 35 String line; 36 while ((line = bufferedReader.readLine()) != null) { 37 System.out.println(line); 38 }
sshj 例子
1 DefaultConfig defaultConfig = new DefaultConfig(); 2 final SSHClient client = new SSHClient(defaultConfig); 3 String host = "127.0.0.1"; 4 String user = "king"; 5 String password = "123456"; 6 client.setTimeout(60000); 7 client.loadKnownHosts(); 8 client.addHostKeyVerifier(new PromiscuousVerifier()); 9 client.connect(host); 10 try { 11 client.authPassword(user, password); 12 final SessionChannel session = (SessionChannel) client.startSession(); 13 session.allocateDefaultPTY(); 14 //这里的session 类似 jsch 里面的exec ,可以直接执行命令。 15 //session.exec("pwd"); 16 SessionChannel shell = (SessionChannel) session.startShell(); 17 try { 18 OutputStream outputStream = shell.getOutputStream(); 19 outputStream.write("pwd\n".getBytes()); 20 outputStream.flush(); 21 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(shell.getInputStream(), "utf-8")); 22 String line; 23 while ((line = bufferedReader.readLine()) != null) { 24 System.out.println(line); 25 } 26 } catch (InterruptedException e) { 27 e.printStackTrace(); 28 } 29 } finally { 30 client.disconnect(); 31 }