I. Introduction
JSch library can achieve Java Linux server connection and operation commands, files, and support for a variety of common licensing model. URL: http://www.jcraft.com/jsch/
Similar SSH.Net framework in C #.
Second, the case
1, the new Maven project, add the following dependencies in pom.xml:
<dependencies> <!-- https://mvnrepository.com/artifact/com.jcraft/jsch --> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> </dependencies>
2, create a class ShellTest, reads as follows:
package com.test; import com.jcraft.jsch.*; import javax.swing.*; import java.io.FilterInputStream; import java.io.IOException; /** * @author Sindrol 2020/3/10 11:16 */ public class ShellTest { public static void main(String[] args) throws JSchException { JSch jsch = new JSch(); //jsch.setKnownHosts("C:\\Users\\XXX\\.ssh\\known_hosts"); String host = JOptionPane.showInputDialog("Enter hostname", "192.168.213.134"); int port = 22; String user = "root"; Session session = jsch.getSession(user, host, 22); String passwd = JOptionPane.showInputDialog("Enter password", "123456"); session.setPassword(passwd); session.setUserInfo(new MyUserInfo()); session.connect(30000); Channel channel = session.openChannel("shell"); //((ChannelShell)channel).setAgentForwarding(true); // use Window problem channel.setInputStream ( new new FilterInputStream (the System.in) { @Override public int Read ( byte [] B, int OFF, int len) throws IOException { return in.read (B, OFF, (len> 1024 1024? : len)); } }); // channel.setInputStream (System.in); channel.setOutputStream (System.out); // remove the console color output ((ChannelShell) channel) .setPtyType ( "vt102 " ); //((ChannelShell) channel).setEnv("LANG", "zh_CN"); channel.connect(3 * 1000); } public static class MyUserInfo implements UserInfo, UIKeyboardInteractive { @Override public String getPassword() { return null; } @Override public boolean promptYesNo(String message) { Object[] options = {"yes", "no"}; int foo = JOptionPane.showOptionDialog(null, message, "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); return foo == 0; } @Override public String getPassphrase() { return null; } @Override public boolean promptPassphrase(String message) { return false; } @Override public boolean promptPassword(String message) { return false; } @Override public void showMessage(String message) { JOptionPane.showMessageDialog(null, message); } @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { return null; } } }
3, run directly (or labeled after running cmd window Jar) effect