jsch远程连接服务器执行命令

远程ssh连接执行shell脚本工具类



import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.sinosig.tianshu.ExecutionLxdasScript;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class sshLxdasUtil {
    private static final Logger logger = Logger.getLogger(ExecutionLxdasScript.class);
    public static List<String> getShLxdas(String ip, String user, String password,String shellPath,String logPath) {
        try {
            JSch jSch = new JSch();

            Session session = jSch.getSession(user, ip);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            ChannelShell shell = (ChannelShell) session.openChannel("shell");


            String hdfsCommand1 = "sh " +shellPath+" >"+logPath +" 2>&1";
            String hdfsCommand2 = "awk '{print}' " +logPath;


            InputStream inputStream = shell.getInputStream();
            OutputStream outputStream = shell.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream);
            shell.setPty(true);
            shell.connect();
            printWriter.println(hdfsCommand1);
            printWriter.println(hdfsCommand2);
            printWriter.println("exit");
            printWriter.flush();
            outputStream.flush();
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
            String msg = null;
            List<String> lis = new ArrayList<>();
            while ((msg = in.readLine()) != null) {
                lis.add(msg.trim());
            }
            in.close();
            session.disconnect();
            return lis;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("错误:", e);
            return null;
        }
    }
}

jsch所需pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>executionLxdasScript</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.32</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.9</version>
        </dependency>

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

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.17.0</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.14</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>






        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.25</version>
            <!--            <scope>compile</scope>-->
        </dependency>

        <dependency>
            <groupId>com.typesafe.play</groupId>
            <artifactId>play-mailer_2.12</artifactId>
            <version>7.0.0</version>
        </dependency>




    </dependencies>

<build>
<!--        增加编译xml文件配置-->
<!--        <resources>-->
<!--            <resource>-->
<!--                <directory>src/main/scala</directory>-->
<!--                <includes>-->
<!--                    <include>**/*.xml</include>-->
<!--                    <include>**/*.perperties</include>-->
<!--                </includes>-->
<!--            </resource>-->
<!--            <resource>-->
<!--                <directory>src/main/resources</directory>-->
<!--                <includes>-->
<!--                    <include>**/*.xml</include>-->
<!--                    <include>**/*.perperties</include>-->
<!--                </includes>-->
<!--            </resource>-->
<!--        </resources>-->

<plugins>
    <!-- 该插件用于将Scala代码编译成class文件 -->
    <plugin>
        <groupId>net.alchim31.maven</groupId>
        <artifactId>scala-maven-plugin</artifactId>
        <version>4.4.0</version>
        <executions>
            <execution>
                <!-- 声明绑定到maven的compile阶段 -->
                <goals>
                    <goal>compile</goal>
                </goals>
            </execution>
            <!-- 声明 -->
            <execution>
                <id>compile-scala</id>
                <phase>process-resources</phase>
                <goals>
                    <goal>add-source</goal>
                    <goal>compile</goal>
                </goals>
            </execution>
            <execution>
                <id>scala-compile-first</id>
                <phase>compile</phase>
                <goals>
                    <goal>add-source</goal>
                    <goal>testCompile</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.3.0</version>
        <configuration>
            <descriptorRefs>
                <descriptorRef>
                    jar-with-dependencies
                </descriptorRef>
            </descriptorRefs>
        </configuration>
        <executions>
            <execution>
                <id>make-assembly</id>
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
    </plugin>



</plugins>
</build>

        </project>

因为本项目同时使用了java和Scala代码,所以依赖中添加了编译Scala的部分。

  • 14
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现连接远程服务器执行命令,可以使用Java中的SSH协议。SSH(Secure Shell)是一种加密网络协议,可用于安全地连接到远程服务器执行命令Java中有一些SSH库可以用来实现这个功能,比如JSch和Apache Mina SSHD。下面是一个使用JSch的示例代码: ```java import com.jcraft.jsch.*; public class SSHConnection { public static void main(String[] args) { String host = "remotehost.com"; String user = "username"; String password = "password"; try { JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); Channel channel = session.openChannel("exec"); ((ChannelExec)channel).setCommand("ls -la"); channel.setInputStream(null); ((ChannelExec)channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) break; System.out.print(new String(tmp, 0, i)); } if (channel.isClosed()) { if (in.available() > 0) continue; System.out.println("exit-status: " + channel.getExitStatus()); break; } try { Thread.sleep(1000); } catch (Exception e) {} } channel.disconnect(); session.disconnect(); } catch (JSchException | IOException e) { e.printStackTrace(); } } } ``` 这个代码片段使用JSch创建一个SSH会话,并通过该会话连接到远程主机。然后它打开一个执行通道并设置要执行的命令(在这个例子中是“ls -la”)。执行通道连接后,它从通道的输入流中读取输出并将其打印到控制台。最后,通道断开连接,并且会话关闭。 需要注意的是,这个示例代码中的密码是明文存储的,这是不安全的。在实际生产环境中,应该考虑使用密钥进行身份验证,而不是密码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值