一、簡介
JSch庫可以實作Java連接配接Linux伺服器并操作指令、檔案等,支援常用的各種授權模式。網址:http://www.jcraft.com/jsch/
類似C#中的SSH.Net架構。在Java中,類似的庫還有:Apache Mina SSHD http://mina.apache.org/sshd-project/
二、案例
1、建立Maven項目,在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、建立類ShellTest,内容如下:
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);
//使用Window的問題
channel.setInputStream(new FilterInputStream(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);
//去除控制台彩色輸出
((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、直接運作(或者打成Jar後在cmd視窗中運作)效果

宋興柱(Sindrol):轉載内容,請标明出處,謝謝!源文來自 寶貝雲知識分享:https://www.dearcloud.cn