java远程连接Linux执行命令的3种方式完整代码

 更新时间:2024年06月07日 09:32:33   作者:凡客丶  
在一些Java应用程序中需要执行一些Linux系统命令,例如服务器资源查看、文件操作等,这篇文章主要给大家介绍了关于java远程连接Linux执行命令的3种方式,文中通过代码介绍的非常详细,需要的朋友可以参考下

1. 使用JDK自带的RunTime类和Process类实现

public static void main(String[] args){
    Process proc = RunTime.getRunTime().exec("cd /home/tom; ls;")

    // 标准输入流(必须写在 waitFor 之前)
    String inStr = consumeInputStream(proc.getInputStream());
    // 标准错误流(必须写在 waitFor 之前)
    String errStr = consumeInputStream(proc.getErrorStream());

    int retCode = proc.waitFor();
    if(retCode == 0){
        System.out.println("程序正常执行结束");
    }
}

/**
 *   消费inputstream,并返回
 */
public static String consumeInputStream(InputStream is){
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String s ;
    StringBuilder sb = new StringBuilder();
    while((s=br.readLine())!=null){
        System.out.println(s);
        sb.append(s);
    }
    return sb.toString();
}

2. ganymed-ssh2 实现

pom

<!--ganymed-ssh2包-->
<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>build210</version>
</dependency>
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

public static void main(String[] args){
    String host = "210.38.162.181";
    int port = 22;
    String username = "root";
    String password = "root";
    // 创建连接
    Connection conn = new Connection(host, port);
    // 启动连接
    conn.connection();
    // 验证用户密码
    conn.authenticateWithPassword(username, password);
    Session session = conn.openSession();
    session.execCommand("cd /home/winnie; ls;");
    
    // 消费所有输入流
    String inStr = consumeInputStream(session.getStdout());
    String errStr = consumeInputStream(session.getStderr());
    
    session.close;
    conn.close();
}

/**
 *   消费inputstream,并返回
 */
public static String consumeInputStream(InputStream is){
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String s ;
    StringBuilder sb = new StringBuilder();
    while((s=br.readLine())!=null){
        System.out.println(s);
        sb.append(s);
    }
    return sb.toString();
}

3. jsch实现

pom

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public static void main(String[] args){
    String host = "210.38.162.181";
    int port = 22;
    String username = "root";
    String password = "root";
    // 创建JSch
    JSch jSch = new JSch();
    // 获取session
    Session session = jSch.getSession(username, host, port);
    session.setPassword(password);
    Properties prop = new Properties();
    prop.put("StrictHostKeyChecking", "no");
    session.setProperties(prop);
    // 启动连接
    session.connect();
    ChannelExec exec = (ChannelExec)session.openChannel("exec");
    exec.setCommand("cd /home/winnie; ls;");
    exec.setInputStream(null);
    exec.setErrStream(System.err);
    exec.connect();
   
    // 消费所有输入流,必须在exec之后
    String inStr = consumeInputStream(exec.getInputStream());
    String errStr = consumeInputStream(exec.getErrStream());
    
    exec.disconnect();
    session.disconnect();
}

/**
 *   消费inputstream,并返回
 */
public static String consumeInputStream(InputStream is){
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String s ;
    StringBuilder sb = new StringBuilder();
    while((s=br.readLine())!=null){
        System.out.println(s);
        sb.append(s);
    }
    return sb.toString();
}

4. 完整代码:

执行shell命令

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>
<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>build210</version>
</dependency>
import cn.hutool.core.io.IoUtil;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Vector;

/**
 * shell脚本调用类
 *
 * @author Micky
 */
