国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

springboot通過(guò)接口執(zhí)行本地shell腳本

這篇具有很好參考價(jià)值的文章主要介紹了springboot通過(guò)接口執(zhí)行本地shell腳本。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

首先創(chuàng)建springboot項(xiàng)目
shell腳本
這里是執(zhí)行本地腳本

#!/bin/sh
 echo 'Hello World!'

然后編寫執(zhí)行shell腳本的util類

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ShellUtils {

    /**
     * @param pathOrCommand 腳本路徑或者命令
     * @return
     */
    public static List<String> exceShell(String pathOrCommand) {
        List<String> result = new ArrayList<>();

        try {
            // 執(zhí)行腳本
            Process ps = Runtime.getRuntime().exec(pathOrCommand);
            int exitValue = ps.waitFor();
            if (0 != exitValue) {
                System.out.println("call shell failed. error code is :" + exitValue);
            }

            // 只能接收腳本echo打印的數(shù)據(jù),并且是echo打印的最后一次數(shù)據(jù)
            BufferedInputStream in = new BufferedInputStream(ps.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println("腳本返回的數(shù)據(jù)如下: " + line);
                result.add(line);
            }
            in.close();
            br.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
}

最后開(kāi)發(fā)接口調(diào)用此類


@RestController
@RequestMapping("/shell/test")
public class ShellTestController {

    @GetMapping("/shell")
    public List<String> shellTest(){
        List<String> list = ShellUtils.exceShell("/home/shelltest/test.sh");
        return list;
    }
}

如何執(zhí)行遠(yuǎn)程腳本
在這里我試用了三種方式,實(shí)現(xiàn)遠(yuǎn)程腳本的執(zhí)行
但是使用ssh2時(shí)

java.io.IOException: Key exchange was not finished, connection is closed.
	at ch.ethz.ssh2.transport.KexManager.getOrWaitForConnectionInfo(KexManager.java:75)
	at ch.ethz.ssh2.transport.TransportManager.getConnectionInfo(TransportManager.java:169)
	at ch.ethz.ssh2.Connection.connect(Connection.java:759)
	at ch.ethz.ssh2.Connection.connect(Connection.java:628)
	at com.zhou.util.SSHClient.login(SSHClient.java:39)
	at com.zhou.util.SSHClient.exec(SSHClient.java:47)
	at com.zhou.util.SSHClient.main(SSHClient.java:76)
Caused by: java.io.IOException: Cannot negotiate, proposals do not match.
	at ch.ethz.ssh2.transport.ClientKexManager.handleMessage(ClientKexManager.java:123)
	at ch.ethz.ssh2.transport.TransportManager.receiveLoop(TransportManager.java:572)
	at ch.ethz.ssh2.transport.TransportManager$1.run(TransportManager.java:261)
	at java.lang.Thread.run(Thread.java:745)

會(huì)拋出上述的異常,大體的意思就是密鑰交換算法不匹配,導(dǎo)致連接失敗。
但是老版本的centos系統(tǒng)還是可以使用的
springboot通過(guò)接口執(zhí)行本地shell腳本,問(wèn)題雜談,spring boot,shell
此版本使用沒(méi)有問(wèn)題 ,下面是代碼
引入的maven

        <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>262</version>
        </dependency>
package com.zhou.util;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class SSHClient {
    private String ip;
    private String username;
    private String password;

    private String charset = Charset.defaultCharset().toString();
    private static final int TIME_OUT = 1000 * 5 * 60;

    private Connection conn;

    public SSHClient(String ip, String username, String password) {
        this.ip = ip;
        this.username = username;
        this.password = password;
    }

    /**
     * 登錄指遠(yuǎn)程服務(wù)器
     * @return
     * @throws IOException
     */
    private boolean login() throws IOException {
        conn = new Connection(ip);
        conn.connect();
        return conn.authenticateWithPassword(username, password);
    }

    public List<String> exec(String shell) throws Exception {
        List<String> result = new ArrayList<>();
        int ret = -1;
        try {
            if (login()) {
                Session session = conn.openSession();
                session.execCommand(shell);
                session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
                ret = session.getExitStatus();
                // 只能接收腳本echo打印的數(shù)據(jù),并且是echo打印的最后一次數(shù)據(jù)
                BufferedInputStream in = new BufferedInputStream(session.getStdout());
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println("腳本返回的數(shù)據(jù)如下: " + line);
                    result.add(line);
                }
                in.close();
                br.close();
            } else {
                throw new Exception("登錄遠(yuǎn)程機(jī)器失敗" + ip); // 自定義異常類 實(shí)現(xiàn)略
            }
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        return result;
    }

    public static void main(String[] args) {
        try {
            SSHClient sshClient = new SSHClient("192.168.0.1", "root", "123456");
            List<String> exec = sshClient.exec("/home/shell/run_all.sh");
            for (String s : exec) {
                System.out.println(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

使用sshd可以正常進(jìn)行遠(yuǎn)程執(zhí)行shell文件
maven代碼

<!--        ssh-core start-->
        <dependency>
            <groupId>org.apache.sshd</groupId>
            <artifactId>sshd-core</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>net.i2p.crypto</groupId>
            <artifactId>eddsa</artifactId>
            <version>0.3.0</version>
        </dependency>
<!--        ssh-core end-->
package com.zhou.util.sshcore;

import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ChannelExec;
import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.future.ConnectFuture;
import org.apache.sshd.client.session.ClientSession;

import java.io.ByteArrayOutputStream;
import java.util.EnumSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class SshSelfDemo {
    public static String runCommand(String hostName,String userName,String pwd,int port,String cmd, long timeout)
            throws Exception {
        SshClient client = SshClient.setUpDefaultClient();

        try {
            // Open the client
            client.start();
            // Connect to the server
            ConnectFuture cf = client.connect(userName, hostName, port);
            ClientSession session = cf.verify().getSession();
            session.addPasswordIdentity(pwd);
            session.auth().verify();
            // 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);
            return out.toString();

        } finally {
            client.stop();
        }

    }
    public static void main(String[] args) throws Exception{
        String hostName = "192.168.0.1";
        String userName = "root";
        String pwd = "123456";
        int port = 22;
        SshConnection  conn  = new SshConnection(userName,pwd,hostName);
//    &&-表示前面命令執(zhí)行成功在執(zhí)行后面命令; ||表示前面命令執(zhí)行失敗了在執(zhí)行后面命令; ";"表示一次執(zhí)行兩條命令
        String cmd = "/home/shell/run_all.sh";
        String result = runCommand(hostName,userName,pwd,port,cmd,15);
        System.out.println("===返回結(jié)果===>"+result);


//    runCommandForInteractive(conn,15);
    }
}

使用jsch也可以正常執(zhí)行shell文件
maven依賴

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

代碼

package com.zhou.util.sshcore;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.Properties;

public class JSchExecShellUtil {

    private static final Logger logger = LoggerFactory.getLogger(JSchExecShellUtil.class);

    public static String execShell(String hostName,String userName,String pwd,int port,String command, int timeout){
        // 創(chuàng)建JSch對(duì)象
        JSch jSch = new JSch();
        Session jSchSession = null;
        Channel jschChannel = null;
        // 存放執(zhí)行命令結(jié)果
        StringBuffer result = new StringBuffer();
        int exitStatus = 0;
        try {
            // 根據(jù)主機(jī)賬號(hào)、ip、端口獲取一個(gè)Session對(duì)象
            jSchSession = jSch.getSession(userName, hostName, port);
            // 存放主機(jī)密碼
            jSchSession.setPassword(pwd);

            // 去掉首次連接確認(rèn)
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            jSchSession.setConfig(config);

            // 超時(shí)連接時(shí)間為3秒
            jSchSession.setTimeout(timeout);
            // 進(jìn)行連接
            jSchSession.connect();
            jschChannel = jSchSession.openChannel("exec");
            ((ChannelExec) jschChannel).setCommand(command);

            jschChannel.setInputStream(null);
            // 錯(cuò)誤信息輸出流,用于輸出錯(cuò)誤的信息,當(dāng)exitstatus<0的時(shí)候
            ((ChannelExec)jschChannel).setErrStream(System.err);

            // 執(zhí)行命令,等待執(zhí)行結(jié)果
            jschChannel.connect();

            // 獲取命令執(zhí)行結(jié)果
            InputStream in = jschChannel.getInputStream();
            /**
             * 通過(guò)channel獲取信息的方式,采用官方Demo代碼
             */
            byte[] tmp=new byte[1024];
            while(true){
                while(in.available() > 0){
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) {
                        break;
                    }
                    result.append(new String(tmp, 0, i));
                }
                // 從channel獲取全部信息之后,channel會(huì)自動(dòng)關(guān)閉
                if(jschChannel.isClosed()){
                    if (in.available() > 0) {
                        continue;
                    }
                    exitStatus = jschChannel.getExitStatus();
                    break;
                }
                try{Thread.sleep(1000);}catch(Exception ee){}
            }

        } catch (Exception e) {
            logger.warn(e.getMessage());
        } finally {
            // 關(guān)閉sftpChannel
            if (jschChannel != null && jschChannel.isConnected()) {
                jschChannel.disconnect();
            }

            // 關(guān)閉jschSesson流
            if (jSchSession != null && jSchSession.isConnected()) {
                jSchSession.disconnect();
            }

        }
        logger.info("獲取執(zhí)行命令的結(jié)果結(jié)果:"+result);
        logger.info("退出碼為:"+exitStatus);
        return result.toString();
    }

    public static void main(String[] args) {
        String username = "root";
        String password = "123456";
        String host = "192.168.0.1";
        int port = 22;
        String commond = "/home/shell/run_all.sh";
        execShell(host,username,password, port, commond, 1000);
    }
}


以上是整理的Java遠(yuǎn)程調(diào)用以及本地調(diào)用的代碼實(shí)現(xiàn)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-621661.html

到了這里,關(guān)于springboot通過(guò)接口執(zhí)行本地shell腳本的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 在shell腳本中切換用戶之后再執(zhí)行多個(gè)函數(shù)以及執(zhí)行多行命令的方法和遇到的問(wèn)題

    其中,username是您要切換到的用戶的用戶名,function1和function2是您要執(zhí)行的函數(shù)名稱,您可以根據(jù)需要添加更多函數(shù)和命令。在EOF標(biāo)記之間的所有內(nèi)容都將作為切換后的用戶執(zhí)行。請(qǐng)注意,您需要確保切換后的用戶具有執(zhí)行所需命令和函數(shù)的權(quán)限。 其中,username為要切換到的

    2024年02月04日
    瀏覽(23)
  • 【Linux命令-shell】虛擬機(jī)中創(chuàng)建shell腳本、查看當(dāng)前路徑、執(zhí)行腳本

    目錄 一、創(chuàng)建shell腳本 二、查看當(dāng)前的路徑 三、執(zhí)行腳本 一、創(chuàng)建shell腳本 shell腳本的特點(diǎn) 提前將可執(zhí)行的命令語(yǔ)句寫入一個(gè)文件中 順序執(zhí)行 解釋器逐行解釋代碼 常見(jiàn)的腳本有:shell、python、PHP...... 注:用什么解釋器就是什么腳本 編寫shell腳本: 步驟: 1、新建文件 2、

    2024年02月05日
    瀏覽(95)
  • Linux下定時(shí)執(zhí)行shell腳本

    vi test.sh 錄入要執(zhí)行的命令 ?保存退出,并且對(duì)腳本進(jìn)行授權(quán) ?:wq chmod 777 test.sh ?生產(chǎn)文件data.txt touch /opt/data.txt ?vi /etc/crontab? 錄入: 一分鐘執(zhí)行一次 ?保存退出即可每個(gè)一分鐘執(zhí)行一次 配置說(shuō)明:

    2024年02月17日
    瀏覽(26)
  • nodejs腳本中執(zhí)行shell命令

    Node.js v8.x 中文文檔: child_process - 子進(jìn)程 Node.js中使用內(nèi)置的 child_process 模塊來(lái)執(zhí)行shell命令。該模塊提供了 exec 、 execFile 、 spawn 等方法來(lái)啟動(dòng)子進(jìn)程并執(zhí)行命令 exec 方法是將整個(gè)命令輸出緩存到內(nèi)存中,當(dāng)執(zhí)行 完成后一次性 返回,所以適合執(zhí)行 較小 的命令 exec 方法的 回調(diào)

    2024年01月21日
    瀏覽(23)
  • 【Linux】編寫一個(gè) shell 腳本&執(zhí)行

    在Linux中編寫和執(zhí)行腳本相對(duì)簡(jiǎn)單。下面是一個(gè)基本的步驟指南,幫助你創(chuàng)建一個(gè)簡(jiǎn)單的bash腳本并運(yùn)行它: 1. 創(chuàng)建腳本文件 首先,你需要使用文本編輯器創(chuàng)建一個(gè)新的文件。這個(gè)文件通常會(huì)有 .sh 的擴(kuò)展名,以表明它是一個(gè)shell腳本。例如,你可以創(chuàng)建一個(gè)名為 myscript.sh 的文

    2024年04月26日
    瀏覽(25)
  • shell批量執(zhí)行命令與文件傳輸腳本

    shell批量執(zhí)行命令與文件傳輸腳本

    對(duì)未進(jìn)行主機(jī)信任操作的服務(wù)器進(jìn)行批量操作 由于ssh只能在交互模式中輸入服務(wù)器密碼進(jìn)行登錄登操作,不便于進(jìn)行大批量服務(wù)器進(jìn)行巡檢或日志采集。sshpass恰好又解決了這個(gè)問(wèn)題,使用 ssh -p passwd 可以實(shí)現(xiàn)命令行輸入密碼操作,便于進(jìn)行規(guī)模巡檢 首先需要在腳本執(zhí)行機(jī)器

    2024年02月08日
    瀏覽(25)
  • shell腳本-批量主機(jī)執(zhí)行命令(expect)

    上次連接多臺(tái)服務(wù)器使用ssh-keygen,24機(jī)器去連接22、25,所以存在.ssh/authorized_keys 1.如果有.ssh/authorized_keys該文件則先刪除 1.expect命令含義 expect是一種腳本語(yǔ)言,它能夠代替人工實(shí)現(xiàn)與終端的交互,主要應(yīng)用于執(zhí)行命令和程序時(shí),系統(tǒng)以交互形式要求輸入指定字符串,實(shí)現(xiàn)交互

    2024年02月13日
    瀏覽(18)
  • Linux 環(huán)境使用定時(shí)任務(wù)執(zhí)行shell腳本

    Linux 環(huán)境使用定時(shí)任務(wù)執(zhí)行shell腳本

    前言:Linux添加定時(shí)任務(wù)需要依賴crond服務(wù),如果沒(méi)有該服務(wù),需要先安裝:yum -y install crontabs 1、crond服務(wù)相關(guān)命令介紹 ????????啟動(dòng)crond服務(wù): service crond start ????????停止crond服務(wù): service crond stop ????????重啟crond服務(wù): service crond restart ????????重載crond服務(wù)

    2024年02月16日
    瀏覽(21)
  • postgresql|數(shù)據(jù)庫(kù)|批量執(zhí)行SQL腳本文件的shell腳本

    postgresql|數(shù)據(jù)庫(kù)|批量執(zhí)行SQL腳本文件的shell腳本

    對(duì)于數(shù)據(jù)庫(kù)的維護(hù)而言,肯定是有SQL腳本的執(zhí)行,例如,某個(gè)項(xiàng)目需要更新,那么,可能會(huì)有很多的SQL腳本需要執(zhí)行,SQL腳本可能會(huì)包含有建表,插入數(shù)據(jù),索引建立,約束建立,主外鍵建立等等內(nèi)容。 那么,幾個(gè)SQL腳本可能無(wú)所謂,navicat或者psql命令行 簡(jiǎn)簡(jiǎn)單單的就導(dǎo)入了

    2024年02月01日
    瀏覽(88)
  • shell:腳本執(zhí)行失敗就退出的3種方案

    shell:腳本執(zhí)行失敗就退出的3種方案

    簡(jiǎn)介: ?在日常的自動(dòng)化測(cè)試中,尤其shell腳本,在針對(duì)需要多個(gè)程序運(yùn)行,shell腳本順序執(zhí)行過(guò)程可能會(huì)有中間環(huán)節(jié)會(huì)運(yùn)行失敗,拋出異常停止運(yùn)行并報(bào)錯(cuò),然而shell的其他下方語(yǔ)句仍然會(huì)繼續(xù)往下執(zhí)行,有時(shí)需要規(guī)避這類問(wèn)題,使得出錯(cuò)后就退出后面的執(zhí)行。 案例目錄結(jié)構(gòu)

    2024年02月11日
    瀏覽(23)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包