java如何連續(xù)執(zhí)行多條cmd命令
java連續(xù)執(zhí)行多條cmd命令
命令之間用&連接
例如:
Process p = Runtime.getRuntime().exec("cmd /c d: & cd bin/");
java ssh登錄執(zhí)行多條cmd命令
java登錄ssh執(zhí)行多條命令,解決出現(xiàn)more自動回車的問題
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.jcraft.jsch.Channel; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.UIKeyboardInteractive; import com.jcraft.jsch.UserInfo; public class JavaSsh implements Runnable { protected Logger logger = LogManager.getLogger(); /** * 退格 */ private static final String BACKSPACE = new String(new byte[] { 8 }); /** * ESC */ private static final String ESC = new String(new byte[] { 27 }); /** * 空格 */ private static final String BLANKSPACE = new String(new byte[] { 32 }); /** * 回車 */ private static final String ENTER = new String(new byte[] { 13 }); /** * 某些設(shè)備回顯數(shù)據(jù)中的控制字符 */ private static final String[] PREFIX_STRS = { BACKSPACE + "+" + BLANKSPACE + "+" + BACKSPACE + "+", "(" + ESC + "\\[\\d+[A-Z]" + BLANKSPACE + "*)+" }; private int sleepTime = 200; /** * 連接超時(shí)(單次命令總耗時(shí)) */ private int timeout = 4000; /** * 保存當(dāng)前命令的回顯信息 */ protected StringBuffer currEcho; /** * 保存所有的回顯信息 */ protected StringBuffer totalEcho; private String ip; private int port; private String endEcho = "#,?,>,:"; private String moreEcho = "---- More ----"; private String moreCmd = BLANKSPACE; private JSch jsch = null; private Session session; private Channel channel; @Override public void run() { InputStream is; try { is = channel.getInputStream(); String echo = readOneEcho(is); while (echo != null) { currEcho.append(echo); String[] lineStr = echo.split("\\n"); if (lineStr != null && lineStr.length > 0) { String lastLineStr = lineStr[lineStr.length - 1]; if (lastLineStr != null && lastLineStr.indexOf(moreEcho) > 0) { totalEcho.append(echo.replace(lastLineStr, "")); } else { totalEcho.append(echo); } } echo = readOneEcho(is); } } catch (IOException e) { e.printStackTrace(); } } protected String readOneEcho(InputStream instr) { byte[] buff = new byte[1024]; int ret_read = 0; try { ret_read = instr.read(buff); } catch (IOException e) { return null; } if (ret_read > 0) { String result = new String(buff, 0, ret_read); for (String PREFIX_STR : PREFIX_STRS) { result = result.replaceFirst(PREFIX_STR, ""); } try { return new String(result.getBytes(), "GBK"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } else { return null; } } public JavaSsh(String ip, int port, String endEcho, String moreEcho) { this.ip = ip; this.port = port; if (endEcho != null) { this.endEcho = endEcho; } if (moreEcho != null) { this.moreEcho = moreEcho; } totalEcho = new StringBuffer(); currEcho = new StringBuffer(); } private void close() { if (session != null) { session.disconnect(); } if (channel != null) { channel.disconnect(); } } private boolean login(String[] cmds) { String user = cmds[0]; String passWord = cmds[1]; jsch = new JSch(); try { session = jsch.getSession(user, this.ip, this.port); session.setPassword(passWord); UserInfo ui = new SSHUserInfo() { public void showMessage(String message) { } public boolean promptYesNo(String message) { return true; } }; session.setUserInfo(ui); session.connect(30000); channel = session.openChannel("shell"); channel.connect(3000); new Thread(this).start(); try { Thread.sleep(sleepTime); } catch (Exception e) { } return true; } catch (JSchException e) { return false; } } protected void sendCommand(String command, boolean sendEnter) { try { OutputStream os = channel.getOutputStream(); os.write(command.getBytes()); os.flush(); if (sendEnter) { currEcho = new StringBuffer(); os.write(ENTER.getBytes()); os.flush(); } } catch (IOException e) { e.printStackTrace(); } } protected boolean containsEchoEnd(String echo) { boolean contains = false; if (endEcho == null || endEcho.trim().equals("")) { return contains; } String[] eds = endEcho.split(","); for (String ed : eds) { if (echo.trim().endsWith(ed)) { contains = true; break; } } return contains; } private String runCommand(String command, boolean ifEnter) { currEcho = new StringBuffer(); sendCommand(command, ifEnter); int time = 0; if (endEcho == null || endEcho.equals("")) { while (currEcho.toString().equals("")) { try { Thread.sleep(sleepTime); time += sleepTime; if (time >= timeout) { break; } } catch (InterruptedException e) { e.printStackTrace(); } } } else { while (!containsEchoEnd(currEcho.toString())) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } time += sleepTime; if (time >= timeout) { break; } String[] lineStrs = currEcho.toString().split("\\n"); if (lineStrs != null && lineStrs.length > 0) { if (moreEcho != null && lineStrs[lineStrs.length - 1] != null && lineStrs[lineStrs.length - 1].contains(moreEcho)) { sendCommand(moreCmd, false); currEcho.append("\n"); time = 0; continue; } } } } return currEcho.toString(); } private String batchCommand(String[] cmds, int[] othernEenterCmds) { StringBuffer sb = new StringBuffer(); for (int i = 2; i < cmds.length; i++) { String cmd = cmds[i]; if (cmd.equals("")) { continue; } boolean ifInputEnter = false; if (othernEenterCmds != null) { for (int c : othernEenterCmds) { if (c == i) { ifInputEnter = true; break; } } } cmd += (char) 10; String resultEcho = runCommand(cmd, ifInputEnter); sb.append(resultEcho); } close(); return totalEcho.toString(); } public String executive(String[] cmds, int[] othernEenterCmds) { if (cmds == null || cmds.length < 3) { logger.error("{} ssh cmds is null", this.ip); return null; } if (login(cmds)) { return batchCommand(cmds, othernEenterCmds); } logger.error("{} ssh login error", this.ip); return null; } private abstract class SSHUserInfo implements UserInfo, UIKeyboardInteractive { public String getPassword() { return null; } public boolean promptYesNo(String str) { return true; } public String getPassphrase() { return null; } public boolean promptPassphrase(String message) { return true; } public boolean promptPassword(String message) { return true; } public void showMessage(String message) { } public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { return null; } } public static void main(String[] args) { String ip = "192.168.0.238"; int port = 22; JavaSsh JavaSsh2 = new JavaSsh(ip, port, null, null); String username = "ssh"; String password = "yzfar.com"; String[] cmds = { username, password, "display mac-address", "display mac-address" }; String executive = JavaSsh2.executive(cmds, null); System.out.println(executive); } }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Kafka在客戶端實(shí)現(xiàn)消息的發(fā)送與讀取
這篇文章主要介紹了Kafka在客戶端實(shí)現(xiàn)消息的發(fā)送與讀取,KafkaProducer是用于發(fā)送消息的類,ProducerRecord類用于封裝Kafka的消息,KafkaProducer的實(shí)例化需要指定的參數(shù),Producer的參數(shù)定義在 org.apache.kafka.clients.producer.ProducerConfig類中,需要的朋友可以參考下2023-12-12Java每7天日志自動清理的項(xiàng)目實(shí)踐
在實(shí)際項(xiàng)目中由于服務(wù)器內(nèi)存有限,人工清理常會忘記,本文主要介紹了Java每7天日志自動清理的項(xiàng)目實(shí)踐,具有一定的參考價(jià)值,感興趣的可以了解一下2024-01-01SpringBoot環(huán)境屬性占位符解析和類型轉(zhuǎn)換方式
這篇文章主要介紹了SpringBoot環(huán)境屬性占位符解析和類型轉(zhuǎn)換方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11java web用servlet監(jiān)聽器實(shí)現(xiàn)顯示在線人數(shù)
這篇文章主要為大家詳細(xì)介紹了java web用servlet監(jiān)聽器實(shí)現(xiàn)顯示在線人數(shù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03Java并發(fā)編程之CountDownLatch的使用
CountDownLatch是一個(gè)倒數(shù)的同步器,常用來讓一個(gè)線程等待其他N個(gè)線程執(zhí)行完成再繼續(xù)向下執(zhí)行,本文主要介紹了CountDownLatch的具體使用方法,感興趣的可以了解一下2023-05-05java并發(fā)高的情況下用ThreadLocalRandom來生成隨機(jī)數(shù)
如果我們想要生成一個(gè)隨機(jī)數(shù),通常會使用Random類。但是在并發(fā)情況下Random生成隨機(jī)數(shù)的性能并不是很理想,本文主要介紹了java并發(fā)高的情況下用ThreadLocalRandom來生成隨機(jī)數(shù),感興趣的可以了解一下2022-05-05Spring?Security權(quán)限管理小結(jié)
SpringSecurity是一個(gè)權(quán)限管理框架,核心是認(rèn)證和授權(quán),前面已經(jīng)系統(tǒng)的給大家介紹過了認(rèn)證的實(shí)現(xiàn)和源碼分析,本文重點(diǎn)來介紹下權(quán)限管理,需要的朋友可以參考下2022-08-08java驗(yàn)證用戶是否已經(jīng)登錄 java實(shí)現(xiàn)自動登錄
這篇文章主要介紹了java驗(yàn)證用戶是否已經(jīng)登錄,java實(shí)現(xiàn)自動登錄,感興趣的小伙伴們可以參考一下2016-04-04