最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java執(zhí)行shell并獲取shell輸出日志方式

 更新時(shí)間:2024年04月28日 14:39:08   作者:shy_snow  
這篇文章主要介紹了java執(zhí)行shell并獲取shell輸出日志方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

java執(zhí)行shell并獲取shell輸出日志

獲取shell輸出日志需要java使用兩個(gè)線程分別接受shell的標(biāo)準(zhǔn)輸入流和錯(cuò)誤流并打印出來(lái)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

public class ShellLogRunTest {
	public static void main(String[] args) throws Exception, SecurityException {

		Process p = null;
		Runtime rt = Runtime.getRuntime();
		String command = "cmd /c java -version";
		command = "cmd /c ping 127.0.0.1 -n 3";
		if (args != null && args.length > 0 && args[0] != null && args[0].trim().length() > 0) {
			command = args[0];
		}
		try {
			p = rt.exec(command, null, null);
			// 獲取進(jìn)程的標(biāo)準(zhǔn)輸入流
			final InputStream is1 = p.getInputStream();
			// 獲取進(jìn)城的錯(cuò)誤流
			final InputStream is2 = p.getErrorStream();
			// 啟動(dòng)兩個(gè)線程,一個(gè)線程負(fù)責(zé)讀標(biāo)準(zhǔn)輸出流,另一個(gè)負(fù)責(zé)讀標(biāo)準(zhǔn)錯(cuò)誤流
			new Thread() {
				public void run() {
					BufferedReader br1 = new BufferedReader(new InputStreamReader(is1, Charset.forName("gb2312"))); // 這里要注意shell返回的類型,windows和linux可能不同
					try {
						String line1 = null;
						while ((line1 = br1.readLine()) != null) {
							if (line1 != null) {
								System.out.println(line1);
							}
						}
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						try {
							is1.close();
							System.out.println("is1線程關(guān)閉");
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}.start();

			new Thread() {
				public void run() {
					BufferedReader br2 = new BufferedReader(new InputStreamReader(is2, Charset.forName("gb2312")));
					try {
						String line2 = null;
						while ((line2 = br2.readLine()) != null) {
							if (line2 != null) {
								System.out.println(line2);
							}
						}
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						try {
							is2.close();
							System.out.println("is2線程關(guān)閉");
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}.start();

			p.waitFor();
			p.destroy();
			System.out.println("進(jìn)程結(jié)束");
		} catch (Exception e) {
			try {
				p.getErrorStream().close();
				p.getInputStream().close();
				p.getOutputStream().close();
			} catch (Exception ee) {
			   ee.printStackTrace();
			}
		}
	}
}

java執(zhí)行shell命令(分批 多條 走一步看一步的執(zhí)行)

說(shuō)明

網(wǎng)上有很多通過(guò)java執(zhí)行命令的程序,但是只能執(zhí)行一條命令,或者是所有命令一次性執(zhí)行完畢。

而我想要的是執(zhí)行一條命令,看一看返回結(jié)果,然后在去執(zhí)行下一條命令,可惜翻遍全網(wǎng),竟然一個(gè)可行的方法都沒(méi)有!??!

沒(méi)辦法,自己想辦法解決吧。

實(shí)現(xiàn)代碼

廢話不多說(shuō),直接上代碼:

入口類

import core.CmdClient;

public class Main
{
    public static void main(String[] args)
    {
        CmdClient client = new CmdClient();
        client.run("cd /");
        client.run("ls");
        client.run("exit");
        System.out.println("主線程結(jié)束");
    }
}

核心代碼類:

這里就盡量不寫的太復(fù)雜,把多線程直接的交互都給砍掉了。大家可以根據(jù)自己需求去修改。

package core;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class CmdClient
{
    // 中文有亂碼的可以試著改一下編碼格式。
    private static final Charset charset = StandardCharsets.UTF_8;
    // 初始化
    public CmdClient()
    {
        try
        {
            /*
              Runtime.getRuntime().exec()方法本質(zhì)和windows上的運(yùn)行一樣,只能執(zhí)行一個(gè)命令來(lái)啟動(dòng)一個(gè)程序。
              這里啟動(dòng)的是sh解釋器,可以根據(jù)需要改成其他shell解釋器。適用mac,linux系統(tǒng)。
              對(duì)于windows,則是運(yùn)行C:\Windows\System32\cmd.exe,同時(shí)執(zhí)行的也不是shell命令,而是dos命令。
             */
            Process process = Runtime.getRuntime().exec("/bin/sh");
            // 獲取程序的輸出流和輸入流
            inputStream = process.getInputStream();
            errorStream = process.getErrorStream();
            outputStream = process.getOutputStream();
            /*
              輸出數(shù)據(jù)需要,若執(zhí)行的命令沒(méi)有輸出結(jié)果,就會(huì)阻塞讀取流的線程。
              為了防止主線程被阻塞,所以聲明新的線程專門盯著輸出數(shù)據(jù)。
             */
            new Thread(this::ReadCmdOut).start();
            new Thread(this::ReadCmdError).start();
        }
        catch (IOException e)
        { throw new RuntimeException("cmd初始化異常", e); }
        System.out.println("控制臺(tái)初始化完畢");
    }

    private final InputStream inputStream;
    private final InputStream errorStream;
    private final OutputStream outputStream;

    // 運(yùn)行命令
    public void run(String cmd)
    {
        try
        {
        	// 若執(zhí)行某些命令出現(xiàn)異常,可以嘗試更換 \n 為 \r 或 \n\r
            outputStream.write((cmd + "\n").getBytes(charset));
            outputStream.flush();
        }
        catch (Exception e)
        { throw new RuntimeException("命令執(zhí)行錯(cuò)誤:" + cmd, e); }
    }

    private void ReadCmdOut()
    {
        try
        { print(inputStream); }
        catch (Exception e)
        { throw new RuntimeException("獲取輸出流異常", e); }
        System.out.println("正常輸出流結(jié)束");
    }

    private void ReadCmdError()
    {
        try
        { print(errorStream); }
        catch (Exception e)
        { throw new RuntimeException("獲取錯(cuò)誤流異常", e); }
        System.out.println("異常輸出流結(jié)束");
    }

    /**
     * 這里直接把數(shù)據(jù)打印出來(lái)了,有其他需求的可以在這里寫判來(lái)確定下一步來(lái)執(zhí)行什么。
     */
    private void print(InputStream inputStream) throws IOException
    {
        byte[] bytes = new byte[1024];
        int i;
        while (true)
        {
            i = inputStream.read(bytes);
            if (i == -1) break;
            System.out.print(new String(bytes, 0, i, charset));
        }
        System.out.println();
    }
}

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

微山县| 镇雄县| 东兰县| 五家渠市| 耿马| 含山县| 彩票| 罗定市| 古蔺县| 新兴县| 广宗县| 蒙自县| 常山县| 丹巴县| 锡林浩特市| 遵义县| 彩票| 霍邱县| 罗田县| 刚察县| 青冈县| 保康县| 文山县| 甘德县| 沁水县| 奉化市| 武夷山市| 关岭| 上高县| 江陵县| 浑源县| 蛟河市| 庆元县| 合肥市| 泰来县| 浮山县| 尚义县| 台中县| 连南| 开化县| 闸北区|