java如何连续执行多条cmd命令
作者:薛8 时间:2023-07-13 13:10:41
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 });
/**
* 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 });
/**
* 某些设备回显数据中的控制字符
*/
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);
}
}
来源:https://blog.csdn.net/xueba8/article/details/78945954
标签:java,执行,cmd命令
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android 悬浮窗权限各机型各系统适配大全(总结)
2022-04-27 10:09:53
![](https://img.aspxhome.com/file/2023/1/139171_0s.png)
c# WPF中自定义加载时实现带动画效果的Form和FormItem
2021-05-29 22:49:17
![](https://img.aspxhome.com/file/2023/0/88420_0s.gif)
Android填坑系列:在小米系列等机型上放开定位权限后的定位请求弹框示例
2022-03-29 15:15:49
![](https://img.aspxhome.com/file/2023/1/94281_0s.png)
java selenium教程环境搭建基于Maven
2023-11-27 01:35:38
java实现变更文件查询的方法
2022-07-29 04:55:37
基于android studio的layout的xml文件的创建方式
2022-10-31 10:52:06
![](https://img.aspxhome.com/file/2023/3/138563_0s.jpg)
java文件输出流写文件的几种方法
2023-11-08 16:17:30
浅析C#中静态方法和非静态方法的区别
2023-04-07 07:55:15
![](https://img.aspxhome.com/file/2023/3/91283_0s.png)
Java中接口和抽象类的区别详解
2022-09-28 15:21:19
win10和win7下java开发环境配置教程
2022-05-01 05:34:22
![](https://img.aspxhome.com/file/2023/6/79866_0s.png)
Java Socket实现多人聊天系统
2023-08-08 04:44:35
![](https://img.aspxhome.com/file/2023/2/65322_0s.jpg)
在Java中int和byte[]的相互转换
2023-09-23 15:35:45
Android使用ListView实现下拉刷新及上拉显示更多的方法
2023-01-10 04:29:45
Java多种经典排序算法(含动态图)
2023-09-24 00:45:02
![](https://img.aspxhome.com/file/2023/3/84243_0s.png)
基于socket和javaFX简单文件传输工具
2022-11-04 12:37:42
C# 显示、隐藏窗口对应的任务栏
2023-06-13 03:57:32
![](https://img.aspxhome.com/file/2023/3/87053_0s.png)
springmvc限流拦截器的示例代码
2021-09-08 02:50:55
![](https://img.aspxhome.com/file/2023/1/64761_0s.gif)
Java class文件格式之常量池_动力节点Java学院整理
2023-04-14 07:14:06
![](https://img.aspxhome.com/file/2023/2/66472_0s.jpg)
Android之ListView分页加载数据功能实现代码
2023-08-13 03:44:17
![](https://img.aspxhome.com/file/2023/4/126794_0s.png)
Spring main方法中如何调用Dao层和Service层的方法
2023-11-28 23:15:19
![](https://img.aspxhome.com/file/2023/3/60753_0s.png)