天天看点

JCraft通过SSH进行交互式指令发送

private String executeCommand(String host, String user, String password, ArrayList<String> cmds) {
		JSch jsch = new JSch();
		String result = "";

	//	Channel channel = null;
		Session session = null;
		ChannelShell channelShell=null;
		try {
			session = jsch.getSession(user, host, 22);
			session.setPassword(password);
			session.setServerAliveCountMax(0);
			UserInfo ui = new MyUserInfo() {
				public void showMessage(String message) {
					System.out.println(message);
				}

				public boolean promptYesNo(String message) {
					return true;
				}
			};

			session.setUserInfo(ui);

			session.connect(30000); // making a connection with timeout.

			/*
			 * channel = session.openChannel("shell"); String cmdsString = ""; for (String
			 * cmd : cmds) { cmdsString += cmd+" \r\n"; } System.out.println(cmdsString);
			 * InputStream is = new ByteArrayInputStream(cmdsString.getBytes());
			 * channel.setInputStream(is); ByteArrayOutputStream baos = new
			 * ByteArrayOutputStream(); channel.setOutputStream(baos);
			 * System.out.println("channel1:" + channel.isConnected());
			 * channel.connect(30000); TimeUnit.SECONDS.sleep(5); String tmpResult = new
			 * String(baos.toByteArray()); // channel.connect(30000); // result+=tmpResult;
			 * System.out.println(tmpResult);
			 * 
			 */

			channelShell = (ChannelShell) session.openChannel("shell");
			channelShell.connect(3000);
			InputStream inputStream = channelShell.getInputStream();
			OutputStream outputStream = channelShell.getOutputStream();

			for (String cmd : cmds) {
				outputStream.write((cmd + " \n\r").getBytes());
				outputStream.flush();
				TimeUnit.SECONDS.sleep(1);
				// BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
				System.out.println(cmd);
				byte[] tmp = new byte[1024];
				while (true) {
					while (inputStream.available() > 0) {
						int i = inputStream.read(tmp, 0, 1024);
						if (i < 0)
							break;
						System.out.println(new String(tmp, 0, i));
					}
					TimeUnit.SECONDS.sleep(1);
					if (channelShell.isClosed()) {
						if (inputStream.available() > 0)
							continue;
						System.out.println("exit-status: " + channelShell.getExitStatus());
						break;
					}
					break;
					// inputStream.close();
				}
			}

		} catch (JSchException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (channelShell != null)
				channelShell.disconnect();
			if(session!=null)
				session.disconnect();
		}
		return result;
	}