public class SshUtil {
    private static final Logger logger = LoggerFactory.getLogger(SshUtil.class);
    private Vector<String> stdout;
    // 会话session
    Session session;
    //输入IP、端口、用户名和密码,连接远程服务器
    public SshUtil(final String ipAddress, final String username, final String password, int port) {
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(username, ipAddress, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(100000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int execute(final String command) {
        int returnCode = 0;
        ChannelShell channel = null;
        PrintWriter printWriter = null;
        BufferedReader input = null;
        stdout = new Vector<String>();
        try {
            channel = (ChannelShell) session.openChannel("shell");
            channel.connect();
            input = new BufferedReader(new InputStreamReader(channel.getInputStream()));
            printWriter = new PrintWriter(channel.getOutputStream());
            printWriter.println(command);
            printWriter.println("exit");
            printWriter.flush();
            logger.info("The remote command is: ");
            String line;
            while ((line = input.readLine()) != null) {
                stdout.add(line);
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }finally {
            IoUtil.close(printWriter);
            IoUtil.close(input);
            if (channel != null) {
                channel.disconnect();
            }
        }
        return returnCode;
    }

    // 断开连接
    public void close(){
        if (session != null) {
            session.disconnect();
        }
    }
    // 执行命令获取执行结果
    public String executeForResult(String command) {
        execute(command);
        StringBuilder sb = new StringBuilder();
        for (String str : stdout) {
            sb.append(str);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
    	String cmd = "ls /opt/";
        SshUtil execute = new SshUtil("XXX","abc","XXX",22);
        // 执行命令
        String result = execute.executeForResult(cmd);
        System.out.println(result);
        execute.close();
    }
}

下载和上传文件

/**
 * 下载和上传文件
 */
public class ScpClientUtil {

    private String ip;
    private int port;
    private String username;
    private String password;

    static private ScpClientUtil instance;

    static synchronized public ScpClientUtil getInstance(String ip, int port, String username, String passward) {
        if (instance == null) {
            instance = new ScpClientUtil(ip, port, username, passward);
        }
        return instance;
    }

    public ScpClientUtil(String ip, int port, String username, String passward) {
        this.ip = ip;
        this.port = port;
        this.username = username;
        this.password = passward;
    }

    public void getFile(String remoteFile, String localTargetDirectory) {
        Connection conn = new Connection(ip, port);
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);
            if (!isAuthenticated) {
                System.err.println("authentication failed");
            }
            SCPClient client = new SCPClient(conn);
            client.get(remoteFile, localTargetDirectory);
        } catch (IOException ex) {
            ex.printStackTrace();
        }finally{
            conn.close();
        }
    }

    public void putFile(String localFile, String remoteTargetDirectory) {
        putFile(localFile, null, remoteTargetDirectory);
    }

    public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory) {
        putFile(localFile, remoteFileName, remoteTargetDirectory,null);
    }

    public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory, String mode) {
        Connection conn = new Connection(ip, port);
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);
            if (!isAuthenticated) {
                System.err.println("authentication failed");
            }
            SCPClient client = new SCPClient(conn);
            if ((mode == null) || (mode.length() == 0)) {
                mode = "0600";
            }
            if (remoteFileName == null) {
                client.put(localFile, remoteTargetDirectory);
            } else {
                client.put(localFile, remoteFileName, remoteTargetDirectory, mode);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }finally{
            conn.close();
        }
    }

    public static void main(String[] args) {
        ScpClientUtil scpClient = ScpClientUtil.getInstance("XXX", 22, "XXX", "XXX");
        // 从远程服务器/opt下的index.html下载到本地项目根路径下
        scpClient.getFile("/opt/index.html","./");
       // 把本地项目下根路径下的index.html上传到远程服务器/opt目录下
        scpClient.putFile("./index.html","/opt");
    }
}

总结 

到此这篇关于java远程连接Linux执行命令的3种方式的文章就介绍到这了,更多相关java远程连接Linux执行命令内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Spring 多线程下注入bean问题详解

    Spring 多线程下注入bean问题详解

    本篇文章主要介绍了Spring 多线程下注入bean问题详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • springboot在idea下debug调试热部署问题

    springboot在idea下debug调试热部署问题

    这篇文章主要介绍了springboot在idea下debug调试热部署问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-02-02
  • Map按单个或多个Value排序当Value相同时按Key排序

    Map按单个或多个Value排序当Value相同时按Key排序

    Map可以先按照value进行排序,然后按照key进行排序。 或者先按照key进行排序,然后按照value进行排序,这样操作都行,这篇文章主要介绍了Map按单个或多个Value排序,当Value相同时按Key排序,需要的朋友可以参考下
    2023-02-02
  • java中匿名内部类解读分析

    java中匿名内部类解读分析

    本篇文章介绍了,java中匿名内部类解读分析。需要的朋友参考下
    2013-05-05
  • 初识Java环境变量配置及IDEA

    初识Java环境变量配置及IDEA

    这篇文章主要介绍了Java环境变量配置及IDEA,本文通过图文实例相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-03-03
  • Java 静态数据初始化的示例代码

    Java 静态数据初始化的示例代码

    这篇文章主要介绍了Java 静态数据初始化的示例代码,帮助大家更好的理解和学习Java,感兴趣的朋友可以了解下
    2020-09-09
  • Mybatis中通用Mapper的InsertList()用法

    Mybatis中通用Mapper的InsertList()用法

    文章介绍了通用Mapper中的insertList()方法在批量新增时的使用方式,包括自增ID和自定义ID的情况,对于自增ID,使用tk.mybatis.mapper.additional.insert.InsertListMapper包下的insertList()方法;对于自定义ID,需要重写insertList()方法
    2025-02-02
  • 一文盘点五种最常用的Java加密算法

    一文盘点五种最常用的Java加密算法

    大家平时的工作中,可能也在很多地方用到了加密、解密,比如:支付功能等,所以本文为大家盘点了Java中五个常用的加密算法,希望对大家有所帮助
    2023-06-06
  • java自带的四种线程池实例详解

    java自带的四种线程池实例详解

    java线程的创建非常昂贵,需要JVM和OS(操作系统)互相配合完成大量的工作,下面这篇文章主要给大家介绍了关于java自带的四种线程池的相关资料,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2022-04-04
  • 一个简单的Spring容器初始化流程详解

    一个简单的Spring容器初始化流程详解

    这篇文章主要给大家介绍了一个简单的Spring容器初始化流程的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01

最新评论