java orion ssh scp 使用案例

首先得先下载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 
方法可以把文件发送到远程服务器。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值