protected void Arrange()
        {
            _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict);
            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _sftpSessionMock = new Mock<ISftpSession>(MockBehavior.Strict);

            _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));
            _operationTimeout = TimeSpan.FromSeconds(new Random().Next(1, 10));
            _sftpClient = new SftpClient(_connectionInfo, false, _serviceFactoryMock.Object);
            _sftpClient.OperationTimeout = _operationTimeout;

            var sequence = new MockSequence();
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateSession(_connectionInfo))
                .Returns(_sessionMock.Object);
            _sessionMock.InSequence(sequence).Setup(p => p.Connect());
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding))
                .Returns(_sftpSessionMock.Object);
            _sftpSessionMock.InSequence(sequence).Setup(p => p.Connect());
            _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting());
            _sftpSessionMock.InSequence(sequence).Setup(p => p.Disconnect());
            _sftpSessionMock.InSequence(sequence).Setup(p => p.Dispose());
            _sessionMock.InSequence(sequence).Setup(p => p.Disconnect());
            _sessionMock.InSequence(sequence).Setup(p => p.Dispose());

            _sftpClient.Connect();
            _sftpClient.Dispose();
        }
 //Dispose implementation & Destructor
 public void Dispose()
 {
     _sftpClient?.Disconnect();
     _sftpClient?.Dispose();
     _sshClient?.Disconnect();
     _sshClient?.Dispose();
 }
示例#3
0
        private SftpClient CreateClient()
        {
            SftpClient client = null;

            if (!string.IsNullOrEmpty(PrivateKeyFile))
            {
                using var pkf = new PrivateKeyFile(PrivateKeyFile, Password);
                try
                {
                    client = new SftpClient(Host, Port, Username, pkf);
                    client.Connect();
                }
                catch
                {
                    client?.Dispose();
                    throw;
                }
            }
            else
            {
                try
                {
                    client = new SftpClient(Host, Port, Username, Password);
                    client.Connect();
                }
                catch
                {
                    client?.Dispose();
                    throw;
                }
            }

            return(client);
        }
示例#4
0
#pragma warning restore AsyncFixer01 // Unnecessary async/await usage

        protected void Dispose(bool disposing)
        {
            if (disposing)
            {
                _client?.Disconnect();
                _client?.Dispose();
            }
        }
        protected virtual void Dispose(Boolean disposing)
        {
            if (disposing)
            {
                // Free managed resources
                _sftpClient?.Dispose();
            }

            // Free unmanaged resources
        }
示例#6
0
        public void Dispose()
        {
            _shellStream?.Close();
            _shellStream = null;

            _client?.Dispose();
            _client = null;

            _sftp?.Dispose();
            _sftp = null;

            _fsw?.Dispose();
            _fsw = null;
        }
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            if (disposing)
            {
                _client?.Dispose();
            }

            _disposed = true;
        }
示例#8
0
        private bool Reset(bool connect = true)
        {
            _ssh?.Dispose();  _ssh  = null;  SSHError = null;
            _sftp?.Dispose(); _sftp = null; SFTPError = null;

            if (connect)
            {
                bool cssh = false, csftp = false;
                try { cssh = SSH.IsConnected; } catch {}
                try { csftp = SFTP.IsConnected; } catch {}

                return(cssh && csftp);
            }
            else
            {
                return(false);
            }
        }
