scp a file or files to a remote system
320770
def send(self, local, remote, makedirs=False):
        '''
        
        '''
        if makedirs:
            self.exec_cmd('mkdir -p {0}'.format(os.path.dirname(remote)))

        # scp needs [<ipv6}
        host = self.host
        if ':' in host:
            host = '[{0}]'.format(host)

        cmd = '{0} {1}:{2}'.format(local, host, remote)
        cmd = self._cmd_str(cmd, ssh='scp')

        logmsg = 'Executing command: {0}'.format(cmd)
        if self.passwd:
            logmsg = logmsg.replace(self.passwd, ('*' * 6))
        log.debug(logmsg)

        return self._run_cmd(cmd)
472861
def send_file_to_remote(dev, src_file, dst_filename, filesize, dst_mode='wb'):
    
    bytes_remaining = filesize
    save_timeout = dev.timeout
    dev.timeout = 1
    while bytes_remaining > 0:
        # Wait for ack so we don't get too far ahead of the remote
        ack = dev.read(1)
        if ack is None or ack != b'\x06':
            sys.stderr.write("timed out or error in transfer to remote\n")
            sys.exit(2)

        if HAS_BUFFER:
            buf_size = BUFFER_SIZE
        else:
            buf_size = BUFFER_SIZE // 2
        read_size = min(bytes_remaining, buf_size)
        buf = src_file.read(read_size)
        #sys.stdout.write('\r%d/%d' % (filesize - bytes_remaining, filesize))
        #sys.stdout.flush()
        if HAS_BUFFER:
            dev.write(buf)
        else:
            dev.write(binascii.hexlify(buf))
        bytes_remaining -= read_size
    #sys.stdout.write('\r')
    dev.timeout = save_timeout
1247321
def ssh(cmd=''):
    '''
    
    '''
    with settings(warn_only=True):
        local('ssh -A -o StrictHostKeyChecking=no -i "%s" %s@%s "%s"' % (
            env.key_filename, env.user, env.host, cmd))
174368
def relative_to_remote_path(path)
      if path && path.length > 0
        File.join(remote_path, path)
      else
        remote_path
      end
    end
315679
def remote_file_exists(self, url):
        
        status = requests.head(url).status_code

        if status != 200:
            raise RemoteFileDoesntExist
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);
        }
    }
1167841
def send_file(self, local_path, remote_path, user='root', unix_mode=None):
        
        self.enable_user(user)
        return self.ssh_pool.send_file(user, local_path, remote_path, unix_mode=unix_mode)
605931
def put_file(self, in_path, out_path):
        '''  '''
        vvv("PUT %s TO %s" % (in_path, out_path), host=self.host)
        if not os.path.exists(in_path):
            raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
        cmd = self._password_cmd()

        if C.DEFAULT_SCP_IF_SSH:
            cmd += ["scp"] + self.common_args
            cmd += [in_path,self.host + ":" + out_path]
            indata = None
        else:
            cmd += ["sftp"] + self.common_args + [self.host]
            indata = "put %s %s\n" % (in_path, out_path)

        p = subprocess.Popen(cmd, stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        self._send_password()
        stdout, stderr = p.communicate(indata)

        if p.returncode != 0:
            raise errors.AnsibleError("failed to transfer file to %s:\n%s\n%s" % (out_path, stdout, stderr))
1106248
def scp(cls, vm_id, login, identity, local_file, remote_file):
        """"""
        cmd = ['scp']
        if identity:
            cmd.extend(('-i', identity,))

        version, ip_addr = cls.vm_ip(vm_id)
        if version == 6:
            ip_addr = '[%s]' % ip_addr

        cmd.extend((local_file, '%s@%s:%s' %
                    (login, ip_addr, remote_file),))
        cls.echo('Running %s' % ' '.join(cmd))
        for _ in range(5):
            ret = cls.execute(cmd, False)
            if ret:
                break
            time.sleep(.5)
        return ret
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)
146394
def asa_scp_handler(ssh_conn, cmd="ssh scopy enable", mode="enable"):
    """"""
    if mode == "disable":
        cmd = "no " + cmd
    return ssh_conn.send_config_set([cmd])
1129242
def put_str(content, path, share='C$', conn=None, host=None, username=None, password=None):
    '''
    
    '''
    if HAS_SMBPROTOCOL:
        return _put_str_smbprotocol(
            content, path, share, conn=conn, host=host,
            username=username, password=password
        )
    elif HAS_IMPACKET:
        return _put_str_impacket(
            content, path, share, conn=conn, host=host, username=username, password=password
        )
    raise MissingSmb("SMB library required (impacket or smbprotocol)")
