服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java如何连续执行多条cmd命令

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

2021-11-13 13:19薛8 Java教程

这篇文章主要介绍了java如何连续执行多条cmd命令的方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

java连续执行多条cmd命令

命令之间用&连接

例如:

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

java ssh登录执行多条cmd命令

java登录ssh执行多条命令,解决出现more自动回车的问题

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
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教程Java使用SAX解析xml的示例

    Java使用SAX解析xml的示例

    这篇文章主要介绍了Java使用SAX解析xml的示例,帮助大家更好的理解和学习使用Java,感兴趣的朋友可以了解下...

    大行者10067412021-08-30
  • Java教程20个非常实用的Java程序代码片段

    20个非常实用的Java程序代码片段

    这篇文章主要为大家分享了20个非常实用的Java程序片段,对java开发项目有所帮助,感兴趣的小伙伴们可以参考一下 ...

    lijiao5352020-04-06
  • Java教程Java BufferWriter写文件写不进去或缺失数据的解决

    Java BufferWriter写文件写不进去或缺失数据的解决

    这篇文章主要介绍了Java BufferWriter写文件写不进去或缺失数据的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望...

    spcoder14552021-10-18
  • Java教程Java实现抢红包功能

    Java实现抢红包功能

    这篇文章主要为大家详细介绍了Java实现抢红包功能,采用多线程模拟多人同时抢红包,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙...

    littleschemer13532021-05-16
  • Java教程Java8中Stream使用的一个注意事项

    Java8中Stream使用的一个注意事项

    最近在工作中发现了对于集合操作转换的神器,java8新特性 stream,但在使用中遇到了一个非常重要的注意点,所以这篇文章主要给大家介绍了关于Java8中S...

    阿杜7482021-02-04
  • Java教程xml与Java对象的转换详解

    xml与Java对象的转换详解

    这篇文章主要介绍了xml与Java对象的转换详解的相关资料,需要的朋友可以参考下...

    Java教程网2942020-09-17
  • Java教程小米推送Java代码

    小米推送Java代码

    今天小编就为大家分享一篇关于小米推送Java代码,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧...

    富贵稳中求8032021-07-12
  • Java教程升级IDEA后Lombok不能使用的解决方法

    升级IDEA后Lombok不能使用的解决方法

    最近看到提示IDEA提示升级,寻思已经有好久没有升过级了。升级完毕重启之后,突然发现好多错误,本文就来介绍一下如何解决,感兴趣的可以了解一下...

    程序猿DD9332021-10-08