java远程操作linux

in 四月桐花 with 0 comment

Runtime.exec()

这个指令是对当前的安装jar的系统进行操作,用户权限为当前启动jar的用户权限.

远程执行session&channel

对于需要远程连接其他linux主机并进行操作的情况,建议使用jsch包,进行扩展

<dependency>
	<groupId>com.jcraft</groupId>
	<artifactId>jsch</artifactId>
	<version>0.1.53</version>
</dependency>

下面是实现代码:

package com.fusionskye.ezsonar;

import com.fusionskye.ezsonar.model.Exec;
import com.jcraft.jsch.*;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @author: joshua
 * @date: 2023/7/13 13:42
 * @description:
 */
public class QuickTest {
    public static final String username = "username";
    public static final String passwd = "password";
    public static final String host = "192.168.1.x";
    public static final int port = 22;
    
    public static void main(String[] args) {
        try {
//          exec("/bin/bash /home/joshua/test.sh");
            exec("env");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int exec(String command) {
        Channel channel = null;
        Session session = null;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(username, host, port);
            session.setPassword(passwd);
            UserInfo ui = new Exec.MyUserInfo();
            session.setUserInfo(ui);
            session.connect(20000);
            channel = session.openChannel("exec");
            ChannelExec channelExec = (ChannelExec) channel;
            channelExec.setCommand(command);
            channel.setInputStream(null);
            channelExec.setErrStream(System.err);
            channel.connect();
            StringBuilder sb = new StringBuilder(16);
            try (InputStream in = channelExec.getInputStream();
                 InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                 BufferedReader reader = new BufferedReader(isr)) {
                String buffer;
                while ((buffer = reader.readLine()) != null) {
                    sb.append("\n").append(buffer);
                }
                // 输出远端的返回数据
                System.out.println(sb);
            }
            return channel.getExitStatus();
        } catch (Exception e) {
            return -1;
        } finally {
            // 释放资源
            if (channel != null)
                channel.disconnect();
            if (session != null)
                session.disconnect();
        }
    }
}

环境变量的问题

用这种方式连接远端linux一定要注意环境变量的问题,解决方式有三种:

  1. (推荐)目的脚本初始化系统的环境变量,如java的JAVA_HOME,CLASSPATH等等
  2. 脚本使用绝对路径
  3. 在/usr/bin 目录下使用ln创建软连接到目的执行文件