java orion ssh scp 使用案例

来源:互联网 发布:淘宝读书官方版 编辑:程序博客网 时间:2024/04/30 19:24

首先得先下载orion-ssh2-214.jar包。


把jar包加入你的classpath然后就可以使用了。

SSH的使用方法如下:

/**   * 执行远程的封存脚本   * @param host   * @param username   * @param password   */  public static List<String> runRomoteScript(String host, String username, String password, String cmd) throws Exception  {  List<String> result = new ArrayList<String>();      Connection conn = new Connection(host);      conn.connect();      boolean isAuthenticated = conn.authenticateWithPassword(username, password);      if (isAuthenticated == false)      throw new RuntimeException("权限不够");      Session sess = conn.openSession();      sess.execCommand(cmd);      InputStream stdout = new StreamGobbler(sess.getStdout());      BufferedReader br = new BufferedReader(new InputStreamReader(stdout));      while (true)      {      String line = br.readLine();      if (line == null)      break;      System.out.println(line);      result.add(line);      }      sess.close();      conn.close();      return result;  }

从远程获取文件:

/*   * 命令成功执行   */  public static final String SUCCESS = "SUCCESS";    /**   * 从远程服务器下载文件到本地文件夹   * @param host   * @param username   * @param password   * @param romoteFileName   * @param localDir   */  public static String getFileFromRemote(String host, String username, String password, String romoteFileName, String localDir)  {    String msg = SSHUtil.SUCCESS;    try    {      Connection conn = new Connection(host);      conn.connect();      boolean isAuthenticated = conn.authenticateWithPassword(username, password);      if (isAuthenticated == false)        return "权限不够!";      File inputFile = new File(localDir);      if(!inputFile.exists())     //如果文件夹不存在,则新建文件夹      {        inputFile.mkdirs();      }      SCPClient scpClient = conn.createSCPClient();      scpClient.get(romoteFileName, localDir);      conn.close();    }    catch (IOException e)    {      return "出现了IO错误!";    }    return msg;  }
以上代码经测试,运行正常,请放心使用。
SCPClient.put 
方法可以把文件发送到远程服务器。


原创粉丝点击