示例#9
0
        bool Execute()
        {
            try
            {
                if (Direction == SshDirection.ToSshServer)
                {
                    ExpandDestination = false;
                }
                else
                {
                    ExpandSource = false;
                }

                List <string> sources = new List <string>();
                if (ExpandSource)
                {
                    sources = STEM.Sys.IO.Path.ExpandRangedPath(SourcePath);
                }
                else
                {
                    sources.Add(SourcePath);
                }

                List <string> destinations = new List <string>();
                if (ExpandDestination)
                {
                    destinations = STEM.Sys.IO.Path.ExpandRangedPath(DestinationPath);
                }
                else
                {
                    destinations.Add(DestinationPath);
                }

                List <string> sourceFiles = new List <string>();

                int filesActioned = 0;

                foreach (string src in sources)
                {
                    List <SftpFile> items = new List <SftpFile>();

                    if (Direction == SshDirection.ToSshServer)
                    {
                        PostMortemMetaData["LastOperation"] = "STEM_GetFiles:SourceFile";

                        sourceFiles = STEM.Sys.IO.Directory.STEM_GetFiles(src, FileFilter, DirectoryFilter, (RecurseSource ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly), false);
                    }
                    else
                    {
                        PostMortemMetaData["LastOperation"] = "ListDirectory:SourceFile";

                        items = Authentication.ListDirectory(_Address, Int32.Parse(Port), src, SSHListType.File, RecurseSource, DirectoryFilter, FileFilter);

                        sourceFiles = items.Select(i => i.FullName).ToList();
                    }

                    foreach (string s in sourceFiles)
                    {
                        try
                        {
                            bool success = false;

                            Exception lastEX = null;

                            foreach (string d in destinations)
                            {
                                try
                                {
                                    string dFile = "";

                                    try
                                    {
                                        if (PopulatePostMortemMeta)
                                        {
                                            PostMortemMetaData["LastOperation"] = "GetFileInfo:SourceFile";

                                            if (Direction == SshDirection.ToSshServer)
                                            {
                                                PostMortemMetaData["FileSize"]      = new FileInfo(s).Length.ToString();
                                                PostMortemMetaData["SourceIP"]      = STEM.Sys.IO.Path.IPFromPath(s);
                                                PostMortemMetaData["DestinationIP"] = _Address;
                                            }
                                            else
                                            {
                                                PostMortemMetaData["FileSize"]      = Authentication.GetFileInfo(_Address, Int32.Parse(Port), s).Size.ToString();
                                                PostMortemMetaData["SourceIP"]      = _Address;
                                                PostMortemMetaData["DestinationIP"] = STEM.Sys.IO.Path.IPFromPath(d);
                                            }
                                        }
                                    }
                                    catch { }

                                    string dPath = STEM.Sys.IO.Path.AdjustPath(d);
                                    if (RecurseSource && RecreateTree)
                                    {
                                        dPath = System.IO.Path.Combine(dPath, STEM.Sys.IO.Path.GetDirectoryName(s).Replace(STEM.Sys.IO.Path.AdjustPath(src), "").Trim(System.IO.Path.DirectorySeparatorChar));
                                    }

                                    dPath = System.IO.Path.Combine(dPath, DestinationFilename);

                                    if (dPath.Contains("*.*"))
                                    {
                                        dPath = dPath.Replace("*.*", STEM.Sys.IO.Path.GetFileName(s));
                                    }

                                    if (dPath.Contains("*"))
                                    {
                                        dPath = dPath.Replace("*", STEM.Sys.IO.Path.GetFileNameWithoutExtension(s));
                                    }

                                    if (Direction == SshDirection.ToSshServer)
                                    {
                                        string directory = STEM.Sys.IO.Path.GetDirectoryName(dPath);

                                        PostMortemMetaData["LastOperation"] = "DirectoryExists:DestinationDirectory";

                                        if (!Authentication.DirectoryExists(_Address, Int32.Parse(Port), directory))
                                        {
                                            Authentication.CreateDirectory(_Address, Int32.Parse(Port), directory);
                                        }

                                        PostMortemMetaData["LastOperation"] = "FileExists:DestinationFile";

                                        if (Authentication.FileExists(_Address, Int32.Parse(Port), dPath))
                                        {
                                            switch (ExistsAction)
                                            {
                                            case Sys.IO.FileExistsAction.Overwrite:
                                                Authentication.DeleteFile(_Address, Int32.Parse(Port), dPath);
                                                dFile = dPath;
                                                break;

                                            case Sys.IO.FileExistsAction.OverwriteIfNewer:

                                                if (Authentication.GetFileInfo(_Address, Int32.Parse(Port), dPath).LastWriteTimeUtc >= File.GetLastWriteTimeUtc(s))
                                                {
                                                    continue;
                                                }

                                                Authentication.DeleteFile(_Address, Int32.Parse(Port), dPath);
                                                dFile = dPath;
                                                break;

                                            case Sys.IO.FileExistsAction.Skip:
                                                continue;

                                            case Sys.IO.FileExistsAction.Throw:
                                                throw new IOException("Destination file exists. (" + dPath + ")");

                                            case Sys.IO.FileExistsAction.MakeUnique:
                                                dFile = Authentication.UniqueFilename(_Address, Int32.Parse(Port), dPath);
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            dFile = dPath;
                                        }

                                        DateTime mt = File.GetLastWriteTimeUtc(s);

                                        PostMortemMetaData["LastOperation"] = "OpenSftpClient";

                                        SftpClient client = null;

                                        try
                                        {
                                            client = Authentication.OpenSftpClient(_Address, Int32.Parse(Port));

                                            try
                                            {
                                                PostMortemMetaData["LastOperation"] = "UploadFile";

                                                using (System.IO.Stream sStream = System.IO.File.Open(STEM.Sys.IO.Path.AdjustPath(s), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None))
                                                {
                                                    client.UploadFile(sStream, Authentication.AdjustPath(_Address, dFile));
                                                    //client.SetLastWriteTimeUtc(Authentication.AdjustPath(_Address, dFile), mt);
                                                }
                                            }
                                            finally
                                            {
                                                PostMortemMetaData["LastOperation"] = "RecycleClient";
                                                Authentication.RecycleClient(client);
                                                client = null;
                                            }
                                        }
                                        catch
                                        {
                                            try
                                            {
                                                client.Disconnect();
                                            }
                                            catch { }
                                            try
                                            {
                                                client.Dispose();
                                            }
                                            catch { }

                                            throw;
                                        }
                                    }
                                    else
                                    {
                                        PostMortemMetaData["LastOperation"] = "File.Exists:DestinationFile";
                                        if (File.Exists(dPath))
                                        {
                                            switch (ExistsAction)
                                            {
                                            case Sys.IO.FileExistsAction.Overwrite:
                                                File.Delete(dPath);
                                                dFile = dPath;
                                                break;

                                            case Sys.IO.FileExistsAction.OverwriteIfNewer:

                                                if (File.GetLastWriteTimeUtc(dPath) >= Authentication.GetFileInfo(_Address, Int32.Parse(Port), s).LastWriteTimeUtc)
                                                {
                                                    continue;
                                                }

                                                File.Delete(dPath);
                                                dFile = dPath;
                                                break;

                                            case Sys.IO.FileExistsAction.Skip:
                                                continue;

                                            case Sys.IO.FileExistsAction.Throw:
                                                throw new IOException("Destination file exists. (" + dPath + ")");

                                            case Sys.IO.FileExistsAction.MakeUnique:
                                                dFile = STEM.Sys.IO.File.UniqueFilename(dPath);
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            dFile = dPath;
                                        }

                                        PostMortemMetaData["LastOperation"] = "Directory.Exists:DestinationDirectory";

                                        if (!Directory.Exists(STEM.Sys.IO.Path.GetDirectoryName(dFile)))
                                        {
                                            Directory.CreateDirectory(STEM.Sys.IO.Path.GetDirectoryName(dFile));
                                        }

                                        SftpClient client = null;

                                        try
                                        {
                                            client = Authentication.OpenSftpClient(_Address, Int32.Parse(Port));

                                            string tmp = "";
                                            try
                                            {
                                                PostMortemMetaData["LastOperation"] = "DownloadFile";

                                                tmp = Path.Combine(STEM.Sys.IO.Path.GetDirectoryName(dFile), "TEMP");

                                                if (!Directory.Exists(tmp))
                                                {
                                                    Directory.CreateDirectory(tmp);
                                                }

                                                tmp = Path.Combine(tmp, STEM.Sys.IO.Path.GetFileName(dFile));

                                                using (System.IO.Stream dStream = System.IO.File.Open(tmp, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None))
                                                {
                                                    client.DownloadFile(Authentication.AdjustPath(_Address, s), dStream);
                                                }

                                                File.Move(tmp, STEM.Sys.IO.Path.AdjustPath(dFile));
                                            }
                                            finally
                                            {
                                                try
                                                {
                                                    if (File.Exists(tmp))
                                                    {
                                                        File.Delete(tmp);
                                                    }
                                                }
                                                catch { }

                                                PostMortemMetaData["LastOperation"] = "RecycleClient";
                                                Authentication.RecycleClient(client);
                                                client = null;
                                            }
                                        }
                                        catch
                                        {
                                            try
                                            {
                                                client.Disconnect();
                                            }
                                            catch { }
                                            try
                                            {
                                                client.Dispose();
                                            }
                                            catch { }

                                            throw;
                                        }

                                        PostMortemMetaData["LastOperation"] = "SetLastWriteTimeUtc:DestinationFile";
                                        try
                                        {
                                            File.SetLastWriteTimeUtc(dFile, Authentication.GetFileInfo(_Address, Int32.Parse(Port), s).LastWriteTimeUtc);
                                        }
                                        catch { }
                                    }

                                    if (!String.IsNullOrEmpty(dFile))
                                    {
                                        filesActioned++;

                                        _FilesActioned[s] = dFile;

                                        if (Action == ActionType.Move)
                                        {
                                            AppendToMessage(s + " moved to " + dFile);
                                        }
                                        else
                                        {
                                            AppendToMessage(s + " copied to " + dFile);
                                        }
                                    }

                                    success = true;

                                    if (DestinationActionRule == DestinationRule.FirstSuccess)
                                    {
                                        break;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    lastEX = ex;

                                    if (DestinationActionRule == DestinationRule.AllOrNone)
                                    {
                                        throw ex;
                                    }
                                }
                            }

                            if (!success)
                            {
                                throw new Exception("No successful actions taken for " + s, lastEX); // + "\r\n" + ((lastEX == null) ? "No additional information." : lastEX.ToString()));
                            }
                            if (Action == ActionType.Move)
                            {
                                if (Direction == SshDirection.ToSshServer)
                                {
                                    PostMortemMetaData["LastOperation"] = "File.Delete:SourceFile";
                                    File.Delete(s);
                                }
                                else
                                {
                                    PostMortemMetaData["LastOperation"] = "DeleteFile:SourceFile";
                                    Authentication.DeleteFile(_Address, Int32.Parse(Port), s);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            AppendToMessage(ex.Message);
                            Exceptions.Add(ex);
                        }
                    }
                }

                if (PopulatePostMortemMeta)
                {
                    PostMortemMetaData["FilesActioned"] = filesActioned.ToString();
                }
            }
            catch (Exception ex)
            {
                AppendToMessage(ex.Message);
                Exceptions.Add(ex);
            }

            if (_FilesActioned.Count == 0)
            {
                switch (ZeroFilesAction)
                {
                case FailureAction.SkipRemaining:
                    SkipRemaining();
                    return(true);

                case FailureAction.SkipNext:
                    SkipNext();
                    return(true);

                case FailureAction.SkipToLabel:
                    SkipForwardToFlowControlLabel(FailureActionLabel);
                    return(true);

                case FailureAction.Rollback:
                    RollbackAllPreceedingAndSkipRemaining();
                    break;

                case FailureAction.Continue:
                    return(true);
                }

                Message = "0 Files Actioned\r\n" + Message;
            }

            return(Exceptions.Count == 0);
        }
示例#10
0
        protected override void _Rollback()
        {
            if (ExecutionMode == ExecuteOn.ForwardExecution)
            {
                foreach (string d in _FilesActioned.Keys)
                {
                    try
                    {
                        string s = _FilesActioned[d];

                        if (Action == ActionType.Move)
                        {
                            SftpClient client = null;

                            try
                            {
                                client = Authentication.OpenSftpClient(_Address, Int32.Parse(Port));

                                try
                                {
                                    if (Direction == SshDirection.ToSshServer)
                                    {
                                        string tmp = "";

                                        try
                                        {
                                            tmp = Path.Combine(STEM.Sys.IO.Path.GetDirectoryName(d), "TEMP");

                                            if (!Directory.Exists(tmp))
                                            {
                                                Directory.CreateDirectory(tmp);
                                            }

                                            tmp = Path.Combine(tmp, STEM.Sys.IO.Path.GetFileName(d));

                                            using (System.IO.Stream dStream = System.IO.File.Open(tmp, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None))
                                            {
                                                client.DownloadFile(Authentication.AdjustPath(_Address, d), dStream);
                                            }

                                            File.Move(tmp, STEM.Sys.IO.Path.AdjustPath(d));
                                        }
                                        finally
                                        {
                                            try
                                            {
                                                if (File.Exists(tmp))
                                                {
                                                    File.Delete(tmp);
                                                }
                                            }
                                            catch { }
                                        }
                                    }
                                    else
                                    {
                                        using (System.IO.Stream sStream = System.IO.File.Open(STEM.Sys.IO.Path.AdjustPath(s), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None))
                                        {
                                            client.UploadFile(sStream, Authentication.AdjustPath(_Address, d));
                                        }
                                    }
                                }
                                finally
                                {
                                    Authentication.RecycleClient(client);
                                    client = null;
                                }
                            }
                            catch
                            {
                                try
                                {
                                    client.Disconnect();
                                }
                                catch { }
                                try
                                {
                                    client.Dispose();
                                }
                                catch { }

                                throw;
                            }
                        }

                        if (Direction == SshDirection.ToSshServer)
                        {
                            Authentication.DeleteFile(_Address, Int32.Parse(Port), s);
                        }
                        else
                        {
                            STEM.Sys.IO.File.STEM_Delete(s, false, Retry, RetryDelaySeconds);
                        }
                    }
                    catch { }
                }
            }
            else
            {
                int r = Retry;
                while (r-- >= 0 && !Stop)
                {
                    _Address = Authentication.NextAddress(ServerAddress);

                    if (_Address == null)
                    {
                        Exception ex = new Exception("No valid address. (" + ServerAddress + ")");
                        Exceptions.Add(ex);
                        AppendToMessage(ex.Message);
                        return;
                    }

                    Exceptions.Clear();
                    Message = "";
                    bool success = Execute();
                    if (success)
                    {
                        return;
                    }

                    System.Threading.Thread.Sleep(RetryDelaySeconds * 1000);
                }
            }
        }
示例#11
0
 public override void Dispose()
 {
     client.Dispose();
 }
 public void Dispose()
 {
     _connection.Dispose();
 }
示例#13
0
        public void Dispose()
        {
            if (_client == null)
            {
                return;
            }

            Task.Run(() =>
            {
                //                _log.Debug("Disposing _client");

                var timer = new System.Timers.Timer
                {
                    Interval  = 2000,
                    AutoReset = false
                };

                timer.Elapsed += (s, e) =>
                {
                    try
                    {
                        var sessionField = _client.GetType().GetProperty("Session", BindingFlags.NonPublic | BindingFlags.Instance);

                        if (sessionField != null)
                        {
                            var session = sessionField.GetValue(_client);

                            if (session != null)
                            {
                                var socketField = session.GetType().GetField("_socket", BindingFlags.NonPublic | BindingFlags.Instance);

                                if (socketField != null)
                                {
                                    var socket = (Socket)socketField.GetValue(session);

                                    if (socket != null)
                                    {
//                                        _log.Debug($"Socket state: Connected = {socket.Connected}, Blocking = {socket.Blocking}, Available = {socket.Available}, LocalEndPoint = {socket.LocalEndPoint}, RemoteEndPoint = {socket.RemoteEndPoint}");

//                                        _log.Debug("Set _socket to null");

                                        try
                                        {
                                            socket.Dispose();
                                        }
                                        catch (Exception ex)
                                        {
//                                            _log.Debug("Exception disposing _socket", ex);
                                        }

                                        socketField.SetValue(session, null);
                                    }
                                    else
                                    {
//                                        _log.Debug("_socket was null");
                                    }
                                }

                                var messageListenerCompletedField = session.GetType().GetField("_messageListenerCompleted", BindingFlags.NonPublic | BindingFlags.Instance);

                                var messageListenerCompleted = (EventWaitHandle)messageListenerCompletedField.GetValue(session);

                                if (messageListenerCompleted != null)
                                {
                                    var waitHandleSet = messageListenerCompleted.WaitOne(0);

//                                    _log.Debug($"_messageListenerCompleted was set = {waitHandleSet}");

                                    if (!waitHandleSet)
                                    {
//                                        _log.Debug($"Calling Set()");
                                        messageListenerCompleted.Set();
                                    }
                                }
                                else
                                {
//                                    _log.Debug("_messageListenerCompleted was null");
                                }
                            }
                            else
                            {
//                                _log.Debug("Session was null");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
//                        _log.Debug($"Exception in Timer event handler", ex);
                    }
                };

                timer.Start();

                _client.Dispose();

//                _log.Info("Disposed _client");
            });
        }
示例#14
0
        protected override bool _Run()
        {
            int r = Retry;

            while (r-- >= 0 && !Stop)
            {
                try
                {
                    PostMortemMetaData["LastOperation"] = "NextAddress";
                    string address = Authentication.NextAddress(ServerAddress);

                    if (address == null)
                    {
                        Exception ex = new Exception("No valid address. (" + ServerAddress + ")");
                        Exceptions.Add(ex);
                        AppendToMessage(ex.Message);
                        return(false);
                    }

                    string sData = null;
                    byte[] bData = null;

                    string sFile = Authentication.AdjustPath(address, SourceFile);

                    PostMortemMetaData["LastOperation"] = "OpenSftpClient";
                    SftpClient client = null;

                    try
                    {
                        client = Authentication.OpenSftpClient(address, Int32.Parse(Port));

                        try
                        {
                            PostMortemMetaData["LastOperation"] = "DownloadFile";
                            using (System.IO.MemoryStream s = new System.IO.MemoryStream())
                            {
                                client.DownloadFile(sFile, s);

                                bData = s.ToArray();

                                if (FileType == DataType.String)
                                {
                                    sData = System.Text.Encoding.Unicode.GetString(bData, 0, bData.Length);
                                    bData = null;
                                }
                            }
                        }
                        finally
                        {
                            PostMortemMetaData["LastOperation"] = "RecycleClient";
                            Authentication.RecycleClient(client);
                            client = null;
                        }
                    }
                    catch
                    {
                        try
                        {
                            client.Disconnect();
                        }
                        catch { }
                        try
                        {
                            client.Dispose();
                        }
                        catch { }

                        throw;
                    }

                    switch (TargetContainer)
                    {
                    case ContainerType.InstructionSetContainer:

                        if (bData != null)
                        {
                            InstructionSet.InstructionSetContainer[ContainerDataKey] = bData;
                        }
                        else
                        {
                            InstructionSet.InstructionSetContainer[ContainerDataKey] = sData;
                        }

                        break;

                    case ContainerType.Session:

                        if (bData != null)
                        {
                            STEM.Sys.State.Containers.Session[ContainerDataKey] = bData;
                        }
                        else
                        {
                            STEM.Sys.State.Containers.Session[ContainerDataKey] = sData;
                        }

                        break;

                    case ContainerType.Cache:

                        if (bData != null)
                        {
                            STEM.Sys.State.Containers.Cache[ContainerDataKey] = bData;
                        }
                        else
                        {
                            STEM.Sys.State.Containers.Cache[ContainerDataKey] = sData;
                        }

                        break;
                    }

                    break;
                }
                catch (Exception ex)
                {
                    if (r < 0)
                    {
                        AppendToMessage(ex.Message);
                        Exceptions.Add(ex);
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(RetryDelaySeconds * 1000);
                    }
                }
            }

            return(Exceptions.Count == 0);
        }
示例#15
0
        private void download_sftp(string remote_path, string local_path)
        {
            // https://stackoverflow.com/questions/43555982/displaying-progress-of-file-upload-in-a-progressbar-with-ssh-net
            // https://stackoverflow.com/questions/44442714/displaying-progress-of-file-download-in-a-progressbar-with-ssh-net

            download_status = DOWNLOAD_STATUS.start;
            update_ui();

            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();


            SftpClient sftp = new SftpClient(Constants.SFTP_ADDR, Constants.SFTP_ID, Constants.SFTP_PWD);

            try
            {
                using (var stream = new FileStream(local_path, FileMode.Create))
                    using (sftp)
                    {
                        if (!sftp.IsConnected)
                        {
                            sftp.Connect();
                        }
                        SftpFileAttributes attributes = sftp.GetAttributes(remote_path);

                        // Set progress bar maximum on foreground thread
                        Application.Current.Dispatcher.Invoke(() => {
                            var file_size = ByteSize.FromBytes((double)attributes.Size);

                            prgbDownload.Value    = 0;
                            prgbDownload.Maximum  = (int)file_size.Bytes;
                            prgbDownloadText.Text = string.Format("{0} / {1:F1} MB", 0, file_size.MegaBytes);
                        });
                        sftp.DownloadFile(remote_path, stream, download_sftp_progress);
                        extract_zipfile(local_path);

                        download_status = DOWNLOAD_STATUS.end;
                        update_ui();
                    }
            }
            catch (Exception e)
            {
                download_status = DOWNLOAD_STATUS.ini;
                update_ui();
                MessageBox.Show(e.Message);
            }

            stopWatch.Stop();
            TimeSpan ts          = stopWatch.Elapsed;
            string   elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);

            if (download_status == DOWNLOAD_STATUS.end)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    prgbDownloadText.Text += "(" + elapsedTime + ")";
                });
            }

            sftp.Dispose();
        }
示例#16
0
 public void Dispose()
 {
     ssh.Dispose();
     sftp.Dispose();
 }
示例#17
0
 public void disConnect()
 {
     client.Disconnect();
     client.Dispose();
     client = null;
 }
        /// <summary>
        /// ftp로 데이터를 전송하기 위한 디렉토리에 신규 파일 생성시 이벤트 발생 메소드
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnCreated(object sender, FileSystemEventArgs e)
        {
            //파일명 얻어오기
            var        fullFileName = e.FullPath;
            var        fileName     = e.Name;
            SftpClient sftp         = null;

            //접속하기
            try
            {
                sftp = new SftpClient(FtpDirectoryInfo.SFTPHOST, int.Parse(FtpDirectoryInfo.STFPPORT), FtpDirectoryInfo.SFTPUSERNAME, FtpDirectoryInfo.SFTPPASSWORD);

                sftp.ConnectionInfo.Timeout = TimeSpan.FromSeconds(3);
                // SFTP 서버 연결
                sftp.Connect();

                _logDisplay.Display(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "," + FtpDirectoryInfo.SFTPHOST + " 에 접속했습니다.");
                log.Info(FtpDirectoryInfo.SFTPHOST + " connected");

                if (FtpDirectoryInfo.REMOTEDIRECTORYPATH != "" && FtpDirectoryInfo.REMOTEDIRECTORYPATH != "\\")
                {
                    sftp.ChangeDirectory(FtpDirectoryInfo.REMOTEDIRECTORYPATH);
                    _logDisplay.Display(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "," + FtpDirectoryInfo.REMOTEDIRECTORYPATH + " 디렉토리를 변경했습니다.");
                    log.Info(FtpDirectoryInfo.REMOTEDIRECTORYPATH + " directory changed");
                }

                // SFTP 업로드
                SendFile(sftp, fileName);

                var files = Directory.GetFiles(this._directoryPath);

                if (files.Length > 0)
                {
                    if (files.Length > 30)
                    {
                        for (int i = 0; i <= 30; i++)
                        {
                            SendFile(sftp, Path.GetFileName(files[i]));
                        }
                    }
                    else
                    {
                        for (int i = 0; i < files.Length; i++)
                        {
                            SendFile(sftp, Path.GetFileName(files[i]));
                        }
                    }
                }

                sftp.Disconnect();
                sftp = null;

                _logDisplay.Display(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "," + FtpDirectoryInfo.SFTPHOST + " 접속을 해제했습니다.");
                log.Info(FtpDirectoryInfo.SFTPHOST + " disconnected");
            }
            catch (Exception ex)
            {
                _logDisplay.Display(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "," + ex.Message + " 문제가 발생했습니다.");
                log.Error(ex.Message);
            }
            finally
            {
                if (sftp != null)
                {
                    sftp.Dispose();
                    sftp = null;
                }
            }
        }
示例#19
0
        private void upload_Click(object sender, EventArgs e)
        {
            saveConfig();
            string host, username, password, fixedOut = "";
            int    port = -1;

            try
            {
                host = hostName.Text.Split('@')[1].Split(':')[0];
                try
                {
                    port = int.Parse(hostName.Text.Split('@')[1].Split(':')[1]);
                }
                catch (Exception)
                {
                    port = 22;
                }
                username = hostName.Text.Split('@')[0];
                password = userPass.Text;
                fixedOut = outputDir.Text.EndsWith("/") ? outputDir.Text : outputDir.Text + "/";
            }
            catch (Exception)
            {
                MessageBox.Show("Invalid argument(s).");
                return;
            }

            bool fail   = false;
            var  coninf = new ConnectionInfo(host, port, username, new PasswordAuthenticationMethod(username, userPass.Text), new PrivateKeyAuthenticationMethod(username, new PrivateKeyFile(keyPath.Text)));

            using (var client = new SftpClient(coninf))
            {
                try
                {
                    client.Connect();

                    if (uploadFile.Checked)
                    {
                        fixedOut += Path.GetFileName(sourcePath.Text);
                        FileStream fs = File.OpenRead(sourcePath.Text);
                        client.UploadFile(fs, fixedOut);
                    }
                    else
                    {
                        foreach (string file in Directory.EnumerateFiles(sourcePath.Text, "*.*", SearchOption.AllDirectories))
                        {
                            var separator    = unixPath.Checked ? '/' : '\\';
                            var revseparator = unixPath.Checked ? '\\' : '/';

                            var formattedpath = fixedOut + (Path.GetFileName(sourcePath.Text) +
                                                            "/" + file.ReplaceFirst(sourcePath.Text.EndsWith("\\") ?
                                                                                    sourcePath.Text : sourcePath.Text + "\\", ""));
                            formattedpath = formattedpath.Replace(revseparator, separator);

                            FileStream fs        = File.OpenRead(file);
                            var        splitpath = new List <string>(formattedpath.Split(separator));
                            splitpath.RemoveAt(splitpath.Count - 1);
                            var dirname = string.Join(separator.ToString(), splitpath.ToArray());
                            Debug.WriteLine(formattedpath);
                            Debug.WriteLine(dirname);

                            for (int i = 1; i < splitpath.Count; i++)
                            {
                                string check = string.Join(separator.ToString(), splitpath.Take(i + 1).ToArray());
                                Debug.WriteLine(check);
                                if (!client.Exists(check))
                                {
                                    client.CreateDirectory(check);
                                }
                            }
                            client.UploadFile(fs, formattedpath);
                        }
                    }

                    client.Disconnect();
                }
                catch (Exception err)
                {
                    MessageBox.Show("SFTP error: " + err.Message);
                    fail = true;
                }
                finally
                {
                    client.Dispose();
                }
            }
            if (!fail)
            {
                MessageBox.Show("File upload was successful!");
            }
        }
        public async static Task <bool> UploadFiles(Boolean UploadPrompt = true, Boolean AllLogs = true)
        {
            Global global = FormsApp.config.Global;

            // Path where the file should be saved once downloaded (locally)
            string path = (AllLogs) ? Mobile.LogPath : Mobile.LogUserPath;

            // Only upload if there are files available
            List <FileInfo> filesToUpload = LogFilesToUpload(path);

            var upload = false;

            if (filesToUpload.Count > 0)
            {
                upload = true;
            }

            if (UploadPrompt &&
                filesToUpload.Count > 0)
            {
                upload = await Application.Current.MainPage.DisplayAlert(
                    "Pending log files",
                    "Do you want to Upload them?",
                    "Ok", "Cancel");
            }
            //          else upload = false;


            if (!upload)
            {
                return(false);
            }

            // The FTP credentiales are not present in Global.xml
            if (!global.IsFtpUploadSet)
            {
                await Errors.ShowAlert(new FtpCredentialsMissingException());

                return(false);
            }

            // Has the devices internet connection
            if (!Mobile.IsNetAvailable())
            {
                await Errors.ShowAlert(new NoInternetException());

                return(false);
            }

            // Cancel action
            bool cancelled = false;

            System.Action OnCancel = () =>
            {
                cancelled = true;
            };

            TaskCompletionSource <bool> tcs = new TaskCompletionSource <bool> ();

            Device.BeginInvokeOnMainThread(async() =>
            {
                // Progress bar
                using (Acr.UserDialogs.IProgressDialog progress = UserDialogs.Instance.Progress("Uploading", OnCancel, "Cancel"))
                {
                    // Is necessary for appear the progress bar right now
                    await Task.Delay(10);

                    NumFilesUploaded = 0;

                    SftpClient sftp = null;

                    try
                    {
                        string remotePath = global.ftpRemotePath;
                        using (sftp = new SftpClient(global.ftpRemoteHost, 22, global.ftpUserName, global.ftpPassword))
                        {
                            sftp.Connect();

                            // If not exist create the remote path from global.xml
                            if (!sftp.Exists(remotePath))
                            {
                                sftp.CreateDirectory(remotePath);
                            }

                            using (MD5 md5Hash = MD5.Create())
                            {
                                byte[] md5Local;
                                byte[] md5Remote;
                                foreach (FileInfo file in filesToUpload)
                                {
                                    if (cancelled)
                                    {
                                        throw new Exception();
                                    }

                                    // Is necessary for update the progress bar
                                    await Task.Delay(10);

                                    // Upload local file to the FTP server
                                    using (FileStream fileStream = new FileStream(file.FullName, FileMode.Open))
                                    {
                                        // Folder path
                                        remotePath = Path.Combine(global.ftpRemotePath, file.Directory.Name); // Logs + User folder

                                        if (!sftp.Exists(remotePath))
                                        {
                                            sftp.CreateDirectory(remotePath);
                                        }

                                        // File path
                                        string sTick = DateTime.Now.Ticks.ToString();
                                        string sName = file.Name.Substring(0, 10) + "-" + sTick + "Log.xml";
                                        remotePath   = Path.Combine(remotePath, sName);

                                        sftp.UploadFile(fileStream, remotePath, null);
                                    }

                                    // Compare local and remote files
                                    using (StreamReader stream = new StreamReader(file.FullName))
                                        md5Local = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(stream.ReadToEnd()));

                                    md5Remote = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(sftp.ReadAllText(remotePath)));

                                    // If both files are equal, move local file to backup folder
                                    if (Enumerable.SequenceEqual(md5Local, md5Remote))
                                    {
                                        // Only create backup file ( "moving" log to backup folder ) in interactive mode
                                        if (!Data.Get.IsFromScripting)
                                        {
                                            string url_to_copy = Mobile.LogUserBackupPath;// Path.Combine ( file.Directory.FullName, Mobile.PATH_BACKUP );
                                            if (!Directory.Exists(url_to_copy))
                                            {
                                                Directory.CreateDirectory(url_to_copy);
                                            }

                                            File.Copy(file.FullName, Path.Combine(url_to_copy, file.Name), true);
                                        }
                                        File.Delete(file.FullName);

                                        NumFilesUploaded += 1;

                                        progress.PercentComplete = ( int )(NumFilesUploaded * 100 / filesToUpload.Count);

                                        Utils.Print("- " + file.Directory.Name + " uploaded");
                                    }
                                }
                            }

                            sftp.Disconnect();
                        }
                    }
                    catch (Exception e)
                    {
                        // Catch all exceptions and then always show the number of
                        // files uploaded using the exception FtpUpdateLogsException
                    }
                    finally
                    {
                        if (sftp != null)
                        {
                            sftp.Dispose();
                        }

                        sftp = null;

                        // Is necessary for appear the progress full ( 100% )
                        await Task.Delay(10);

                        tcs.SetResult(NumFilesUploaded == filesToUpload.Count);
                    }
                }
            });

            bool result = await tcs.Task; // Wait for upload completion

            // Finish ok if all files have been uploaded
            if (result)
            {
                return(true);
            }

            if (!cancelled)
            {
                await Errors.ShowAlert(new FtpUpdateLogsException ( NumFilesUploaded + "/" + filesToUpload.Count ));
            }
            else
            {
                await PageLinker.ShowAlert("Uploading canceled", "Only uploaded " + NumFilesUploaded + " / " + filesToUpload.Count + " log files");
            }

            return(false);
        }
        private void ShellBuilder()
        {
            bool          isExist  = false;
            string        userPath = (m_Username == "root") ? "/root" : $"/home/{m_Username}";
            List <string> path     = new List <string>();
            List <string> file     = new List <string>();

            foreach (var item in m_SftpClient.ListDirectory(userPath))
            {
                if (item.IsDirectory)
                {
                    path.Add(item.Name);
                }
            }
            if (!path.Contains("steamcmd"))
            {
                m_SftpClient.CreateDirectory(userPath + "/steamcmd");
            }

            foreach (var item in m_SftpClient.ListDirectory(userPath + "/steamcmd"))
            {
                if (!item.IsDirectory)
                {
                    file.Add(item.Name);
                }
            }
            if (file.Contains("steamcmd_linux.tar.gz"))
            {
                isExist = true;
            }

            m_SftpClient.Create(userPath + "/steamcmd" + "/getsteamcmd.sh");

            StringBuilder command = new StringBuilder(512);

            command.Append($" +force_install_dir {textBox_Path.Text.Replace(@"\", @"\\")}");
            command.Append($" +login anonymous");
            command.Append($" +app_update 343050");
            if ((bool)radioButton_Alpha.IsChecked)
            {
                command.Append($" -beta {textBox_Name.Text}");
            }
            command.Append($" validate");
            command.Append($" +quit");

            MemoryStream commandStream = new MemoryStream();
            StreamWriter commandWriter = new StreamWriter(commandStream, Encoding.UTF8);

            commandWriter.Write($"#!/bin/bash\n\n");
            commandWriter.Write($"cd steamcmd\n");
            if (!isExist)
            {
                commandWriter.Write($"wget https://steamcdn-a.akamaihd.net/client/installer/steamcmd_linux.tar.gz\n");
            }
            if (!isExist)
            {
                commandWriter.Write($"tar -xvzf steamcmd_linux.tar.gz\n");
            }
            //commandWriter.Write($"rm -f steamcmd_linux.tar.gz\n");
            commandWriter.Write($"chmod 777 ./steamcmd.sh\n");
            commandWriter.Write($"./steamcmd.sh {command.ToString()}\n");

            commandWriter.Flush();

            m_SftpClient.WriteAllBytes(userPath + "/steamcmd" + "/getsteamcmd.sh", commandStream.ToArray());
            commandStream.Close();

            SendCommand($"chmod 777 {userPath}/steamcmd/getsteamcmd.sh");
            SendCommand($"dos2unix {userPath}/steamcmd/getsteamcmd.sh");

            m_SftpClient.Dispose();
        }
示例#22
0
 public void Dispose()
 {
     client.Disconnect();
     client.Dispose();
 }
        private void RunCommand()
        {
            // check if the windows wallet is installed at %AppData%\Bitradio\\
            //if (!Directory.Exists(@"%AppData%\Bitradio\\"))
            //{
            //    MessageBox.Show("Have you installed the Wallet at /%AppData%/Roaming/Bitradio ?");  //If not
            //    return;
            //}

            //check for existing masternode.conf
            if (!File.Exists(@"%AppData%\Bitradio\\masternode.conf"))
            {
                using (StreamWriter sw = new StreamWriter(Environment.ExpandEnvironmentVariables(@"%AppData%\Bitradio\\masternode.conf"), true))  //if not than create
                {
                }
            }

            //load all variables

            ip             = ip_feld.Text;
            username       = username_feld.Text;
            password       = password_feld.Text;
            port           = port_feld.Text;
            genkey         = genkey_feld.Text;
            output         = output_feld.Text;
            output_after   = after_output_feld.Text;
            masternodename = masternodename_feld.Text;
            string TEMP_PATH = Path.GetTempPath();



            //login and create connection
            using (var client = new SshClient(ip, Convert.ToInt16(port), username, password))
            {
                // check if everything givem
                try
                {
                    client.Connect();
                    //port = null;
                    //masternodename = null;
                    //output_after = null;
                    //genkey = null;
                    //output = null;
                }
                catch
                {
                    if (language_info == "deu")
                    {
                        MessageBox.Show("Bitte fülle die Felder IP, Benutzername, Benutzerpasswort, rcuser und rpcpasswort aus!");
                    }
                    else if (language_info == "rus")
                    {
                        MessageBox.Show("Пожалуйста, укажите IP, пользователя, пароль, ключ (genkey), порт, выход, число после выхода и имя мастерноды!");
                    }
                    else
                    {
                        MessageBox.Show("Please fill out the IP, user, password, genkey, port, output, after_output and masternodename!");  //if not
                    }
                    return;
                }


                // Crappy way!! I don't know how to transfer a lokal variable to the vps. So I create lokal a file with the genkey as name, upload it
                // to the vps and read the new created directory. The output is the genkey :D

                var command = client.CreateCommand("mkdir /root/temp_bitradio/");
                var result  = command.BeginExecute();
                command = client.CreateCommand("cd /root/temp_bitradio/");
                result  = command.BeginExecute();

                //create the lokale file
                if (!File.Exists(TEMP_PATH + genkey))
                {
                    using (StreamWriter sw = new StreamWriter(Environment.ExpandEnvironmentVariables(TEMP_PATH + genkey), true))
                    {
                    }
                }
                client.Disconnect();
            }

            //upload the file
            using (var client = new SftpClient(ip, Convert.ToInt16(port), username, password))
            {
                client.Connect();

                FileInfo f          = new FileInfo(TEMP_PATH + genkey);
                string   uploadfile = f.FullName;

                var fileStream = new FileStream(uploadfile, FileMode.Open);
                if (fileStream != null)
                {
                    client.UploadFile(fileStream, "/root/temp_bitradio/" + f.Name, null);
                    client.Disconnect();
                    client.Dispose();
                }
            }

            // execute the ./Bitradiod install script (self-made)
            using (var client = new SshClient(ip, Convert.ToInt16(port), username, password))
            {
                client.Connect();

                var command = client.CreateCommand("./Bitradiod getblockcount");
                var result  = command.BeginExecute();
                if (startup_checkbox.Checked)
                {
                    command = client.CreateCommand("sudo wget https://raw.githubusercontent.com/Roalkege/bitradio_masternode_creator/master/Bitradio_MN_tool_cron.sh && bash Bitradio_MN_tool_cron.sh");  //download the script
                    result  = command.BeginExecute();
                }
                else
                {
                    command = client.CreateCommand("sudo wget https://raw.githubusercontent.com/Roalkege/bitradio_masternode_creator/master/Bitradio_MN_tool.sh && bash Bitradio_MN_tool.sh");  //download the script
                    result  = command.BeginExecute();
                }

                //log vps output
                using (var reader =
                           new StreamReader(command.OutputStream, Encoding.UTF8, true, 1024, true))
                {
                    while (!result.IsCompleted || !reader.EndOfStream)
                    {
                        string line = reader.ReadLine();
                        if (line != null)
                        {
                            log_feld.Invoke(
                                (MethodInvoker)(() =>
                                                log_feld.AppendText(line + Environment.NewLine)));
                        }
                    }
                }

                command.EndExecute(result);


                command = client.CreateCommand("cd ~");
                result  = command.BeginExecute();
                command = client.CreateCommand("rm Bitradio_MN_tool.sh");  //remove the script
                result  = command.BeginExecute();
                if (language_info == "ger")
                {
                    MessageBox.Show("Masternode wurde installiert, starte jetzt deine Windows Wallet neu und starte den Alias");
                }
                else if (language_info == "rus")
                {
                    MessageBox.Show("Мастернода установлена, теперь перезагрузите кошелек и начните работать в режиме анонимности.");
                }
                else
                {
                    MessageBox.Show("Masternode installed now restart your windows wallet and start the Alias");
                }
                client.Disconnect();
            }


            //edit the lokal masternode.conf
            using (StreamWriter sw = new StreamWriter(Environment.ExpandEnvironmentVariables(TEMP_PATH + @"\masternode.conf"), true))
            {
                sw.Write(masternodename + " " + ip + ":32454 " + genkey + " " + output + " " + output_after + " " + "\r\n");
            }
        }
 protected override void Act()
 {
     _sftpClient.Dispose();
 }
示例#25
0
        protected override bool _Run()
        {
            int r = Retry;

            while (r-- >= 0 && !Stop)
            {
                PostMortemMetaData["LastOperation"] = "NextAddress";
                _Address = Authentication.NextAddress(ServerAddress);

                if (_Address == null)
                {
                    Exception ex = new Exception("No valid address. (" + ServerAddress + ")");
                    Exceptions.Add(ex);
                    AppendToMessage(ex.Message);
                    return(false);
                }

                try
                {
                    string sData = null;
                    byte[] bData = null;

                    switch (TargetContainer)
                    {
                    case ContainerType.InstructionSetContainer:

                        if (!InstructionSet.InstructionSetContainer.ContainsKey(ContainerDataKey))
                        {
                            throw new Exception("ContainerDataKey (" + ContainerDataKey + ") does not exist.");
                        }

                        sData = InstructionSet.InstructionSetContainer[ContainerDataKey] as string;
                        bData = InstructionSet.InstructionSetContainer[ContainerDataKey] as byte[];

                        break;

                    case ContainerType.Session:

                        if (!STEM.Sys.State.Containers.Session.ContainsKey(ContainerDataKey))
                        {
                            throw new Exception("ContainerDataKey (" + ContainerDataKey + ") does not exist.");
                        }

                        sData = STEM.Sys.State.Containers.Session[ContainerDataKey] as string;
                        bData = STEM.Sys.State.Containers.Session[ContainerDataKey] as byte[];

                        break;

                    case ContainerType.Cache:

                        if (!STEM.Sys.State.Containers.Cache.ContainsKey(ContainerDataKey))
                        {
                            throw new Exception("ContainerDataKey (" + ContainerDataKey + ") does not exist.");
                        }

                        sData = STEM.Sys.State.Containers.Cache[ContainerDataKey] as string;
                        bData = STEM.Sys.State.Containers.Cache[ContainerDataKey] as byte[];

                        break;
                    }

                    string dFile = DestinationFile;

                    PostMortemMetaData["LastOperation"] = "FileExists";
                    if (Authentication.FileExists(_Address, Int32.Parse(Port), DestinationFile))
                    {
                        switch (FileExistsAction)
                        {
                        case STEM.Sys.IO.FileExistsAction.Skip:
                            return(true);

                        case STEM.Sys.IO.FileExistsAction.Throw:
                            r = -1;
                            throw new System.IO.IOException("Destination file exists. (" + DestinationFile + ")");

                        case STEM.Sys.IO.FileExistsAction.Overwrite:
                        case STEM.Sys.IO.FileExistsAction.OverwriteIfNewer:
                            Authentication.DeleteFile(_Address, Int32.Parse(Port), DestinationFile);
                            break;

                        case STEM.Sys.IO.FileExistsAction.MakeUnique:
                            DestinationFile = Authentication.UniqueFilename(_Address, Int32.Parse(Port), DestinationFile);
                            break;
                        }
                    }

                    dFile = Authentication.AdjustPath(_Address, dFile);
                    string directory = Authentication.AdjustPath(_Address, STEM.Sys.IO.Path.GetDirectoryName(dFile));

                    PostMortemMetaData["LastOperation"] = "DirectoryExists";
                    if (!Authentication.DirectoryExists(_Address, Int32.Parse(Port), directory))
                    {
                        PostMortemMetaData["LastOperation"] = "CreateDirectory";
                        Authentication.CreateDirectory(_Address, Int32.Parse(Port), directory);
                    }

                    byte[] data = null;

                    if (bData != null && bData.Length > 0)
                    {
                        data = bData;
                    }

                    if (data == null)
                    {
                        if (sData != null && sData.Length > 0)
                        {
                            data = System.Text.Encoding.UTF8.GetBytes(sData);
                        }
                    }

                    if (data == null && CreateEmptyFiles)
                    {
                        data = new byte[1];
                    }

                    if (data != null)
                    {
                        PostMortemMetaData["LastOperation"] = "OpenSftpClient";
                        SftpClient client = null;

                        try
                        {
                            client = Authentication.OpenSftpClient(_Address, Int32.Parse(Port));

                            try
                            {
                                PostMortemMetaData["LastOperation"] = "UploadFile";
                                using (System.IO.MemoryStream s = new System.IO.MemoryStream(data))
                                {
                                    client.UploadFile(s, dFile);

                                    _SavedFile = dFile;
                                }
                            }
                            finally
                            {
                                PostMortemMetaData["LastOperation"] = "RecycleClient";
                                Authentication.RecycleClient(client);
                                client = null;
                            }
                        }
                        catch
                        {
                            try
                            {
                                client.Disconnect();
                            }
                            catch { }
                            try
                            {
                                client.Dispose();
                            }
                            catch { }

                            throw;
                        }
                    }

                    break;
                }
                catch (Exception ex)
                {
                    if (r < 0)
                    {
                        AppendToMessage(ex.Message);
                        Exceptions.Add(ex);
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(RetryDelaySeconds * 1000);
                    }
                }
            }

            return(Exceptions.Count == 0);
        }
示例#26
0
        public override void Execute()
        {
            switch (FileTransferAction)
            {
            case eFileTransferAction.GetFile:
                try
                {
                    if (!ConnectFTPClient())
                    {
                        return;
                    }
                    string UnixTargetFilePath = UnixPathCalculated;
                    if (UnixFTPClient.Exists(UnixTargetFilePath) == false)
                    {
                        this.Error = "'" + UnixPathCalculated + "' path does not exists";
                        return;
                    }

                    DownloadFileAndValidate(UnixTargetFilePath, PCPathCalculated);
                }
                catch (Exception e)
                {
                    this.Error = e.Message;
                    Reporter.ToLog(eLogLevel.ERROR, "Get File", e);
                }
                finally
                {
                    UnixFTPClient.Disconnect();
                    UnixFTPClient.Disconnect();
                }

                break;

            case eFileTransferAction.PutFile:
                try
                {
                    if (!ConnectFTPClient())
                    {
                        return;
                    }
                    string unixTargetFolder = CalculateTargetFolder();

                    if (IsDir(PCPathCalculated) == false)
                    {
                        UploadFileAndValidate(PCPathCalculated, unixTargetFolder);
                    }
                    else
                    {
                        string[] fileEntries = Directory.GetFiles(PCPathCalculated);
                        foreach (string fileName in fileEntries)
                        {
                            UploadFileAndValidate(fileName, unixTargetFolder);
                        }
                    }
                }
                catch (Exception e)
                {
                    this.Error = e.Message;
                    Reporter.ToLog(eLogLevel.ERROR, "Put File", e);
                }
                finally
                {
                    UnixFTPClient.Disconnect();
                    UnixFTPClient.Dispose();
                }
                break;

            default:
                break;
            }
        }
示例#27
0
        private void btnQuit_Click(object sender, EventArgs e)
        {
            try
            {
                if (rdp.Connected.ToString() == "1")
                {
                    rdp.Disconnect();
                    timer1.Stop();
                    vf.Close();
                    // Move recording to blob storage
                    var      location   = new System.IO.DirectoryInfo(Path.GetTempPath() + timeStamp + ".avi");
                    FileInfo f          = new FileInfo(location.ToString());
                    string   uploadfile = f.FullName;
                    var      client     = new SftpClient("92.233.50.207", 22, "root", "ChocolateBalls1");
                    client.Connect();
                    client.ChangeDirectory(@"/Recordings");
                    var fileStream = new FileStream(location.ToString(), FileMode.Open);
                    client.BufferSize = 4 * 1024;
                    client.UploadFile(fileStream, f.Name, null);
                    client.Disconnect();
                    client.Dispose();

                    //using (var scp = new ScpClient("92.233.50.207", "root", "toor"))
                    //{
                    //    scp.Connect();
                    //    var location = new System.IO.DirectoryInfo(Path.GetTempPath() + timeStamp + ".avi");
                    //    scp.Upload(location, "/recordings " + timeStamp + ".avi");
                    //}

                    //ScpClient currentScp = new ScpClient("92.233.50.207", "administrator", "test");
                    //currentScp.Connect();
                    //var location = new System.IO.DirectoryInfo(Path.GetTempPath() + timeStamp + ".avi");
                    //currentScp.Upload(location, "/recordings " + timeStamp + ".avi");
                    //currentScp.Disconnect();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Disconnecting", "Error disconnecting from the seesion. Please try again!");
                this.Close();
            }
            // Ship recording

            // Ship the Log!
            current.SessionKey         = information.Token;
            current.UserId             = information.UserId;
            current.LogContentLocation = timeStamp + ".avi";
            current.PermissionLevelId  = 1;
            current.FinishTime         = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            current.UserNote           = "";
            current.ProtectedAccountId = 2;

            string json = "";

            json = JsonConvert.SerializeObject(current);
            json = "=" + json;

            string path = "";

            path = information.URL + "/api/desktopLog";

            string response = ApiConnector.SendToApi(path, json);

            this.Close();
        }
示例#28
0
 public void Dispose()
 {
     Debug.WriteLine("Closing Sftp connection...");
     _sftp.Dispose();
 }
示例#29
0
        /// <summary>
        /// Метод копирования файла на хост
        /// </summary>
        /// <param name="fileName">имя файла</param>
        /// <param name="pathToFile">путь к файлу</param>
        /// <param name="pathDestination">путь, куда будет скопирован файл</param>
        /// <param name="ipAddress">ip адрес хоста</param>
        /// <param name="login">логин, для подключения к хосту</param>
        /// <param name="password">пароль, для подключения к хосту</param>
        public void SftpCopy(string fileName, string pathToFile, string pathDestination, string ipAddress, string login, string password, bool addToListBoxTask = true)
        {
            try
            {
                bool endRunThread = false;
                var  startThread  = new Thread(new ThreadStart(() =>
                {
                    //BackgroundWorker progressBarCopyWorker = new BackgroundWorker();
                    PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(ipAddress, 22, login, password);
                    connectionInfo.Timeout         = TimeSpan.FromSeconds(15);
                    string fileFullName            = System.IO.Path.Combine(pathToFile, fileName);
                    string fileDestinationFullName = System.IO.Path.Combine(pathDestination, fileName);

                    ItemListBoxTask curItemLBT = new ItemListBoxTask()
                    {
                        IPOrName = ipAddress, Description = $"Выполняется копирование: {fileName} в {pathDestination}", CVZNumber = $"ЦВЗ№{SelectedTT.NumberCVZ.ToString()}"
                    };


                    #region Скопировать файл на хост
                    // Проверка доступности файла
                    if (File.Exists(fileFullName))
                    {
                        //Dispatcher.Invoke(() =>
                        //{

                        if (addToListBoxTask)
                        {
                            Dispatcher.Invoke(() =>
                            {
                                Bindings.listBoxTaskItemsSource.Add(curItemLBT);
                            });
                            //ListBoxTask.Items.Add(curItemLBT);
                        }
                        using (FileStream stream = new FileStream(fileFullName, FileMode.Open, FileAccess.Read))
                        {
                            curItemLBT.MaxValueProgressBar = stream.Length;
                            //progressBarStatus.Maximum = stream.Length;
                        }
                        //progressBarStatus.Value = 0;
                        //progressBarStatus.Visibility = Visibility.Visible;
                        //Bindings.StatusBarText = $"Выполняется копирование файла {fileName}";
                        bool uploadFileStoped = false;
                        UpdateProgressBarDelegate updProgress = new UpdateProgressBarDelegate(progressBarStatus.SetValue);
                        //UpdateProgressBarDelegate updProgressItemTask = new UpdateProgressBarDelegate(progressBarStatus.SetValue);
                        using (var sftp = new SftpClient(connectionInfo))
                        {
                            try
                            {
                                sftp.Connect();

                                using (FileStream stream = new FileStream(fileFullName, FileMode.Open, FileAccess.Read))
                                {
                                    var startUpload = sftp.BeginUploadFile(stream, fileDestinationFullName, (asyncCallback) =>
                                    {
                                        //sftp.EndUploadFile(startUpload);
                                        endRunThread = true;
                                    }, null, (progressBarStatusCallBack) =>
                                    {
                                        var temp = curItemLBT.StopProcess;
                                        if (curItemLBT.StopProcess)
                                        {
                                            if (!uploadFileStoped)
                                            {
                                                try
                                                {
                                                    uploadFileStoped = true;
                                                    sftp.Disconnect();
                                                    endRunThread = true;
                                                }
                                                catch (Exception)
                                                {
                                                }
                                            }
                                        }
                                        Dispatcher.Invoke((Action)(() => { curItemLBT.CurValueProgressBar = (double)progressBarStatusCallBack; }));
                                        Dispatcher.Invoke(updProgress, System.Windows.Threading.DispatcherPriority.Render, new object[] { MetroProgressBar.ValueProperty, (double)progressBarStatusCallBack });
                                    });


                                    while (!startUpload.IsCompleted)
                                    {
                                        if (startUpload.IsCompleted)
                                        {
                                            stream.Close();
                                            stream.Dispose();
                                            endRunThread = true;
                                        }
                                    }

                                    Log(!uploadFileStoped ? $"Выполнено копирование {fileDestinationFullName} на хост {ipAddress}" : $"Прервано копирование {fileDestinationFullName} на хост {ipAddress}", false, true);
                                }
                            }
                            //catch(excep)
                            catch (Exception ex)
                            {
                                Log(!uploadFileStoped ? ex.Message : $"Прервано копирование {fileDestinationFullName} на хост {ipAddress}", false, true);
                                //Log(ex.Message, true, false, ex.StackTrace);
                            }
                            finally
                            {
                                try
                                {
                                    sftp.Disconnect();
                                    sftp.Dispose();
                                }
                                catch (Exception)
                                {
                                }
                            }
                        }
                    }
                    else
                    {
                        Log($"{fileFullName} не доступен", true, true);
                    }

                    #endregion
                    //}
                }));
                startThread.Start();

                //startThread.Suspend();

                //new Thread(new ThreadStart(() =>
                //{
                //    while (!endRunThread)
                //    {
                //        if (endRunThread)
                //        {
                //            int endD = 1;
                //        }
                //    }
                //})).Start();
            }
            catch (Exception ex)
            {
                Log(ex.Message, true, true, ex.StackTrace);
            }
        }
示例#30
0
        public async Task <Boolean> EncriptarEnviarArchivoAsync(CancellationToken cancelToken, String nombreArchivo, String rutaArchivo)
        {
            Boolean esConforme = false, esEncriptado = false, esEnviado = false;
            String  arguments = String.Empty, error = String.Empty, message = String.Empty;

            try
            {
                if (nombreArchivo != String.Empty)
                {
                    String rutaDestino       = String.Format("{0}{1}{2}", _carpetaEncriptado, nombreArchivo, Constante.EXTENSION_PGP);
                    String carpetaEncriptado = _carpetaEncriptado.Substring(Constante._0, _carpetaEncriptado.LastIndexOf(Constante.DELIMITADOR_BACKSLASH));
                    String homeDirectory     = string.Format("\"{0}\"", Constante.PGP_DIRECTORY);
                    arguments = String.Format("{0} {1} {2} {3} {4} {5} {6} {7} {8}", Constante.PGP_VERBOSE, Constante.PGP_HOME_DIRECTORY, homeDirectory, Constante.PGP_ENCRYPT, rutaArchivo, Constante.SCOTIABANK_DEV_KEY_ID, Constante.PGP_OUTPUT, carpetaEncriptado, Constante.PGP_OVERWRITE);
                    Process process = new Process();
                    process.StartInfo.FileName               = Constante.PGP_EXE;
                    process.StartInfo.Arguments              = arguments;
                    process.StartInfo.UseShellExecute        = false;
                    process.StartInfo.CreateNoWindow         = true;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError  = true;
                    process.Start();
                    message = process.StandardOutput.ReadToEnd();
                    error   = process.StandardError.ReadToEnd();
                    process.WaitForExit(Timeout.Infinite);

                    if (File.Exists(rutaDestino))
                    {
                        esEncriptado = true;
                        File.Delete(rutaArchivo);
                        rutaArchivo   = String.Format("{0}{1}{2}", _carpetaEncriptado, nombreArchivo, Constante.EXTENSION_PGP);
                        nombreArchivo = nombreArchivo.Replace(Constante.EXTENSION_TXT, Constante.EXTENSION_PGP);

                        PasswordAuthenticationMethod authentication = new PasswordAuthenticationMethod(_usuario, _clave);
                        ConnectionInfo connection = new ConnectionInfo(_servidor, _puerto, _usuario, authentication);
                        using (SftpClient sftpClient = new SftpClient(connection))
                        {
                            sftpClient.Connect();
                            Boolean isConnected = sftpClient.IsConnected;

                            if (isConnected)
                            {
                                using (FileStream fileStream = File.OpenRead(rutaArchivo))
                                {
                                    String rutaRemota = String.Format("{0}{1}", Constante.CARPETA_IN, nombreArchivo);
                                    sftpClient.UploadFile(fileStream, rutaRemota);
                                    esEnviado  = sftpClient.Exists(rutaRemota);
                                    esConforme = esEnviado == true ? true : false;
                                }
                            }

                            sftpClient.Disconnect();
                            sftpClient.Dispose();
                        }
                    }
                }

                String mensajeEncriptado = esEncriptado ? Constante.MENSAJE_ENCRIPTAR_ARCHIVO_ASYNC_OK : Constante.MENSAJE_ENCRIPTAR_ARCHIVO_ASYNC_NO_OK;
                String mensajeEnviado    = esEnviado ? Constante.MENSAJE_ENVIAR_ARCHIVO_HACIA_BANCO_ASYNC_OK : Constante.MENSAJE_ENVIAR_ARCHIVO_HACIA_BANCO_ASYNC_NO_OK;
                String mensaje           = esConforme ? String.Format("{0} {1}", Constante.MENSAJE_ENCRIPTAR_ARCHIVO_ASYNC_OK, Constante.MENSAJE_ENVIAR_ARCHIVO_HACIA_BANCO_ASYNC_OK) : String.Format("{0} | {1} | {2} | {3} | {4}", mensajeEncriptado, mensajeEncriptado, arguments, message, error);
                await _bitacora.RegistrarEventoAsync(cancelToken, Constante.BITACORA_NOTIFICACION, Constante.PROYECTO_COMUN, Constante.CLASE_UTIL, Constante.METODO_ENCRIPTAR_ENVIAR_ARCHIVO_ASYNC, mensaje);
            }
            catch (Exception e)
            {
                await _bitacora.RegistrarEventoAsync(cancelToken, Constante.BITACORA_ERROR, Constante.PROYECTO_COMUN, Constante.CLASE_UTIL, Constante.METODO_ENCRIPTAR_ENVIAR_ARCHIVO_ASYNC, Constante.MENSAJE_ENCRIPTAR_ARCHIVO_ASYNC_NO_OK, e.Message);

                throw e;
            }
            return(esConforme);
        }
 protected void Act()
 {
     _sftpClient.Dispose();
 }