Example #1
0
        public int Execute()
        {
            try
            {
                // Setup session options
                String hostname = Params.sftpauth.Split('@')[1];
                String username = Params.sftpauth.Split(':')[0];
                String password = Params.sftpauth.Split('@')[0].Split(':')[1];

                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    HostName = hostname,
                    UserName = username,
                    Password = password,
                    SshHostKeyFingerprint = Params.fingerprint
                };

                //Console.WriteLine("Host {0} user {1} pw {2}", hostname, username, password);

                using (Session session = new Session())
                {
                    session.Open(sessionOptions);

                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Binary;

                    if (Params.RecordInitialFileList.Equals("true", StringComparison.InvariantCultureIgnoreCase))
                    {
                        RecordInitialFileList(Params.DownloadedFiles +"_" +  System.Guid.NewGuid().ToString() + ".txt", ListFiles(session, Params.RemoteDir));
                        session.Close();
                        return 0;
                    }

                    List<FileObject> newfiles = GetNewFileNames(ReadLocalFileNames(Params.DownloadedFiles), ListFiles(session, Params.RemoteDir));
                    foreach (FileObject item in newfiles)
                    {
                        DownLoadFile(session, transferOptions, Params.RemoteDir + item.Name, Params.LocalDir);
                        AppendToFile(Params.DownloadedFiles, item.Name);
                    }

                    session.Close();
                }

                return 0;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
                Logger.Error(e.Message);
                throw e;

            }
        }
Example #2
0
 public void Disconnect()
 {
     if (Connected)
     {
         _session.Close();
     }
 }