1065690
public void copyTo(String localPath, String remotePath) throws Exception {
        FileInputStream fis = null;
        String rfile = remotePath;
        String localfile = localPath;
        boolean ptimestamp = true;

        // exec 'scp -t rfile' remotely
        String command = "scp " + (ptimestamp ? "-p" : "") + " -d -t " + rfile;
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);

        // get I/O streams for remote scp
        OutputStream out = channel.getOutputStream();
        InputStream in = channel.getInputStream();

        channel.connect();

        if (checkAck(in) != 0) {
            return;
        }

        File myFile = new File(localfile);
        List<String> files = new ArrayList<String>();

        if (myFile.isDirectory()) {
            File[] listFiles = myFile.listFiles();
            for (File file : listFiles) {
                files.add(file.getAbsolutePath());
            }
        } else {
            files.add(localfile);
        }
        for (String lfile : files) {
            File _lfile = new File(lfile);

            if (ptimestamp) {
                command = "T" + (_lfile.lastModified() / 1000) + " 0";
                // The access time should be sent here,
                // but it is not accessible with JavaAPI ;-<
                command += (" " + (_lfile.lastModified() / 1000) + " 0\n");
                out.write(command.getBytes());
                out.flush();
                if (checkAck(in) != 0) {
                    break;
                }
            }

            // send "C0644 filesize filename", where filename should not include '/'
            long filesize = _lfile.length();
            command = "C0644 " + filesize + " ";
            if (lfile.lastIndexOf('/') > 0) {
                command += lfile.substring(lfile.lastIndexOf('/') + 1);
            } else {
                command += lfile;
            }
            command += "\n";
            out.write(command.getBytes());
            out.flush();
            if (checkAck(in) != 0) {
                break;
            }

            // send a content of lfile
            fis = new FileInputStream(lfile);
            byte[] buf = new byte[1024];
            while (true) {
                int len = fis.read(buf, 0, buf.length);
                if (len <= 0) {
                    break;
                }
                out.write(buf, 0, len);
            }
            fis.close();
            fis = null;
            // send '\0'
            buf[0] = 0;
            out.write(buf, 0, 1);
            out.flush();
            if (checkAck(in) != 0) {
                break;
            }
        }
        out.close();

        channel.disconnect();
    }
802571
def _send_scp(self, cabinet, frame, board, *args, **kwargs):
        
        # Find the connection which best matches the specified coordinates,
        # preferring direct connections to a board when available.
        connection = self.connections.get((cabinet, frame, board), None)
        if connection is None:
            connection = self.connections.get((cabinet, frame), None)
        assert connection is not None, \
            "No connection available to ({}, {}, {})".format(cabinet,
                                                             frame,
                                                             board)

        # Determine the size of packet we expect in return, this is usually the
        # size that we are informed we should expect by SCAMP/SARK or else is
        # the default.
        if self._scp_data_length is None:
            length = consts.SCP_SVER_RECEIVE_LENGTH_MAX
        else:
            length = self._scp_data_length

        return connection.send_scp(length, 0, 0, board, *args, **kwargs)
138221
def remote_delete(self, remote_path, r_st):
        """"""
        # If it's a directory, then delete content and directory
        if S_ISDIR(r_st.st_mode):
            for item in self.sftp.listdir_attr(remote_path):
                full_path = path_join(remote_path, item.filename)
                self.remote_delete(full_path, item)
            self.sftp.rmdir(remote_path)

        # Or simply delete files
        else:
            try:
                self.sftp.remove(remote_path)
            except FileNotFoundError as e:
                self.logger.error(
                    "error while removing {}. trace: {}".format(remote_path, e)
                )
201872
def _scp(p, main=False):
    """"""
    global _current_subproject
    global _current_project
    if p is None:
        mp = project() if main or _current_project is None else \
            _current_project
        _current_subproject = Project(main=mp)
    elif not main:
        _current_subproject = p
    else:
        _current_project = p
640435
def get_remote_file(self, remote_path, local_path):
        
        sftp_client = self.transport.open_sftp_client()
        LOG.debug('Get the remote file. '
                  'Source=%(src)s. Target=%(target)s.' %
                  {'src': remote_path, 'target': local_path})
        try:
            sftp_client.get(remote_path, local_path)
        except Exception as ex:
            LOG.error('Failed to secure copy. Reason: %s.' %
                      six.text_type(ex))
            raise SFtpExecutionError(err=ex)