java使用ganymed-ssh2执行linux操作系统命令

阅读更多

public static void main(String[] args) {

InputStream msgStream;

BufferedReader buffer;

String line;

Connection conn = new Connection("远程主机地址");

Session session = null;

try {

   conn.connect();

   conn.authenticateWithPassword("root", "      ");

   session = conn.openSession();

//这里使用&&连接多条命令可以解决其中一条命令执行失败后,立即返回失败的状态。而不是根据最后一条命令执行的结果返回状态。

   session.execCommand("cd /home/slg&&ls");

   session.waitForCondition(ChannelCondition.EXIT_STATUS, 1000);

   System.out.println(session.getExitStatus());

   msgStream = new SequenceInputStream(session.getStdout(),

   session.getStderr());

   buffer = new BufferedReader(new InputStreamReader(msgStream));

   try {

while ((line = buffer.readLine()) != null) {

   System.out.println(line);

}

   } catch (IOException e) {

e.printStackTrace();

   } finally {

try {

   buffer.close();

   msgStream.close();

} catch (IOException e) {

   e.printStackTrace();

}

   }

   session.close();

   session = conn.openSession();

//通过这种方式可以模拟Shell窗口

   session.requestDumbPTY();

   session.startShell();

   PrintWriter pw = new PrintWriter(session.getStdin());

   pw.println("cd /home/slg");

   pw.println("ls");

   pw.close();

   msgStream = session.getStdout();

   buffer = new BufferedReader(new InputStreamReader(msgStream));

   try {

while ((line = buffer.readLine()) != null) {

   System.out.println(line);

}

   } catch (IOException e) {

e.printStackTrace();

   } finally {

try {

   buffer.close();

   msgStream.close();

} catch (IOException e) {

   e.printStackTrace();

}

   }

   session.close();

   conn.close();

} catch (Exception e) {

   e.printStackTrace();

}

    }

你可能感兴趣的:(java使用ganymed-ssh2执行linux操作系统命令)