Пример #1
0
        }             // Process Record.

        void UploadDirectory(SftpClient client, string localPath, string remotePath)
        {
            IEnumerable <FileSystemInfo> infos = new DirectoryInfo(localPath).EnumerateFileSystemInfos();

            foreach (FileSystemInfo info in infos)
            {
                if (info.Attributes.HasFlag(FileAttributes.Directory))
                {
                    string subPath = remotePath + "/" + info.Name;
                    WriteVerbose("Uploading to " + subPath);
                    if (!client.Exists(subPath))
                    {
                        client.CreateDirectory(subPath);
                    }
                    UploadDirectory(client, info.FullName, remotePath + "/" + info.Name);
                }
                else
                {
                    using (Stream fileStream = new FileStream(info.FullName, FileMode.Open))
                    {
                        var fil = new FileInfo(info.FullName);
                        WriteVerbose("Uploading file: " + remotePath + "/" + info.Name);
                        var progressHelper = new OperationProgressHelper(this, "Upload", fil.Name, fil.Length, 1);
                        client.UploadFile(fileStream, remotePath + "/" + info.Name, progressHelper.Callback);
                        progressHelper.Complete();
                    }
                }
            }
        } // upload directory.
Пример #2
0
        private void DownloadFile(SftpClient client, SftpFile file, string localDirectory)
        {
            WriteVerbose($"Downloading {file.FullName}");
            var localFullPath = System.IO.Path.Combine(localDirectory, file.Name);
            // Setup Action object for showing download progress.
            var progressHelper = new OperationProgressHelper(this, "Download", file.Name, file.Length, 1);

            using (Stream fileStream = File.Create(localFullPath))
            {
                client.DownloadFile(file.FullName, fileStream, progressHelper.Callback);
                progressHelper.Complete();
            }
        }
Пример #3
0
        protected override void ProcessRecord()
        {
            foreach (var sftpSession in ToProcess)
            {
                // check if the file specified actually exists.
                // Resolve the path even if a relative one is given.
                foreach (var localitem in _localItem)
                {
                    ProviderInfo provider;
                    var          pathinfo      = GetResolvedProviderPathFromPSPath(localitem, out provider);
                    var          localfullPath = pathinfo[0];
                    var          filePresent   = File.Exists(@localfullPath);
                    var          dirPresent    = Directory.Exists(@localfullPath);

                    if (filePresent)
                    {
                        var fil            = new FileInfo(@localfullPath);
                        var remoteFullpath = _remotepath.TrimEnd(new[] { '/' }) + "/" + fil.Name;
                        WriteVerbose("Uploading " + localfullPath + " to " + _remotepath);

                        // Setup Action object for showing download progress.
                        var progressHelper = new OperationProgressHelper(this, "Upload", fil.Name, fil.Length, 1);

                        // Check that the path we are uploading to actually exists on the target.
                        if (sftpSession.Session.Exists(_remotepath))
                        {
                            // Ensure the remote path is a directory.
                            var attribs = sftpSession.Session.GetAttributes(_remotepath);
                            if (!attribs.IsDirectory)
                            {
                                throw new SftpPathNotFoundException("Specified path is not a directory");
                            }
                            // Check if the file already exists on the target system.
                            var present = sftpSession.Session.Exists(remoteFullpath);
                            if (!present || _overwrite)
                            {
                                using (var localstream = File.OpenRead(localfullPath))
                                {
                                    try
                                    {
                                        sftpSession.Session.UploadFile(localstream, remoteFullpath, progressHelper.Callback);
                                        progressHelper.Complete();
                                    }
                                    catch (Exception ex)
                                    {
                                        WriteError(new ErrorRecord(
                                                       ex,
                                                       "Error while Uploading",
                                                       ErrorCategory.InvalidOperation,
                                                       sftpSession));
                                    }
                                    finally
                                    {
                                        localstream.Close();
                                    }
                                }
                            }
                            else
                            {
                                var ex = new SftpPermissionDeniedException("File already exists on remote host.");
                                WriteError(new ErrorRecord(
                                               ex,
                                               "File already exists on remote host",
                                               ErrorCategory.InvalidOperation,
                                               sftpSession));
                            }
                        }
                        else
                        {
                            var ex = new SftpPathNotFoundException(_remotepath + " does not exist.");
                            WriteError(new ErrorRecord(
                                           ex,
                                           _remotepath + " does not exist.",
                                           ErrorCategory.InvalidOperation,
                                           sftpSession));
                        }
                    }
                    else if (dirPresent)
                    {
                        var dirName        = new DirectoryInfo(@localfullPath).Name;
                        var remoteFullpath = _remotepath.TrimEnd(new[] { '/' }) + "/" + dirName;

                        WriteVerbose("Uploading " + localfullPath + " to " + _remotepath);
                        if (!sftpSession.Session.Exists(remoteFullpath))
                        {
                            sftpSession.Session.CreateDirectory(remoteFullpath);
                        }
                        else
                        {
                            if (!_overwrite)
                            {
                                var ex = new SftpPermissionDeniedException("Folder already exists on remote host.");
                                ThrowTerminatingError(new ErrorRecord(
                                                          ex,
                                                          "Folder already exists on remote host",
                                                          ErrorCategory.InvalidOperation,
                                                          sftpSession));
                            }
                        }

                        try
                        {
                            UploadDirectory(sftpSession.Session, localfullPath, remoteFullpath);
                        }
                        catch (Exception ex)
                        {
                            WriteError(new ErrorRecord(
                                           ex,
                                           "Error while Uploading",
                                           ErrorCategory.InvalidOperation,
                                           sftpSession));
                        }
                    }
                    else
                    {
                        var ex = new FileNotFoundException("Item to upload " + localfullPath + " was not found.");

                        ThrowTerminatingError(new ErrorRecord(
                                                  ex,
                                                  "Item to upload " + localfullPath + " was not found.",
                                                  ErrorCategory.InvalidOperation,
                                                  localfullPath));
                    } // check if item exists.
                }     // foreach local item
            }         // sftp session.
        }             // Process Record.
