Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public String runCommand(String command) {
- String host = "XX.XX.X.XX";
- String user = "user";
- String password = "password";
- String result = "";
- try{
- Properties config = new Properties();
- config.put("StrictHostKeyChecking", "no");
- JSch jsch = new JSch();
- // Create a JSch session to connect to the server
- Session session = jsch.getSession(user, host, 22);
- session.setPassword(password);
- session.setConfig(config);
- // Establish the connection
- session.connect();
- if(session.isConnected()) {
- System.out.println("Connected...");
- }
- ChannelExec channel = (ChannelExec) session.openChannel("exec");
- channel.setCommand("pwd");
- int stat = channel.getExitStatus();
- StringBuilder outputBuffer = new StringBuilder();
- StringBuilder errorBuffer = new StringBuilder();
- InputStream in = channel.getInputStream();
- InputStream err = channel.getExtInputStream();
- channel.setPty(true);
- channel.connect();
- System.out.println("Channel Connected");
- System.out.println("channel.isConnected() "+channel.isConnected());
- System.out.println("channel.isClosed() "+channel.isClosed());
- byte[] tmp = new byte[1024];
- while (true) {
- while (in.available() > 0) {
- int i = in.read(tmp, 0, 1024);
- if (i < 0) break;
- outputBuffer.append(new String(tmp, 0, i));
- }
- while (err.available() > 0) {
- int i = err.read(tmp, 0, 1024);
- if (i < 0) break;
- errorBuffer.append(new String(tmp, 0, i));
- }
- if (channel.isClosed()) {
- if ((in.available() > 0) || (err.available() > 0)) continue;
- System.out.println("exit-status: " + channel.getExitStatus());
- break;
- }
- try {
- Thread.sleep(1000);
- } catch (Exception ee) {
- }
- }
- System.out.println("output: " + outputBuffer.toString());
- System.out.println("error: " + errorBuffer.toString());
- channel.disconnect();
- session.disconnect();
- System.out.println("Channel And Session Closed!!!");
- }catch(JSchException e){
- e.printStackTrace();
- result = "Auth fail";
- }catch(Exception e){
- e.printStackTrace();
- }
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement