文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

java如何连续执行多条cmd命令

2024-04-02 19:55

关注

java连续执行多条cmd命令

命令之间用&连接

例如:


Process p = Runtime.getRuntime().exec("cmd /c d: & cd bin/");  

java ssh登录执行多条cmd命令

java登录ssh执行多条命令,解决出现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 });
 
	
	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 });
 
	
	private static final String[] PREFIX_STRS = { BACKSPACE + "+" + BLANKSPACE + "+" + BACKSPACE + "+",
			"(" + ESC + "\\[\\d+[A-Z]" + BLANKSPACE + "*)+" };
 
	private int sleepTime = 200;
 
	
	private int timeout = 4000;
 
	
	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);
	}
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