Пример #4
0
        protected override void ProcessRecord()
        {
            foreach (var computer in ComputerName)
            {
                var client = CreateConnection(computer) as ScpClient;
                try
                {
                    if (client != default && client.IsConnected)
                    {
                        switch (PathTransformation.ToLower())
                        {
                        case "shellquote":
                            client.RemotePathTransformation = RemotePathTransformation.ShellQuote;
                            break;

                        case "none":
                            client.RemotePathTransformation = RemotePathTransformation.None;
                            break;

                        case "doublequote":
                            client.RemotePathTransformation = RemotePathTransformation.DoubleQuote;
                            break;
                        }

                        WriteVerbose("Connection successful");

                        ProviderInfo provider;
                        var          pathinfo       = GetResolvedProviderPathFromPSPath(_localpath, out provider);
                        var          localfullPath  = pathinfo[0];
                        var          fil            = new FileInfo(@localfullPath);
                        var          dirinfo        = new DirectoryInfo(@localfullPath);
                        var          remoteFullpath = "";
                        var          localname      = "";

                        if (fil.Exists || dirinfo.Exists)
                        {
                            WriteVerbose("Uploading: " + localfullPath);

                            if (fil.Exists)
                            {
                                localname = fil.Name;
                            }
                            else
                            {
                                localname = dirinfo.Name;
                            }
                            // Set the proper name for the file on the target.
                            if (String.IsNullOrEmpty(_newname))
                            {
                                remoteFullpath = Destination.TrimEnd(new[] { '/' }) + "/" + localname;
                            }
                            else
                            {
                                remoteFullpath = Destination.TrimEnd(new[] { '/' }) + "/" + _newname;
                            }

                            WriteVerbose("Destination: " + remoteFullpath);
                            var    progressHelper = new OperationProgressHelper(this, "Upload", "", 0, 1);
                            string curName        = "";
                            if (progressHelper.IsProgressVisible)
                            {
                                client.Uploading += delegate(object sender, ScpUploadEventArgs e)
                                {
                                    if (e.Filename != curName)
                                    {
                                        progressHelper.Complete();
                                        curName        = e.Filename;
                                        progressHelper = new OperationProgressHelper(this, "Upload", curName, e.Size, 1);
                                    }
                                    progressHelper.Callback?.Invoke((ulong)e.Uploaded);
                                };
                            }

                            if (fil.Exists)
                            {
                                client.Upload(fil, remoteFullpath);
                            }
                            else
                            {
                                client.Upload(dirinfo, remoteFullpath);
                            }
                            progressHelper.Complete();

                            client.Disconnect();
                        }
                        else
                        {
                            var ex = new FileNotFoundException("Item to upload " + localfullPath + " was not found.");

                            ThrowTerminatingError(new ErrorRecord(
                                                      ex,
                                                      "Item to upload " + localfullPath + " was not found.",
                                                      ErrorCategory.InvalidOperation,
                                                      localfullPath));
                        } // check if file exists.

                        client.Disconnect();
                    }
                }
                catch (Exception e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationStopped, client);
                    WriteError(erec);
                }
            }
        } // End process record
Пример #5
0
        protected override void ProcessRecord()
        {
            // check if the path specified actually exists.
            // Resolve the path even if a relative one is given for PowerShell.
            ProviderInfo provider;
            var          pathinfo      = GetResolvedProviderPathFromPSPath(_localpath, out provider);
            var          localfullPath = pathinfo[0];

            if (Directory.Exists(@localfullPath))
            {
                foreach (var sftpSession in ToProcess)
                {
                    foreach (string remotepath in _remotepath)
                    {
                        // Check that the path we are downloading from actually exists on the target.
                        if (sftpSession.Session.Exists(remotepath))
                        {
                            // Check if the remote path is a file or a directory to perform proper action.
                            var attribs = sftpSession.Session.GetAttributes(remotepath);

                            if (attribs.IsDirectory)
                            {
                                string dirName      = new DirectoryInfo(remotepath).Name;
                                var    fileFullPath = $"{@localfullPath}{System.IO.Path.DirectorySeparatorChar}{dirName}";

                                var present = Directory.Exists(fileFullPath);
                                if (!present || _overwrite)
                                {
                                    Directory.CreateDirectory(fileFullPath);
                                    DownloadDirectory(sftpSession.Session, remotepath, fileFullPath, _skipsymlink);
                                }
                                else
                                {
                                    var ex = new SftpPermissionDeniedException($"Item {remotepath} already present on local host.");
                                    WriteError(new ErrorRecord(
                                                   ex,
                                                   $"Item {remotepath} already present on local host.",
                                                   ErrorCategory.InvalidOperation,
                                                   sftpSession));
                                }
                            }
                            else if (attribs.IsRegularFile)
                            {
                                var fileName = new FileInfo(remotepath).Name;

                                var fileFullPath = $"{@localfullPath}{System.IO.Path.DirectorySeparatorChar}{fileName}";

                                var present = File.Exists(fileFullPath);

                                if (!present || _overwrite)
                                {
                                    using (var localstream = File.Create(fileFullPath))
                                    {
                                        try
                                        {
                                            WriteVerbose($"Downloading: {remotepath}");
                                            var progressHelper = new OperationProgressHelper(this, "Download", remotepath, attribs.Size, 1);
                                            sftpSession.Session.DownloadFile(remotepath, localstream, progressHelper.Callback);
                                            progressHelper.Complete();
                                        }
                                        catch
                                        {
                                            var ex = new SftpPermissionDeniedException($"Unable to download {remotepath} from host.");
                                            WriteError(new ErrorRecord(
                                                           ex,
                                                           $"Unable to download {remotepath} from host.",
                                                           ErrorCategory.InvalidOperation,
                                                           sftpSession));
                                        }
                                        finally
                                        {
                                            localstream.Close();
                                        }
                                    }
                                }
                                else
                                {
                                    var ex = new SftpPermissionDeniedException($"Item {remotepath} already present on local host.");
                                    WriteError(new ErrorRecord(
                                                   ex,
                                                   $"Item {remotepath} already present on local host.",
                                                   ErrorCategory.InvalidOperation,
                                                   sftpSession));
                                }
                            }
                            else
                            {
                            }
                        }
                        else
                        {
                            var ex = new SftpPathNotFoundException(remotepath + " does not exist.");

                            WriteError(new ErrorRecord(
                                           ex,
                                           remotepath + " does not exist.",
                                           ErrorCategory.InvalidOperation,
                                           sftpSession));
                        }
                    }
                }
            }
            else
            {
                var ex = new FileNotFoundException("Local path" + localfullPath + " was not found.");

                ThrowTerminatingError(new ErrorRecord(
                                          ex,
                                          "Local path" + localfullPath + " was not found.",
                                          ErrorCategory.InvalidOperation,
                                          localfullPath));
            }
        }
