免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 5286 | 回复: 0

Ganymed SSH-2 for Java 示例 [复制链接]

论坛徽章:
0
发表于 2010-02-01 10:29 |显示全部楼层
The most often source of problems when executing a command with Session.execCommand() are missing/wrong set environment variables on the remote machine.

so don't use Session.execCommand(), instead aquire a pty (pseudo terminal) and then start a shell (use Session.requestPTY() and Session.startShell()). You then have to communicate with the shell process at the other end through stdin and stdout. However, you also have to implement terminal logic (e.g., escape sequence handling (unless you use a "dumb" pty), "expect-send" logic (output parsing, shell prompt detection), etc.).

package c1;
import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Test4 {
    public static void main(String args[]) {
     try
  {
   /* Create a connection instance */
   Connection conn = new Connection("127.0.0.1");
   
   /* Now connect */
   conn.connect();
   /* Authenticate */
   boolean isAuthenticated = conn.authenticateWithPassword("username","password");
   if (isAuthenticated == false)
    throw new IOException("Authentication failed. Please check hostname, username and password.");
   /* Create a session */
   Session sess = conn.openSession();
   // sess.execCommand("uname -a && date && uptime && who");
   System.out.println("start exec command.......");
   
   //sess.execCommand("echo \"Text on STDOUT\"; echo \"Text on STDERR\" >&2");
   //sess.execCommand("env");
            sess.requestPTY("bash");
            
            sess.startShell();
            
            
   InputStream stdout = new StreamGobbler(sess.getStdout());
   InputStream stderr = new StreamGobbler(sess.getStderr());

   BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
   BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));
   
   //if you want to use sess.getStdin().write(), here is a sample
   //byte b[]={'e','n','v','\n'};
   //byte b[]={'e','x','i','t','\n'};
   //sess.getStdin().write(b)
/*   
String str="env";
   String str1="exit";
   System.out.println(str+str1);
   out.write(str.getBytes());
   out.write('\n');
   out.write(str1.getBytes());
   out.write('\n');
*/
   //we used PrintWriter, it makes things simple
   PrintWriter out =new PrintWriter(sess.getStdin());
   out.println("env");
   out.println("exit");
   out.close();
   sess.waitForCondition(ChannelCondition.CLOSED | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS, 30000);
   
   System.out.println("Here is the output from stdout:");
   
   while (true)
   {
    String line = stdoutReader.readLine();
    if (line == null)
     break;
    System.out.println(line);
   }
   System.out.println("Here is the output from stderr:");
   while (true)
   {
    String line = stderrReader.readLine();
    if (line == null)
     break;
    System.out.println(line);
   }
   /* Show exit status, if available (otherwise "null") */
   System.out.println("ExitCode: " + sess.getExitStatus());
   sess.close();/* Close this session */   
   conn.close();/* Close the connection */

  }
  catch (IOException e)
  {
   e.printStackTrace(System.err);
   System.exit(2);
  }
  }
    }


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/19919/showart_2166145.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP