java连接linux的三种方式

简介: java连接linux的三种方式


  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();
}
  1. 远程调用(一)
<!--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();
}
  1. 远程调用(二)
    jsch实现
<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();
}

完整代码:

  • 执行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");
    }
}


相关文章
|
8月前
|
Java Linux Apache
Apache NetBeans 27 (macOS, Linux, Windows) - Java 等多语言开源跨平台 IDE
Apache NetBeans 27 (macOS, Linux, Windows) - Java 等多语言开源跨平台 IDE
488 5
Apache NetBeans 27 (macOS, Linux, Windows) - Java 等多语言开源跨平台 IDE
|
7月前
|
SQL Java 关系型数据库
Java连接MySQL数据库环境设置指南
请注意,在实际部署时应该避免将敏感信息(如用户名和密码)硬编码在源码文件里面;应该使用配置文件或者环境变量等更为安全可靠地方式管理这些信息。此外,在处理大量数据时考虑使用PreparedStatement而不是Statement可以提高性能并防止SQL注入攻击;同时也要注意正确处理异常情况,并且确保所有打开过得资源都被正确关闭释放掉以防止内存泄漏等问题发生。
330 13
|
监控 数据可视化 Java
调试技巧 - 用Linux命令排查Java问题
总的来说,使用Linux命令来排查Java问题,需要一定的实践经验和理论知识。然而,只要我们愿意花时间深入了解这些工具,我们就能够熟练地使用它们来分析和解决问题。此外,这些工具只是帮助我们定位问题,真正解决问题需要我们对Java和JVM有深入的理解,并能够读懂和分析代码。
594 13
|
10月前
|
Java Linux 开发者
linux 查看java的安装路径
本指南详细介绍Java环境的安装验证与配置方法,包括检查Java版本、确认环境变量JAVA_HOME是否正确配置,以及通过which和readlink命令手动定位Java安装路径。同时提供系统级环境变量配置步骤,并给出多版本管理建议。适用于Linux系统用户,特别是需要在服务器或Docker容器中部署Java环境的开发者。注意操作时需具备相应权限,确保路径设置准确无误。
|
监控 Shell Linux
Android调试终极指南:ADB安装+多设备连接+ANR日志抓取全流程解析,覆盖环境变量配置/多设备调试/ANR日志分析全流程,附Win/Mac/Linux三平台解决方案
ADB(Android Debug Bridge)是安卓开发中的重要工具,用于连接电脑与安卓设备,实现文件传输、应用管理、日志抓取等功能。本文介绍了 ADB 的基本概念、安装配置及常用命令。包括:1) 基本命令如 `adb version` 和 `adb devices`;2) 权限操作如 `adb root` 和 `adb shell`;3) APK 操作如安装、卸载应用;4) 文件传输如 `adb push` 和 `adb pull`;5) 日志记录如 `adb logcat`;6) 系统信息获取如屏幕截图和录屏。通过这些功能,用户可高效调试和管理安卓设备。
|
消息中间件 存储 NoSQL
java连接redis和基础操作命令
通过以上内容,您可以掌握在Java中连接Redis以及进行基础操作的基本方法,进而在实际项目中灵活应用。
680 30
|
Linux
SecureCRT连接Linux时乱码问题
本文详细介绍了在使用SecureCRT连接Linux服务器时出现乱码问题的解决方法,包括设置SecureCRT字符编码、检查和配置Linux服务器字符编码、调整终端设置等。通过这些方法,您可以有效解决SecureCRT连接Linux时的乱码问题,确保正常的终端显示和操作。希望本文能帮助您在实际操作中更好地解决类似问题,提高工作效率。
1467 17
|
Java Linux 数据库
java连接kerberos用户认证
java连接kerberos用户认证
418 22
|
存储 NoSQL Linux
微服务2——MongoDB单机部署4——Linux系统中的安装启动和连接
本节主要介绍了在Linux系统中安装、启动和连接MongoDB的详细步骤。首先从官网下载MongoDB压缩包并解压至指定目录,接着创建数据和日志存储目录,并配置`mongod.conf`文件以设定日志路径、数据存储路径及绑定IP等参数。之后通过配置文件启动MongoDB服务,并使用`mongo`命令或Compass工具进行连接测试。此外,还提供了防火墙配置建议以及服务停止的两种方法:快速关闭(直接杀死进程)和标准关闭(通过客户端命令安全关闭)。最后补充了数据损坏时的修复操作,确保数据库的稳定运行。
802 0