java实现ssh登录linux并执行命令的三种实现方式
更新时间:2024年11月30日 09:07:51 作者:坚持奋斗的李洛克
文章介绍了三种在Java中实现SSH登录Linux并执行命令的方法,包括使用ganymed-ssh2、jsch和sshd-core,由于ganymed-ssh2和jsch的最新版本较旧,可能无法与较新的Linux系统兼容,而sshd-core一直在更新,推荐使用
java实现ssh登录linux并执行命令
1.方法一
使用ganymed-ssh2
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>但是这个包最新版本是2014年之后,就没有更新了,linux 操作系统安装 open-ssh 8.5及更高级版本,就一直提示连接失败。就不再提供demo
2.方法二
jsch 暂时能使用,也是很久没有更新了,恐怕后续也会有无法匹配系统最新协议的问题。
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>public class RemoteExecuteCommand {
public static List<String> remoteExecute(Session session, String command)
{
System.out.println("CMD:" + command);
List<String> resultLines = new ArrayList<>();
ChannelExec channel = null;
try
{
channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
InputStream input = channel.getInputStream();
channel.connect(50000);
BufferedReader inputReader = new BufferedReader(new InputStreamReader(input));
String inputLine = null;
while ((inputLine = inputReader.readLine()) != null)
{
System.out.println(inputLine);
resultLines.add(inputLine);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
System.out.println("最后关闭channel");
channel.disconnect();
}
return resultLines;
}
}
String usrName = "root";
String passWord = "******";
String remoteIP = "*****";
String remoteIP = "ifconfig";
JSch jSch = new JSch();
try
{
Session session = jSch.getSession(usrName, remoteIP);
session.setPassword(passWord);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(100000);
session.setTimeout(15000);
if (session.isConnected() == true)
{
System.out.println("Host(" + remoteIP + ") connected!");
}
ChannelExec channel = (ChannelExec) session.openChannel("exec");
remoteExecute(session, cmd);
3.方法三
使用sshd-core,一直在更新
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-core</artifactId>
<version>2.8.0</version>
</dependency>//SshConnection 是自定义的,包含userName,pwd,hostName的实体类
public static SshResponse runCommand(SshConnection conn, String cmd, long timeout)
throws IOException {
SshClient client = SshClient.setUpDefaultClient();
try {
// Open the client
client.start();
// Connect to the server
ConnectFuture cf = client.connect(conn.getUsername(), conn.getHostname(), 22);
ClientSession session = cf.verify().getSession();
session.addPasswordIdentity(conn.getPassword());
session.auth().verify(TimeUnit.SECONDS.toMillis(timeout));
// Create the exec and channel its output/error streams
ChannelExec ce = session.createExecChannel(cmd);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
ce.setOut(out);
ce.setErr(err);
// Execute and wait
ce.open();
Set<ClientChannelEvent> events =
ce.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(timeout));
session.close(false);
// Check if timed out
if (events.contains(ClientChannelEvent.TIMEOUT)) {
throw new RuntimeException(conn.getHostname()+" 命令 "+cmd+ "执行超时 "+timeout);
}
return new SshResponse(out.toString(), err.toString(), ce.getExitStatus());
} finally {
client.stop();
}
}
public static void main(String[] args) throws IOException {
String hostName = "*****";
String userName = "root";
String pwd = "****";
SshConnection conn = new SshConnection(userName,pwd,hostName);
// &&-表示前面命令执行成功在执行后面命令; ||表示前面命令执行失败了在执行后面命令; ";"表示一次执行两条命令
String cmd = "pwd && ps -ef|grep tomcat";
SshResponse response = runCommand(conn,cmd,15);
System.out.println("==error=>"+response.getErrOutput());
System.out.println("===return==>"+response.getReturnCode());
System.out.println("===stdOut===>"+response.getStdOutput());
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
interrupt()和线程终止方式_动力节点Java学院整理
线程的thread.interrupt()方法是中断线程,将会设置该线程的中断状态位,即设置为true,中断的结果线程是死亡、还是等待新的任务或是继续运行至下一步,就取决于这个程序本身2017-05-05
Java实现数据脱敏(Desensitization)的操作指南
数据脱敏是指通过对敏感数据进行部分或完全隐藏处理,保护敏感信息在存储和使用过程中的安全性,常见的应用场景包括日志记录、接口返回、报表展示、数据分析等,本文给大家介绍了Java实现数据脱敏(Desensitization)的操作指南,需要的朋友可以参考下2025-02-02
springMVC @RestControllerAdvice注解使用方式
这篇文章主要介绍了springMVC @RestControllerAdvice注解使用方式,下面通过一个简单的示例,演示如何使用 @RestControllerAdvice,感兴趣的朋友跟随小编一起看看吧2024-08-08
SpringBoot中的@PostConstruct注解详细解析
这篇文章主要介绍了SpringBoot中的@PostConstruct注解详细解析,@PostConstruct注解,主要用于在Spring容器启动时执行某些操作或者任务,@PostConstruct注解一般放在BEAN的方法上,一旦BEAN初始化完成之后,将会调用这个方法,需要的朋友可以参考下2024-01-01
java多线程join()方法的作用和实现原理解析(应用场景)
join方法主要是用于将当前线程挂起,等待其他线程结束后在执行当前线程,本文通过应用场景分析代码示例讲解java多线程join()方法的作用和实现原理,感兴趣的朋友一起看看吧2021-07-07


最新评论