阳光网驿-企业信息化交流平台【DTC零售连锁全渠道解决方案】

 找回密码
 注册

QQ登录

只需一步,快速开始

扫描二维码登录本站

手机号码,快捷登录

手机号码,快捷登录

老司机
查看: 1021|回复: 0

[转帖] Java应用程序远程登录linux并执行其命令

[复制链接]
  • TA的每日心情
    郁闷
    2012-3-7 10:18
  • 签到天数: 1 天

    [LV.1]初来乍到

    发表于 2012-1-5 10:53:15 | 显示全部楼层 |阅读模式
    ganymed.ethz.ch/ssh2/在这个网址下载一个调用ssh和scp命令的jar包。  然后,就可以写程序了。将上面的jar包导入MyEclipse,上面是一个类的实例代码。   packagehh;   importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;   importch.ethz.ssh2.Connection;importch.ethz.ssh2.Session;importch.ethz.ssh2.StreamGobbler;   publicclassBasic   {   publicstaticvoidmain(String[]args)   {   Stringhostname="222.177.211.9";   Stringusername="boss";   Stringpassword="qwer@1234";   try   {   /*Createaconnectioninstance*/   Connectionconn=newConnection(hostname);   /*Nowconnect*/   conn.connect();   /*Authenticate*/   booleanisAuthenticated=conn.authenticateWithPassword(username,password);   if(isAuthenticated==false)   thrownewIOException("Authenticationfailed.");   /*Createasession*/   Sessionsess=conn.openSession();   //sess.execCommand("uname-adateuptimewho");   sess.execCommand("psaux");   System.out.println("Hereissomeinformationabouttheremotehost:");   InputStreamstdout=newStreamGobbler(sess.getStdout());   BufferedReaderbr=newBufferedReader(newInputStreamReader(stdout));   while(true)   {   Stringline=br.readLine();   if(line==null)   break;   System.out.println(line);   }   /*Showexitstatus,ifavailable(otherwise"null")*/   System.out.println("ExitCode:"+sess.getExitStatus());   /*Closethissession*/   sess.1close();   /*Closetheconnection*/   conn.close();   }   catch(IOExceptione)   {   e.printStackTrace(System.err);System.exit(2);   }   }   }   在控制台我们将看到输入结果。  很简单,不过,了解其中的原理,要费一番的周折了,当前再给大家讲一些原理方面的东西。
    楼主热帖
    启用邀请码注册,提高发帖质量,建设交流社区
    您需要登录后才可以回帖 登录 | 注册

    本版积分规则

    快速回复 返回顶部 返回列表