先上依赖
<!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>
只能一次执行一行命令,遇到要交互的场景就GG了,比如sudo su然后要输入密码
代码demo
package com.springdemo.demo;
import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.*;
import java.nio.charset.Charset;
@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
}
private String charset = Charset.defaultCharset().toString();
private static final int TIME_OUT = 1000 * 5 * 60;
@Test
public void testSsh(){
Connection connection = new Connection("192.168.056.105");
Session session = null;
try {
connection.connect();
System.out.println("---------------------开始连接------------------------");
boolean connectResult = connection.authenticateWithPassword("ubuntu","123456");
if(!connectResult){
System.out.println("---------连接失败----------");
return;
}
session = connection.openSession();
session.execCommand("cp /home/ubuntu/test.txt ./installer/");
//接收目标服务器上的控制台返回结果,读取br中的内容;
InputStream stdOut = new StreamGobbler(session.getStdout());
getStrByInputStream(session,stdOut);
//接收目标服务器上的控制台返回结果,读取br中的内容;
InputStream stdErrOut = new StreamGobbler(session.getStderr());
getStrByInputStream(session,stdErrOut);
//当超过 TIME_OUT 中的时候的时候session自动关闭
session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
//得到脚本运行成功与否的标志 :0-成功 非0-失败
int ret = session.getExitStatus();
System.out.println(ret);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (session != null) {
session.close();
}
connection.close();
}
}
String getStrByInputStream(Session session ,InputStream inputStream){
System.out.println("stdOut:"+inputStream.toString());
StringBuffer stringBuffer = new StringBuffer();
byte[] bytes = new byte[1024];
int result = -1;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
String str = null;
try {
while ((result = inputStream.read(bytes, 0, bytes.length)) != -1){
byteArrayOutputStream.write(bytes,0,result);
}
str = new String(byteArrayOutputStream.toByteArray(),charset);
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("获取linux的标准输出的结果-----" + str);
return str;
}
}