一、pom.xml
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.26</version>
</dependency>
二、代码实现
package com.jxq.ssh;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
/**
* @date 2019/7/3 21:21
*/
public class SshBasic {
private static final Logger LOGGER = LoggerFactory.getLogger(SshBasic.class);
private Connection conn;
private static SshBasic instance;
private SshBasic() {
}
public static SshBasic getInstance() {
if (instance == null) {
synchronized (SshBasic.class) {
instance = new SshBasic();
}
}
return instance;
}
/**
* 连接ssh
* @param hostname 主机ip
* @param username 用户名字
* @param password 密码
* @return
*/
public Connection connect(String hostname, String username, String password) {
try {
conn = new Connection(hostname);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false) {
throw new IOException("Authentication failed.");
}
System.out.println("与主机:" + hostname + "连接成功");
} catch (IOException e) {
System.out.println(e.getMessage() + e);
}
return conn;
}
/**
* 执行命令
* @param command 命令字符串
* @return
*/
public boolean execCommand(String command) {
boolean flag = false;
Session session = null;
BufferedReader br = null;
if (conn == null) {
// IllegalStateException:无效状态异常
throw new IllegalStateException("没有建立连接");
}
System.out.println("开始执行命令" + command);
int length = -1;
byte[] buffer = new byte[1024];
long startTime = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
try {
session = conn.openSession();
session.execCommand(command);
InputStream stderr = session.getStderr();
while ((length = stderr.read(buffer)) > -1) {
sb.append(new String(buffer, 0, length));
}
System.out.println(sb.toString()); // 实时打印命令执行情况
flag = true;
System.out.println("命令执行成功,耗时:秒" + (System.currentTimeMillis() - startTime) / 1000.0 + "秒");
} catch (IOException e) {
System.out.println(e.getMessage() + e);
} finally {
try {
if (session != null) {
session.close();
}
if (null != br) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return flag;
}
/**
* 关闭连接
*/
public void close() {
if (conn != null) {
conn.close();
}
}
public static void main(String[] args) {
String hostname="192.168.226.128";
String username="root";
String password="root";
SshBasic instance = SshBasic.getInstance();
instance.connect(hostname,username,password);
instance.execCommand("mkdir /root/1.txt");
instance.close();
}
}
3、执行结果
原文地址:https://blog.csdn.net/u013144287/article/details/77506334