Example #3
0
        private void SFTPDownload(SessionOptions so, string OPFolderName, List <string> IPDir, List <string> OPdir)
        {
            try
            {
                session = new WinSCP.Session();
                session.Open(so);
                for (int i = 0; i < IPDir.Count; i++)
                {
                    string localPath = $"{OPFolderName}{OPdir[i]}";
                    localPath = DeserialiseXMLFromStr(localPath);
                    Directory.CreateDirectory(localPath);
                    string remotePath = IPDir[i];
                    remotePath = DeserialiseXMLFromStr(remotePath);
                    // Enumerate files and directories to download
                    IEnumerable <RemoteFileInfo> fileInfos = session.EnumerateRemoteFiles(remotePath, null, EnumerationOptions.EnumerateDirectories | EnumerationOptions.AllDirectories);

                    foreach (RemoteFileInfo fileInfo in fileInfos)
                    {
                        string localFilePath = session.TranslateRemotePathToLocal(fileInfo.FullName, remotePath, localPath);

                        if (fileInfo.IsDirectory)
                        {
                            // Create local subdirectory, if it does not exist yet
                            Directory.CreateDirectory(localFilePath);
                        }
                        else
                        {
                            WriteToLogBox($"Downloading file {fileInfo.FullName}...");
                            // Download file
                            string remoteFilePath = session.EscapeFileMask(fileInfo.FullName);
                            TransferOperationResult transferResult = session.GetFiles(remoteFilePath, localFilePath);
                            if (!transferResult.IsSuccess)
                            {
                                WriteToLogBox($"Error downloading file {fileInfo.FullName}: {transferResult.Failures[0].Message}");
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                WriteToLogBox($"Error: {e}");
            }
            finally
            {
                session.Close();
                session.Dispose();
                GC.Collect();
            }
        }
Example #4
0
 private void DoTestConnection(object sender, DoWorkEventArgs e)
 {
     try
     {
         using (Session session = new Session())
         {
             session.Open(sessionOptions);
             session.Close();
         }
         RaiseConnectionOK();
     }
     catch (Exception ex)
     {
         RaiseConnectionFAILED();
     }
 }
Example #5
0
 private void DoTransmission(Database db,EmailNotifications emailSettings)
 {
     sendAttempts++;
    new Log("FTP transmission for \"" + db.GetAlias() + "\" started.");
     try
     {
         using (Session session = new Session())
         {
             session.Open(sessionOptions);
             TransferOptions transferOptions = new TransferOptions();
             transferOptions.TransferMode = TransferMode.Binary;
             TransferOperationResult transferResult;
             transferResult = session.PutFiles(db.GetFile(), "DB_" + db.GetAlias() + "_bu" + DateTime.Now.ToString("yyyyMMddHHmm") + ".sql", false, transferOptions);
             transferResult.Check();
             new Log("FTP transmission for \"" + db.GetAlias() + "\" completed successfully.");
             session.Close();
             emailSettings.NotifyCheck(db.GetAlias(),EmailNotifications.FTP_OPERATION_OK);
         }
     }
     catch (Exception ex)
     {
         if (sendAttempts < 6)
             DoTransmission(db,emailSettings);
         else
         {
             new Log("ERROR: FTP transmission for \"" + db.GetAlias() + "\" failed.");
             emailSettings.NotifyCheck(db.GetAlias(), EmailNotifications.FTP_OPERATION_FAIL);
         }
     }
 }
        private void UploadCSV(string filePath)
        {
            var scpSession = new Session();
            var xferOptions = new TransferOptions();
            var sessionOptions = new SessionOptions()
            {
                Protocol = Protocol.Sftp,
                HostName = Configuration.SFTPServer,
                UserName = Configuration.SFTPUsername,
                Password = Configuration.SFTPPassword,
                SshHostKeyFingerprint = Configuration.SFTPServerFingerprint
            };

            try
            {
                xferOptions.TransferMode = TransferMode.Binary;
                scpSession.SessionLogPath = string.Format("{0}\\Log\\{1}-{2}.xferLog", System.IO.Directory.GetCurrentDirectory(), Configuration.TableName, DateTime.Now.ToString("MM-dd-yyyy"));
                scpSession.Open(sessionOptions);
                var xferResult = scpSession.PutFiles(filePath, Configuration.SFTPRemotePath, false, xferOptions);
                xferResult.Check();
                System.IO.File.Delete(filePath);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to upload file", ex);
            }
            finally
            {
                scpSession.Close();
            }
        }
Example #7
-1
        public static void SyncFile()
        {
            SessionOptions sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Sftp,
                HostName = Param.SqlCeConfig["sshServer"].ToString(),
                UserName = Param.SqlCeConfig["sshUsername"].ToString(),
                SshPrivateKeyPath = Param.SqlCeConfig["sshKeyPath"].ToString(),
                PortNumber = int.Parse(Param.SqlCeConfig["sshPort"].ToString()),
                SshHostKeyFingerprint = Param.SqlCeConfig["sshHostKey"].ToString()
            };

            if (CanConnectInternet())
            {
                using (Session session = new Session())
                {
                    session.Open(sessionOptions);

                    RemoteFileInfo fileInfo = session.GetFileInfo(Param.ScpSoftwarePath + "/Updater.exe");
                    FileInfo fi = new FileInfo("Updater.exe");
                    if (DateTimeToUnixTimestamp(fi.LastWriteTime) != DateTimeToUnixTimestamp(fileInfo.LastWriteTime))
                    {
                        try
                        {
                            TransferOptions transferOptions = new TransferOptions();
                            transferOptions.TransferMode = TransferMode.Automatic;
                            TransferOperationResult transferResult;
                            transferResult = session.GetFiles(Param.ScpSoftwarePath + "/Updater.exe", "Updater.exe", false, transferOptions);
                            transferResult.Check();
                            foreach (TransferEventArgs transfer in transferResult.Transfers)
                            {
                                WriteLog(string.Format("Download of {0} : {1} succeeded", transfer.FileName, transfer.Destination));
                            }
                        }
                        catch (Exception ex)
                        {
                            WriteErrorLog(string.Format("SCP Download Error : {0}", ex.Message));
                        }
                    }

                    //session.FileTransferred += FileTransferred;
                    if (Directory.Exists(Param.ApplicationDataPath + @"\log"))
                    {
                        try
                        {
                            TransferOptions transferOptions = new TransferOptions();
                            transferOptions.TransferMode = TransferMode.Automatic;

                            SynchronizationResult synchronizationResult;
                            synchronizationResult = session.SynchronizeDirectories(SynchronizationMode.Remote,
                                Param.ApplicationDataPath + @"\log", Param.ScpLogPath, false, false, SynchronizationCriteria.Time, transferOptions);
                            synchronizationResult.Check();
                        }
                        catch (Exception ex)
                        {
                            WriteErrorLog(string.Format("SCP SynchronizeDirectories Error : {0}", ex.Message));
                        }
                    }

                    session.Close();
                }
            }

        }