Пример #6
0
        protected override void ProcessRecord()
        {
            foreach (var computer in ComputerName)
            {
                var client = CreateConnection(computer) as ScpClient;
                try
                {
                    if (client != default && client.IsConnected)
                    {
                        switch (PathTransformation.ToLower())
                        {
                        case "shellquote":
                            client.RemotePathTransformation = RemotePathTransformation.ShellQuote;
                            break;

                        case "none":
                            client.RemotePathTransformation = RemotePathTransformation.None;
                            break;

                        case "doublequote":
                            client.RemotePathTransformation = RemotePathTransformation.DoubleQuote;
                            break;
                        }
                        WriteVerbose("Connection successful");

                        WriteVerbose("Downloading " + _remotepath);
                        // Get file/directory name for use when downloading the file.
                        var localname       = "";
                        var destinationpath = "";
                        var localfullPath   = this.SessionState.Path.GetUnresolvedProviderPathFromPSPath(_localpath);

                        if (String.IsNullOrEmpty(_newname))
                        {
                            localname = new DirectoryInfo(@_remotepath).Name;
                        }
                        else
                        {
                            localname = _newname;
                        }
                        destinationpath = (localfullPath.TrimEnd('/', '\\')) + System.IO.Path.DirectorySeparatorChar + localname;

                        string curName        = "";
                        var    progressHelper = new OperationProgressHelper(this, "Download", curName, 0, 1);
                        if (progressHelper.IsProgressVisible)
                        {
                            client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                            {
                                if (e.Filename != curName)
                                {
                                    progressHelper.Complete();
                                    curName        = e.Filename;
                                    progressHelper = new OperationProgressHelper(this, "Download", curName, e.Size, 1);
                                }
                                progressHelper.Callback?.Invoke((ulong)e.Downloaded);
                            };
                        }
                        if (String.Equals(_pathtype, "File", StringComparison.OrdinalIgnoreCase))
                        {
                            WriteVerbose("File name " + localname);
                            WriteVerbose("Item type selected: File");

                            WriteVerbose("Saving as " + destinationpath);

                            var fil = new FileInfo(@destinationpath);

                            if (fil.Exists && !this.MyInvocation.BoundParameters.ContainsKey("Force"))
                            {
                                var         e    = new IOException("File " + localname + " already exists.");
                                ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client);
                                WriteError(erec);
                            }
                            else
                            {
                                if (fil.Exists)
                                {
                                    WriteWarning("Overwritting " + destinationpath);
                                    File.Delete(destinationpath);
                                }
                                // Download the file
                                client.Download(_remotepath, fil);
                                progressHelper.Complete();
                            }
                        }
                        else
                        {
                            WriteVerbose("Item type selected: Directory");
                            Directory.CreateDirectory(destinationpath);

                            WriteVerbose("Destination: " + destinationpath);

                            var dirinfo = new DirectoryInfo(@destinationpath);
                            client.Download(_remotepath, dirinfo);
                            progressHelper.Complete();
                        }
                        client.Disconnect();
                    }
                }
                catch (Exception e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationStopped, client);
                    WriteError(erec);
                }
            }
        } // End process record