导入依赖
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-core</artifactId>
<version>2.8.0</version>
</dependency>
代码
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Scanner;
/**
* ClassName:SSHClientDemo
* Package:ssh
* Description:
*
* @date:2022/8/11 20:41
* @author:Riku
*/
public class SSHClientDemo {
private SshClient sshClient = null;
private ClientSession session;
private final static Logger log = LoggerFactory.getLogger(SSHClientDemo.class);
// 初始化
private boolean init(){
sshClient = SshClient.setUpDefaultClient();
sshClient.start();
try {
session = sshClient.connect("root", "192.168.124.9", 22).verify().getSession();
return session.auth().verify().isSuccess();
} catch (IOException e) {
e.printStackTrace();
log.error("Login error");
}
return false;
}
private void close() throws IOException {
if (session != null && session.isOpen()){
session.close();
}
// 关闭 SSH客户端
if (sshClient != null && sshClient.isOpen()) {
sshClient.stop();
sshClient.close();
}
}
public Integer run(String cmd){
ChannelExec channel;
if (this.init()){
try {
channel = session.createExecChannel(cmd);
channel.open();
ByteArrayOutputStream msg = new ByteArrayOutputStream();
channel.setErr(msg);
System.out.println(msg.toString());
return channel.getExitStatus();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public void run(){
ChannelExec channel;
Scanner scanner = new Scanner(System.in);
if (this.init()){
try {
while (true){
channel = session.createExecChannel(scanner.nextLine());
channel.open();
ByteArrayOutputStream msg = new ByteArrayOutputStream();
channel.setOut(msg);
Thread.sleep(100);
System.out.println(msg.toString());
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new SSHClientDemo().run();
}
}
测试
#route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 192.168.124.1 0.0.0.0 UG 100 0 0 ens37
0.0.0.0 192.168.10.2 0.0.0.0 UG 101 0 0 ens33
192.168.10.0 0.0.0.0 255.255.255.0 U 100 0 0 ens33
192.168.124.0 0.0.0.0 255.255.255.0 U 100 0 0 ens37
#cat /etc/os-*
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"
CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"