get remoteFile from specific srcHost and directory

@return true or false
190628
public boolean scpGet(String remoteFile, String localDir, String dst, String instanceName) {
        LOG.info("remoteFile:" + remoteFile + " localdir:" + localDir +
                " dst:" + dst + " instanceName:" + instanceName);
        LOG.info("srchost:" + srcHost + "  dsthost:" + dstHost + "  amHost:" + amHost);

        ScpFrom scpFrom = new ScpFrom(srcHost, user, password);
        ScpTo scpTo = new ScpTo(dstHost, user, password);
        Exec exec = new Exec(srcHost, user, password);

        try {
            String execCommand = "cd " + remoteFile + " && cd .. && tar -cf " + instanceName + ".tar "
                    + instanceName;
            LOG.info("execCommand1:" + execCommand);
            exec.execute(execCommand);
            LOG.info("exec success");
        } catch (Exception ex) {
            try {
                exec = new Exec(srcHost, user, oldPassword);
                String execCommand = "cd " + remoteFile + " && cd .. && tar -cf " + instanceName + ".tar "
                        + instanceName;
                LOG.info("execCommand1:" + execCommand);
                exec.execute(execCommand);
                LOG.info("exec success");
            } catch (Exception eex) {
                LOG.error(eex);
                LOG.error("username:" + user + "  password:" + password);
                return false;
            }
        }

        try {
            //
            if (!amHost.split("/")[1].equals(srcHost) && !amHost.split("/")[0].equals(srcHost)) {
                scpFrom.getRemoteFile(remoteFile + ".tar", localDir);
                LOG.info("getRemoteFile:" + remoteFile + ".tar");
            }
        } catch (Exception ex) {
            try {
                scpFrom = new ScpFrom(srcHost, user, oldPassword);
                scpFrom.getRemoteFile(remoteFile + ".tar", localDir);
                LOG.info("getRemoteFile:" + remoteFile + ".tar");
            } catch (Exception eex) {
                LOG.error(eex);
                LOG.error("username:" + user + "  password:" + password);
                return false;
            }
        }

        try {
            if (!amHost.split("/")[1].equals(dstHost) && !amHost.split("/")[0].equals(dstHost)) {
                //put file to remote
                scpTo.putFile(localDir + instanceName + ".tar", localDir);
                LOG.info("putFileToRemote:" + remoteFile + ".tar");
            }
        } catch (Exception ex) {
            try {
                scpTo = new ScpTo(srcHost, user, oldPassword);
                scpTo.putFile(remoteFile + ".tar", localDir);
                LOG.info("putFileToRemote:" + remoteFile + ".tar");
            } catch (Exception eex) {
                LOG.error(eex);
                LOG.error("username:" + user + "  password:" + oldPassword);
                return false;
            }
        }

        try {
            Exec execRemote = new Exec(dstHost, user, password);
            execRemote.execute("cd " + localDir + "  &&  tar -xf " + instanceName + ".tar");
        } catch (Exception ex) {
            try {
                Exec execRemote = new Exec(dstHost, user, oldPassword);
                execRemote.execute("cd " + localDir + "  && tar -xf " + instanceName + ".tar");
            } catch (Exception eex) {
                LOG.error(eex);
                LOG.error("username:" + user + "  password:" + oldPassword);
                return false;
            }
        }

        return true;
    }
287195
def check_file_exists(self, remote_cmd=""):
        """"""
        if self.direction == "put":
            if not remote_cmd:
                remote_cmd = "dir {}{}".format(self.file_system, self.dest_file)
            remote_out = self.ssh_ctl_chan.send_command_expect(remote_cmd)
            search_string = r"{}.*Usage for".format(self.dest_file)
            if "No such file or directory" in remote_out:
                return False
            elif re.search(search_string, remote_out, flags=re.DOTALL):
                return True
            else:
                raise ValueError("Unexpected output from check_file_exists")
        elif self.direction == "get":
            return os.path.exists(self.dest_file)
803773
def gettextfile(remotefile, localfile = File.basename(remotefile), &block) # :yield: line
      f = open(localfile, "w")
      begin
	retrlines("RETR " + remotefile) do |line|
	  f.puts(line)
	  yield(line) if block
	end
      ensure
	f.close
      end
    end
1097185
public function download($remoteFile)
    {
        // 获取文件内容
        $http = wei()->http([
            'url' => $remoteFile,
            'timeout' => 10000,
            'referer' => true,
            'throwException' => false,
        ]);
        if (!$http->isSuccess()) {
            return false;
        }

        // 保存到本地
        $dir = wei()->upload->getDir() . '/' . $this->app->getId() . '/' . date('Ymd');
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        $file = $dir . time() . rand(1, 10000) . '.' . wei()->file->getExt($remoteFile);
        file_put_contents($file, $http->getResponse());

        return $file;
    }
610934
def get(self, remote, local=None):
        
        if isinstance(local, file_type):  # open file, leave open
            local_file = local
        elif local is None:  # return string
            local_file = buffer_type()
        else:  # path to file, open, write/close return None
            local_file = open(local, 'wb')

        self.conn.retrbinary("RETR %s" % remote, local_file.write)

        if isinstance(local, file_type):
            pass
        elif local is None:
            contents = local_file.getvalue()
            local_file.close()
            return contents
        else:
            local_file.close()

        return None
1224521
def getbinaryfile(remotefile, localfile = File.basename(remotefile),
		      blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data
      if @resume
	rest_offset = File.size?(localfile)
	f = open(localfile, "a")
      else
	rest_offset = nil
	f = open(localfile, "w")
      end
      begin
	f.binmode
	retrbinary("RETR " + remotefile, blocksize, rest_offset) do |data|
	  f.write(data)
	  yield(data) if block
	end
      ensure
	f.close
      end
    end
859352
public function cd($dir = null)
    {
        if (null === $this->_sftp_resource) {
            throw new TransportException(sprintf('None SSH connection available.'));
        }

        $dir = $this->_getAbsoluteRemotePath($dir);
        if (false === @ssh2_sftp_stat($this->_sftp_resource, $this->_remotepath)) {
            return $this->_trigger_error(sprintf('Unable to change remote directory to %s.', $this->_remotepath));
        }

        $this->_remotepath = $dir;

        return true;
    }
130145
def remote(self):
        
        from ambry.exc import NotFoundError

        ds = self.dataset

        if 'remote_name' not in ds.data:
            raise NotFoundError('Could not determine remote for partition: {}'.format(self.identity.fqname))

        return self._bundle.library.remote(ds.data['remote_name'])
1031730
def gettextfile(remotefile, localfile = File.basename(remotefile)) # :yield: line
      result = nil
      if localfile
        f = open(localfile, "w")
      elsif !block_given?
        result = ""
      end
      begin
	retrlines("RETR " + remotefile) do |line|
	  f.puts(line) if localfile
	  yield(line) if block_given?
          result.concat(line + "\n") if result
	end
        return result
      ensure
	f.close if localfile
      end
    end
718706
public boolean remoteExists(URI uri) throws IOException {
    try {
      FileSystems.matchSingleFileSpec(uri.toString());
      return true;
    } catch (FileNotFoundException e) {
      return false;
    }
  }
970808
public function download(String $remotePath, String $localPath, String $type = 'ascii') : Bool
    {
        if( ftp_get($this->connect, $localPath, $remotePath, Helper::toConstant($type, 'FTP_')) )
        {
            return true;
        }
        else
        {
            throw new FileRemoteDownloadException($localPath);
        }
    }
895488
public function get($remotePathname, $localPathname)
    {
        if (!$this->getScp()->get($remotePathname, $localPathname)) {
            throw new \RuntimeException(sprintf('Unable to get file "%s".', $remotePathname));
        }

        return $this;
    }
197328
public void get(String remoteFiles[], String localTargetDirectory) throws IOException {
        Session sess = null;

        if ((remoteFiles == null) || (localTargetDirectory == null))
            throw new IllegalArgumentException("Null argument.");

        if (remoteFiles.length == 0)
            return;

//        String cmd = "scp -f -r";
        String cmd = "scp -f ";

        for (int i = 0; i < remoteFiles.length; i++) {
            if (remoteFiles[i] == null)
                throw new IllegalArgumentException("Cannot accept null filename.");

            cmd += (" " + remoteFiles[i]);
        }

        try {
            sess = conn.openSession();
            sess.execCommand(cmd);
            receiveFiles(sess, remoteFiles, localTargetDirectory);
            sess.close();
        } catch (IOException e) {
            if (sess != null)
                sess.close();

            throw (IOException) new IOException("Error during SCP transfer.").initCause(e);
        }
    }
1073260
def check_file_exists(self, remote_cmd="dir home"):
        """"""
        if self.direction == "put":
            remote_out = self.ssh_ctl_chan.send_command_expect(remote_cmd)
            search_string = r"Directory contents .*{}".format(self.dest_file)
            return bool(re.search(search_string, remote_out, flags=re.DOTALL))
        elif self.direction == "get":
            return os.path.exists(self.dest_file)
284082
public function isWritable($remote_file)
    {
        $this->errorHandler->start();

        //remove slashes at beginning and end of dir's, beginning of file
        $dir = substr($this->configuration->getDir(), 0, 1) == '/' ? substr($this->configuration->getDir(), 1) : $this->configuration->getDir();
        $dir = substr($dir, -1, 1) == '/' ? substr($dir, 0, -1) : $dir;
        $remote_file = substr($remote_file, 0, 1) == '/' ? substr($remote_file, 1) : $remote_file;

        //get path info setup properly.
        $dirname = pathinfo('/' . $dir . '/' . $remote_file);
        $dirname = $dirname['dirname'];

        //get a directory listing and check that the file in question is listed (workaround for file_exists)
        $dirlist = $this->driver->nlist($this->resource, $dirname);
        if (is_array($dirlist) && in_array("/$dir/$remote_file", $dirlist)) {
            //file exists, check if we can open the file for appending
            if (!$handle = $this->driver->fopen($dir . '/' . $remote_file, 'a', $this->configuration)) {
                $this->errorHandler->stop();

                return false;
            }

            //attempt to do an empty append
            if (!fwrite($handle, '') === FALSE) {
                $this->errorHandler->stop();

                return false;
            }
            $this->errorHandler->stop();

            return true;
        }

        //file not found, return false
        $this->errorHandler->stop();

        return false;
    }
429749
public function get($localFile, $remoteFile, $resumePosision = 0)
    {
        $mode = $this->getMode();
        $result = @ftp_get($this->connection, $localFile, $remoteFile, $mode, $resumePosision);

        if ($result === false)
        {
            throw new Exception(sprintf('Unable to get or save file "%s" from %s', $localFile, $remoteFile));
        }

        return $this;
    }
814462
def download(self, localfile: str, remotefile: str, overwrite: bool = True, **kwargs):
      
      valid = self._sb.file_info(remotefile, quiet = True)

      if valid is None:
         return {'Success' : False, 
                 'LOG'     : "File "+str(remotefile)+" does not exist."}

      if valid == {}:
         return {'Success' : False, 
                 'LOG'     : "File "+str(remotefile)+" is a directory."}

      if os.path.isdir(localfile):
         locf = localfile + os.sep + remotefile.rpartition(self._sb.hostsep)[2]
      else:
         locf = localfile

      try:
         fd = open(locf, 'wb')
      except OSError as e:
         return {'Success' : False, 
                 'LOG'     : "File "+str(locf)+" could not be opened. Error was: "+str(e)}

      port =  kwargs.get('port', 0)

      if port==0 and self.sascfg.tunnel:
         # we are using a tunnel; default to that port
         port = self.sascfg.tunnel

      try:
         sock = socks.socket()
         if self.sascfg.tunnel:
            sock.bind(('localhost', port))
         else:
            sock.bind(('', port))
         port = sock.getsockname()[1]
      except OSError:
         return {'Success' : False, 
                 'LOG'     : "Error try to open a socket in the download method. Call failed."}

      if self.sascfg.ssh:
         if not self.sascfg.tunnel:
            host = self.sascfg.hostip #socks.gethostname()
         else:
            host = 'localhost'
      else:
         host = ''

      code = """
         filename saspydir '"""+remotefile+"""' recfm=F encoding=binary lrecl=4096;
         filename sock socket '"""+host+""":"""+str(port)+"""' recfm=S encoding=binary;
         data _null_;
         file sock;
         infile saspydir;
         input;
         put _infile_;
         run;\n"""

      sock.listen(1)
      self._asubmit(code, 'text')

      datar = b''

      newsock = (0,0)
      try:
         newsock = sock.accept()
         while True:
            data = newsock[0].recv(4096)

            if len(data):
               datar += data
            else:
               if len(datar):
                  fd.write(datar)
               break
            if len(datar) > 8300:
               fd.write(datar[:8192])
               datar = datar[8192:]
      except:
         if newsock[0]:
            newsock[0].shutdown(socks.SHUT_RDWR)
            newsock[0].close()
         sock.close()
         fd.close()
         ll = self.submit("filename saspydir;", 'text')
         return {'Success' : False, 
                 'LOG'     : "Download was interupted. Returning the SAS log:\n\n"+ll['LOG']}

      newsock[0].shutdown(socks.SHUT_RDWR)
      newsock[0].close()
      sock.close()

      fd.flush()
      fd.close()

      ll = self.submit("filename saspydir;", 'text')
      return {'Success' : True, 
              'LOG'     : ll['LOG']}