Exemplo n.º 1
2
        private int Download(String HostName, String UserName, String Password, String remoteFilePath, String localPath)
        {
            int result = 0;
            Session session = null;

            // Setup session options               
            SessionOptions sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Ftp,
                HostName = HostName,
                UserName = UserName,
                Password = Password,                
                //HostName =  "119.59.73.48",
                //UserName = "******",
                //Password =  "******",
                //  SshHostKeyFingerprint = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
            };

           
            try
            {

                using (session = new Session())
                {

                    // Connect    
                    session.ReconnectTime = new TimeSpan(0, 0, 30);
                    session.Open(sessionOptions);

                    // Download files
                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Binary;
                  //  transferOptions.ResumeSupport.State = TransferResumeSupportState.Smart;
                    //transferOptions.ResumeSupport.Threshold = 1000;
                    

                    TransferOperationResult transferResult = null;
                Retry:
                    try
                    {
                        transferResult = session.GetFiles(remoteFilePath, localPath, false, transferOptions);


                        // Throw on any error
                        transferResult.Check();
                        // Print results
                        foreach (TransferEventArgs transfer in transferResult.Transfers)
                        {
                            Console.WriteLine("Download of {0} succeeded", transfer.FileName);
                        }


                        result = 0;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error: {0}", e);
                        goto Retry;

                        // result = 1;
                    }
                }
               
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }
            return result;
        }
Exemplo n.º 2
1
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
            //                FolderBrowserDialog ofd = new FolderBrowserDialog();
            //                ofd.ShowDialog();
                string folderToUpload = @"C:\Users\canpy_000\OneDrive\Documents\GitHub\groupVolumeControl(SPIRE)\Installer\Release\*";

                // Setup session options
                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    HostName = "coderguydev.com",
                    UserName = usr,
                    Password = pw,
                    SshHostKeyFingerprint = "ssh-rsa 2048 0d:3c:74:bb:7f:8b:6b:3c:a0:cb:aa:e3:75:a7:30:52"
                };

                using (Session session = new Session())
                {
                    // Connect
                    session.Open(sessionOptions);
                    RemoteDirectoryInfo targetServerDir = session.ListDirectory("/opt/mean/public/VolumeControlUtility/CurrentVersion/");
                    Console.WriteLine(targetServerDir.ToString());
                    // Upload files
                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Binary;

                    TransferOperationResult transferResult;
                    //transferResult = session.PutFiles(@"d:\toupload\*", "/home/user/", false, transferOptions);
                    transferResult = session.PutFiles(folderToUpload, "/opt/mean/public/VolumeControlUtility/CurrentVersion/",
                        false, transferOptions);

                    // Throw on any error
                    transferResult.Check();

                    // Print results
                    foreach (TransferEventArgs transfer in transferResult.Transfers)
                    {
                        Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
                    }
                }

            }
            catch (Exception err)
            {
                Console.WriteLine("Error: {0}", err);
            }
        }
Exemplo n.º 3
1
        public static int Main()
        {
            try
            {
                Helper.AddtoLogFile("-------Program Starts Running----------");
                // Setup session options
                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    HostName = ConfigurationManager.AppSettings["HostName"].ToString(),
                    UserName = ConfigurationManager.AppSettings["UserName"].ToString(),
                    Password = ConfigurationManager.AppSettings["Password"].ToString(),
                    SshHostKeyFingerprint = ConfigurationManager.AppSettings["SshHostKeyFingerprint"].ToString()
                };

                using (Session session = new Session())
                {
                    // Connect
                    session.Open(sessionOptions);
                    Helper.AddtoLogFile("-------Session instance successfully Created.----------");
                    List<SFTPmap> ImportFilePaths = DBProvider.Instance.DownloadParameters();
                    Helper.AddtoLogFile("All File Paths are download.");
                    foreach (SFTPmap item in ImportFilePaths)
                    {
                        if (!string.IsNullOrEmpty(item.FolderNameAlias))
                       {
                            try
                            {
                                Helper.AddtoLogFile("Looping for " + item.FolderNameAlias);
                                Helper.AddtoLogFile("File Path " + item.FilePath);

                                string LocalPath = item.FilePath;
                                string RemotePath = ConfigurationManager.AppSettings["RemotePath"].ToString() + item.FolderNameAlias;

                                RemoteDirectoryInfo directory = session.ListDirectory(RemotePath);
                                LocalPath = LocalPath + item.FolderName + "\\";

                                foreach (RemoteFileInfo fileInfo in directory.Files)
                                {
                                    if (!Directory.Exists(LocalPath))
                                    {
                                        Directory.CreateDirectory(LocalPath);
                                    }

                                    if (!File.Exists(LocalPath + fileInfo.Name))
                                    {
                                        try
                                        {
                                            if (fileInfo.Name != "..")
                                            {
                                                session.GetFiles(RemotePath + "/" + fileInfo.Name, LocalPath + fileInfo.Name).Check();
                                                Console.WriteLine("File Tranfer successful from " + RemotePath + "/" + fileInfo.Name + " to " + LocalPath + fileInfo.Name);
                                                Helper.AddtoLogFile("File Tranfer successful from " + RemotePath + "//" + fileInfo.Name + " to " + LocalPath + fileInfo.Name);
                                            }
                                        }
                                        catch (Exception Ex)
                                        {
                                            Console.WriteLine("Error Occurse:" + Ex.ToString());
                                            Helper.AddtoLogFile("Error Occurse:" + Ex.ToString());
                                        }
                                    }
                                }
                                // Upload files -

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

                                //TransferOperationResult transferResult;
                                //transferResult = session.GetFiles(RemotePath + "*", LocalPath, false, transferOptions);

                                //// Throw on any error
                                //transferResult.Check();

                                //// Print results
                                //foreach (TransferEventArgs transfer in transferResult.Transfers)
                                //{
                                //    Console.WriteLine("Download of {0} succeeded", transfer.FileName);
                                //    Helper.AddtoLogFile("Download of " + transfer.FileName + " succeeded");
                                //}

                            }
                            catch (Exception ex) { Helper.AddtoLogFile("Error:" + ex.ToString()); }
                        }
                    }
                }
                Helper.AddtoLogFile("-------Program End----------");
                return 0;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
                Helper.AddtoLogFile("Error:" + e.ToString());
                Helper.AddtoLogFile("-------Program End----------");
                return 1;
            }
        }
Exemplo n.º 4
1
        /// <summary> 
        /// Downloads audio from the robot  
        /// </summary> 
        /// <param name="sender"> object that called the method </param> 
        /// <param name="e"> any additional arguments </param> 
        void bgWorker_DoWork(object sender, DoWorkEventArgs e) 
        { 
            // Setup session options 
            SessionOptions sessionOptions = new SessionOptions 
            { 
                Protocol = Protocol.Sftp, 
                HostName = ipString, 
                UserName = "******", 
                Password = "******", 
                SshHostKeyFingerprint = "ssh‐rsa 20487c:48:34:e3:c0:7a:92:8e:2f:95:79:0e:12:69:79:e7", 
            }; 
 
            using (Session session = new Session()) 
            { 
                // tell library path to the winSCP executable 
                session.ExecutablePath = System.IO.Directory.GetCurrentDirectory() 
+ "\\winSCPexe.exe"; 
       
                // Connect 
                session.Open(sessionOptions); 
 
                //Set up transfer 
                TransferOptions transferOptions = new TransferOptions(); 
                transferOptions.TransferMode = TransferMode.Binary; 
 
                // generate a file based on date and time 
                string time = Convert.ToString(DateTime.UtcNow.ToFileTime()); 
 
                string destination = "C:\\NAOcam\\" + "NAO_Audio_" + time + ".ogg"; 
 
                // download files 
                TransferOperationResult transferResult; 
                transferResult = session.GetFiles("/home/nao/temp.ogg", 
@destination, true, transferOptions); 
 
                // Throw on any error 
                transferResult.Check(); 
            } 
        } 
Exemplo n.º 5
0
 // S-FTP connection with password
 public SFtpClient(string hostname, string username, string password, string hostKey = "")
 {
     if (string.IsNullOrEmpty(hostKey))
     {
         _sessionOptions = new SessionOptions
         {
             Protocol = Protocol.Sftp,
             HostName = hostname,
             UserName = username,
             Password = password,
             GiveUpSecurityAndAcceptAnySshHostKey = true
         };
     }
     else
     {
         _sessionOptions = new SessionOptions
         {
             Protocol = Protocol.Sftp,
             HostName = hostname,
             UserName = username,
             Password = password,
             SshHostKeyFingerprint = hostKey
         };
     }
 }
Exemplo n.º 6
0
    public static void Sync()
    {
      var optoins = new SessionOptions()
      {
        Protocol = Protocol.Ftp,
        FtpSecure = WinSCP.FtpSecure.ExplicitTls,
        HostName = Config.FTP_HOSTNAME,
        PortNumber = Config.FTP_PORT,
        UserName = Config.FTP_USER,
        Password = Config.FTP_PWD,
      };

      using (var session = new Session())
      {
        Logger.Debug("About to try to connect to the TRTH server...",typeof(FTPSynchroniser));
        session.Open(optoins);

        Logger.Debug("Synchronising directories...",typeof(FTPSynchroniser));
        var result = session.SynchronizeDirectories(SynchronizationMode.Local, Config.DIR_SYNC_TO, Config.DIR_REMOTE, false);

        Logger.Debug(string.Format("FTP Sync Result = {0}", result), typeof (FTPSynchroniser));

        foreach (var file in result.Downloads)
          Logger.DebugFormat(typeof (FTPSynchroniser), "Downloaded {0}", file);
      }

    }
Exemplo n.º 7
0
        private ArrayList ListFiles(String HostName, String UserName, String Password, String remotePath)
        {
            //int result = 0;
            Session session = null;
            ArrayList fileNameList = new ArrayList();
            try
            {
                // Setup session options               
                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Ftp,
                    HostName = HostName,
                    UserName = UserName,
                    Password = Password,
                    //HostName =  "119.59.73.48",
                    //UserName = "******",
                    //Password =  "******",
                    //  SshHostKeyFingerprint = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
                };

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



                    RemoteDirectoryInfo dirInfo = session.ListDirectory(remotePath);

                    foreach (RemoteFileInfo file in dirInfo.Files)
                    {

                        if (!file.IsDirectory)
                        {
                            fileNameList.Add(file.Name);
                        }
                        // Console.WriteLine("File Name: {0},LastWriteTime: {1},IsDirectory: {2},File Length: {3},", file.Name, file.LastWriteTime, file.IsDirectory, file.Length);
                    }

                }

                // return 0;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
                //  return 1;
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }

            return fileNameList;
        }
Exemplo n.º 8
0
    public static int Main()
    {
        try
        {
            // Setup session options
            SessionOptions sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Scp,
                HostName = ConfigurationManager.AppSettings["hostName"],
                PortNumber = Convert.ToInt32(ConfigurationManager.AppSettings["portNumber"]),
                UserName = ConfigurationManager.AppSettings["userName"],
                Password = ConfigurationManager.AppSettings["storedProcedure"],
                SshHostKeyFingerprint = ConfigurationManager.AppSettings["SshHostKeyFingerprint"],
                SshPrivateKeyPath = ConfigurationManager.AppSettings["SshPrivateKeyPath"],
            };

            using (Session session = new Session())
            {
                string fileName = ConfigurationManager.AppSettings["fileName"];
                string localPath = ConfigurationManager.AppSettings["localPath"];
                string remotePath = ConfigurationManager.AppSettings["remotePath"];

                // Connect
                session.Open(sessionOptions);

                Console.WriteLine("## SCP Host Connection Success");

                string getFrom = localPath + fileName;
                string putToo = remotePath;

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

                TransferOperationResult transferResult;
                transferResult = session.PutFiles(getFrom, remotePath, false, transferOptions);

                transferResult.Check();

                foreach (TransferEventArgs transfer in transferResult.Transfers)
                {
                    Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
                    Console.WriteLine("Upload of {0} succeeded", transfer.Destination);
                    Console.WriteLine("Response: ", transfer.Error);
                }

                Console.WriteLine("## SCP Host Transfer Success");
                System.Environment.Exit(0);
            }

            return 1;
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: {0}", e);
            Console.Read();
            return 1;
        }
    }
Exemplo n.º 9
0
 /// <summary>
 /// FTP connection 
 /// </summary>
 /// <param name="hostname"></param>
 /// <param name="username"></param>
 /// <param name="password"></param>
 /// <param name="protocol"></param>
 public SFtpClient(string hostname, string username, string password, Protocol protocol)
 {
     _sessionOptions = new SessionOptions
     {
         Protocol = protocol,
         HostName = hostname,
         UserName = username,
         Password = password,
     };
 }
Exemplo n.º 10
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;

            }
        }
Exemplo n.º 11
0
 public ScpGateway(string userName, string password, string sshHostKeyFingerprint, string hostName)
 {
     sessionOptions = new SessionOptions
                     {
                         Protocol = Protocol.Scp,
                         HostName = hostName,
                         UserName = userName,
                         Password = password,
                         SshHostKeyFingerprint = sshHostKeyFingerprint
                     };
 }
Exemplo n.º 12
0
    // constructor
    public SadistaFunctions(string ipAddress, int port, string username,
                            string password, string ssh_host_key_fingerprint)
    {
        this.ipAddress = ipAddress;
        this.port      = port;
        this.username  = username;
        this.password  = password;
        this.ssh_host_key_fingerprint = ssh_host_key_fingerprint;

        this.session        = null;
        this.sessionOptions = null;
    }
Exemplo n.º 13
0
 public SFtpClient(string hostname, string username, string password, Protocol protocol, TimeSpan timeout, FtpMode ftpMode)
 {
     _sessionOptions = new SessionOptions
     {
         Protocol = protocol,
         HostName = hostname,
         UserName = username,
         Password = password,
         Timeout = timeout,
         FtpMode = ftpMode
     };
 }
Exemplo n.º 14
0
        private void button1_Click(object sender, EventArgs e)
        {
            WinSCP.SessionOptions wse = new WinSCP.SessionOptions()
            {
                FtpMode  = FtpMode.Active,
                UserName = "******",
                Password = "******",
                HostName = "ftp.teatrotse.com",
                Protocol = Protocol.Ftp
            };
            Session s = new Session();

            s.Open(wse);
            Directory.CreateDirectory("Project");
            s.GetFiles("/mobi", "Project", false);
        }
Exemplo n.º 15
0
        public static int Main(string[] args)
        {
            try
            {
                // Setup session options
                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    HostName = ConfigurationManager.AppSettings["HostName"].ToString(),
                    UserName = ConfigurationManager.AppSettings["UserName"].ToString(),
                    Password = ConfigurationManager.AppSettings["Password"].ToString(),
                    SshHostKeyFingerprint = ConfigurationManager.AppSettings["SshHostKeyFingerprint"].ToString()
                };
                string LocalPath = ConfigurationManager.AppSettings["LocalPath"].ToString();
                string RemotePath = ConfigurationManager.AppSettings["RemotePath"].ToString();
                using (Session session = new Session())
                {
                    // Connect
                    session.Open(sessionOptions);

                    // Upload files
                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Binary;

                    TransferOperationResult transferResult;
                    transferResult = session.PutFiles(LocalPath + "*", RemotePath, false, transferOptions);

                    // Throw on any error
                    transferResult.Check();

                    // Print results
                    foreach (TransferEventArgs transfer in transferResult.Transfers)
                    {
                        Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
                    }
                }

                return 0;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
                Console.ReadKey();
                return 1;
            }
        }
Exemplo n.º 16
0
 public void Load()
 {
     try
     {
         // Setup session options
         SessionOptions = new SessionOptions
         {
             Protocol = Protocol.Ftp,
             HostName = "ns513998.dediseedbox.com",
             UserName = "******",
             Password = "******",
         };
     }
     catch (Exception e)
     {
         LOG.ErrorFormat("Error: {0}", e);
     }
 }
Exemplo n.º 17
0
    private bool connect()
    {
        try
        {
            this.sessionOptions = new WinSCP.SessionOptions
            {
                Protocol              = WinSCP.Protocol.Sftp,
                PortNumber            = this.port,
                HostName              = this.ipAddress,
                UserName              = this.username,
                Password              = this.password,
                SshHostKeyFingerprint = this.ssh_host_key_fingerprint
            };

            this.session = new WinSCP.Session();
            this.session.Open(this.sessionOptions);
            return(true);
        }
        catch (Exception e) { Console.WriteLine(e.ToString()); return(false); }
    }
Exemplo n.º 18
0
        //TODO: 1. hide server and username info, how? let user type once?
        public SessionOptions GetSessionOptions()
        {
            Console.Write(TextCollection.Const.InfoEnterPassword);
            var password = Console.ReadLine();
            while (password == null || password.Trim() == "")
            {
                Console.Write(TextCollection.Const.InfoEnterPassword);
                password = Console.ReadLine();
            }

            var sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Sftp,
                HostName = Config.ConfigSftpAddress,
                UserName = Config.ConfigSftpUser,
                Password = password,
                PortNumber = 22, //TODO: make it configurable
                GiveUpSecurityAndAcceptAnySshHostKey = true
            };
            return sessionOptions;
        }
Exemplo n.º 19
0
 public WinSCPSession(string hostName, string userName, string password, string sshHostKeyFingerprint, string hostPortNo)
 {
     try
     {
         // Setup WinSCP session options
         winSCPSessionOptions = new SessionOptions
         {
             Protocol = Protocol.Sftp,
             HostName = hostName,
             UserName = userName,
             Password = password,
             // ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key.pub
             //SshHostKeyFingerprint = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
             SshHostKeyFingerprint = sshHostKeyFingerprint,
             PortNumber = Int32.Parse(hostPortNo)
         };
     }
     catch (Exception e)
     {
         throw new Exception(String.Format("Error: {0}", e.Message));
     }
 }
Exemplo n.º 20
0
        private bool FtpUploadAll(string localSaveFolder)
        {
            var resultFlag = true;

            if (!ConfigUtil.Ftp2Bi)
            {
                ALogger.LogInfo("FTP2BI Setting is false");
                return true;
            }

            try
            {
                var sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    GiveUpSecurityAndAcceptAnySshHostKey = true,
                    HostName = ConfigUtil.GetFtpHost(),
                    UserName = ConfigUtil.EDWFTPUser,
                    Password = ConfigUtil.EDWFTPPassword,
                    PortNumber = ConfigUtil.EDWFTPPort
                };
                using (var session = new Session
                {
                    ExecutablePath = Path.Combine("winscp", "WinSCP.exe"),
                    Timeout = TimeSpan.FromSeconds(30),
                })
                {
                    try
                    {
                        session.Open(sessionOptions);
                        var remoteFilePath = "";
                        var archiveFolder = Path.Combine(localSaveFolder, "Archive");
                        foreach (var fileInfo in GetFTPFileList(localSaveFolder))
                        {
                            try
                            {
                                remoteFilePath = Path.Combine(ConfigUtil.GetFtpPath(), fileInfo.Name).Replace('\\', '/');
                                var result = session.PutFiles(fileInfo.FullName, remoteFilePath);
                                if (result.IsSuccess)
                                {
                                    ALogger.LogInfo("successfully upload file, {0} to {1}", fileInfo.FullName, remoteFilePath);
                                    var newPath = Path.Combine(archiveFolder, fileInfo.Name);
                                    if (!Directory.Exists(archiveFolder)) Directory.CreateDirectory(archiveFolder);
                                    try
                                    {
                                        File.Move(fileInfo.FullName, newPath);
                                    }
                                    catch (Exception)
                                    {
                                    }

                                }
                                else
                                {
                                    ALogger.LogError("failed to upload file, {0} to {1}", fileInfo.FullName, remoteFilePath);
                                    foreach (var failed in result.Failures)
                                    {
                                        ALogger.LogError("\t\t###{0}###", failed);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                ALogger.LogError("failed to upload file, {0} with error {1}", remoteFilePath, ex.Message);
                                resultFlag = false;
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        ALogger.LogError("FtpUpload: exception {0}", ex.Message);
                        resultFlag = false;
                    }

                }
            }
            catch (Exception e)
            {
                ALogger.LogError("FtpUpload(): exception, {0}", e.Message);
                resultFlag = false;
            }
            return resultFlag;
        }
Exemplo n.º 21
0
 public FTP(string host, short port, byte protocol, string fingerprint,string username,string password)
 {
     this.host = host;
     this.port = port;
     this.protocol = protocol;
     this.fingerprint = fingerprint;
     this.username = username;
     this.password = password;
     sessionOptions = new SessionOptions();
     try
     {
         switch (protocol)
         {
             case FTP_PROTOCOL:
                 sessionOptions.Protocol = Protocol.Ftp;
                 break;
             case SCP_PROTOCOL:
                 {
                     sessionOptions.Protocol = Protocol.Scp;
                     if (fingerprint.Equals(""))
                         sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey = true;
                     else
                         sessionOptions.SshHostKeyFingerprint = fingerprint;
                     break;
                 }
             case SFTP_PROTOCOL:
                 {
                     sessionOptions.Protocol = Protocol.Sftp;
                     if (fingerprint.Equals(""))
                         sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey = true;
                     else
                         sessionOptions.SshHostKeyFingerprint = fingerprint;
                     break;
                 }
             case FTPS_PROTOCOL_EXP:
                 {
                     sessionOptions.Protocol = Protocol.Ftp;
                     sessionOptions.FtpSecure = FtpSecure.Explicit;
                     if (fingerprint.Equals(""))
                         sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate = true;
                     else
                         sessionOptions.TlsHostCertificateFingerprint = fingerprint;
                     break;
                 }
             case FTPS_PROTOCOL_IMP:
                 {
                     sessionOptions.Protocol = Protocol.Ftp;
                     sessionOptions.FtpSecure = FtpSecure.Implicit;
                     if (fingerprint.Equals(""))
                         sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate = true;
                     else
                         sessionOptions.TlsHostCertificateFingerprint = fingerprint;
                     break;
                 }
             case WEBDAV_PROTOCOL:
                 sessionOptions.Protocol = Protocol.Webdav;
                 break;
             case WEBDAVSECURE_PROTOCOL:
                 {
                     sessionOptions.Protocol = Protocol.Webdav;
                     sessionOptions.WebdavSecure = true;
                     if (fingerprint.Equals(""))
                         sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate = true;
                     else
                         sessionOptions.TlsHostCertificateFingerprint = fingerprint;
                     break;
                 }
         }
     }
     catch (Exception)
     {
         sessionOptions.Protocol = Protocol.Ftp;
     }
     sessionOptions.HostName = host;
     sessionOptions.PortNumber = port;
     sessionOptions.UserName = username;
     sessionOptions.Password = password;
 }
Exemplo n.º 22
0
        public static void synchro(string typeSynchro)
        {
            try
            {
                string repertoireLocal = FSFLauncherCore.cheminARMA3 + @"\@FSF\";
                string repertoireDistant="";

                fenetrePrincipale.textBox11.Text = "Synchronisation procedure " + typeSynchro + " en cours :" + Environment.NewLine;
                fenetrePrincipale.textBox11.Text += "────────────────────────────" + Environment.NewLine;
                fenetrePrincipale.textBox11.Text += Environment.NewLine + "IMPORTANT : " + Environment.NewLine + "Pour stopper la synchronisation en cours, il vous faut Arreter le processus WinSCP.exe en faisant appel à la combinaison de touche" + Environment.NewLine + " CTRL + MAJ + ESC (onglet processus)." + Environment.NewLine;
                // Setup session options
                SessionOptions sessionOptions = new SessionOptions { };
                switch (typeSynchro)
                {
                    case "beta":
                        SessionOptions sessionOptions1 = new SessionOptions
                        {
                            Protocol = Protocol.Ftp,
                            HostName = constCheminFTP,
                            UserName = constLoginFTP,
                            Password = constMdpFTP

                        };
                        repertoireDistant = "/@FSF/";
                        sessionOptions = sessionOptions1;

                        break;
                    case "officielle":
                        SessionOptions sessionOptions2 = new SessionOptions
                        {
                            Protocol = Protocol.Ftp,
                            HostName = constCheminFTP,
                            UserName = constLoginFTP,
                            Password = constMdpFTP

                        };
                        repertoireDistant = "/@FSF_OFFICIELLE/";
                        sessionOptions = sessionOptions2;
                        break;
                }

                using (Session session = new Session())
                {
                    switch (typeSynchro)
                    {
                        default:
                            Directory.CreateDirectory(repertoireLocal + "@TEMPLATE");
                            Directory.CreateDirectory(repertoireLocal + "@CLIENT");
                            Directory.CreateDirectory(repertoireLocal + "@TEST");
                            Directory.CreateDirectory(repertoireLocal + "@UNITS");
                            Directory.CreateDirectory(repertoireLocal + "@MATERIEL");
                            Directory.CreateDirectory(repertoireLocal + "@ISLANDS");
                            Directory.CreateDirectory(repertoireLocal + "@FRAMEWORK");
                            break;
                    }
                    // Will continuously report progress of synchronization
                    session.FileTransferred += FileTransferred;
                    session.FileTransferProgress += FileTransferProgress;

                    // session log
                    session.DebugLogPath = FSFLauncherCore.cheminARMA3 + @"\userconfig\FSF-LauncherA3\log.txt";
                    // Connect
                    session.Open(sessionOptions);
                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Binary;

                    SynchronizationResult synchronizationResult;

                        fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "****   SYNCHRO @TEMPLATE     ******" + Environment.NewLine);
                        synchronizationResult =
                            session.SynchronizeDirectories(
                                SynchronizationMode.Local,
                                repertoireLocal + "@TEMPLATE",
                                repertoireDistant + "@TEMPLATE",
                                true,
                                false,
                                SynchronizationCriteria.Size);
                        effaceProgressBar();

                        fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "****   SYNCHRO @FRAMEWORK     ******" + Environment.NewLine);
                        synchronizationResult =
                            session.SynchronizeDirectories(
                                SynchronizationMode.Local,
                                repertoireLocal + "@FRAMEWORK",
                                repertoireDistant + "@FRAMEWORK",
                                true,
                                false,
                                SynchronizationCriteria.Size);
                        effaceProgressBar();

                        fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "****   SYNCHRO @CLIENT     ******" + Environment.NewLine);
                        synchronizationResult =
                            session.SynchronizeDirectories(
                                SynchronizationMode.Local,
                                repertoireLocal + "@CLIENT",
                                repertoireDistant + "@CLIENT",
                                true,
                                false,
                                SynchronizationCriteria.Size);
                        effaceProgressBar();

                        fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "****   SYNCHRO @TEST     ******" + Environment.NewLine);
                        synchronizationResult =
                            session.SynchronizeDirectories(
                                SynchronizationMode.Local,
                                repertoireLocal + "@TEST",
                                repertoireDistant + "@TEST",
                                true,
                                false,
                                SynchronizationCriteria.Size);
                        effaceProgressBar();

                        fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "****   SYNCHRO @UNITS     ******" + Environment.NewLine);
                        synchronizationResult =
                            session.SynchronizeDirectories(
                                SynchronizationMode.Local,
                                repertoireLocal + "@UNITS",
                                repertoireDistant + "@UNITS",
                                true,
                                false,
                                SynchronizationCriteria.Size);
                        effaceProgressBar();

                        fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "****   SYNCHRO @MATERIEL     ******" + Environment.NewLine);
                        synchronizationResult =
                            session.SynchronizeDirectories(
                                SynchronizationMode.Local,
                                repertoireLocal + "@MATERIEL",
                                repertoireDistant + "@MATERIEL",
                                true,
                                false,
                                SynchronizationCriteria.Size);
                        effaceProgressBar();

                        fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "****   SYNCHRO @ISLANDS     ******" + Environment.NewLine);
                        synchronizationResult =
                            session.SynchronizeDirectories(
                                SynchronizationMode.Local,
                                repertoireLocal + "@ISLANDS",
                                repertoireDistant + "@ISLANDS",
                                true,
                                false,
                                SynchronizationCriteria.Size);
                        effaceProgressBar();

                        // Throw on any error
                        synchronizationResult.Check();
                        fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "->fichier " + repertoireLocal + "Organisation.txt mis a jour." + Environment.NewLine);

                        downloadnouvelleVersion("Organisation.txt", FSFLauncherCore.constCheminFTP + repertoireDistant, FSFLauncherCore.constLoginFTP, FSFLauncherCore.constMdpFTP, repertoireLocal);
                        downloadnouvelleVersion("version.xml", FSFLauncherCore.constCheminFTP + repertoireDistant, FSFLauncherCore.constLoginFTP, FSFLauncherCore.constMdpFTP, repertoireLocal);

                }
            }
            catch (Exception z)
            {
                fenetrePrincipale.textBox11.Text += "Error: " + z;
            }
            fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "_______________" + Environment.NewLine);
            fenetrePrincipale.textBox11.Text += "Fin de la synchro";
            Interface.AlerteVersionArma3();
            Interface.AlerteVersionSynchro();
        }
Exemplo n.º 23
0
        public DataTable Load()
        {
            StringBuilder requestUri = new StringBuilder();
            SessionOptions sessionOptions = new SessionOptions
            {
                HostName = Server,
                UserName = Username,
                Password = Password,
            };

            sessionOptions.Protocol = WinSCP.Protocol.Ftp;
            if (!String.IsNullOrEmpty(Path))
            {
                if (!Path.StartsWith("/") && !Path.StartsWith("."))
                {
                    requestUri.Append("/");
                }
                requestUri.Append(Path);
            }
            // sessionOptions.SshHostKeyFingerprint = SshHostKeyFingerprint;

            if (!String.IsNullOrEmpty(Path))
            {
                if (!Path.StartsWith("/") && !Path.StartsWith("."))
                {
                    requestUri.Append("/");
                }
                requestUri.Append(Path);
            }

            using (Session session = new Session())
            {
                if (!String.IsNullOrEmpty(WinscpPath))
                {
                    session.ExecutablePath = WinscpPath;
                }

                // prepare for output
                DataTable dataTable = new DataTable();
                dataTable.Columns.Add("Name", typeof(String));
                dataTable.Columns.Add("Size", typeof(long));
                dataTable.Columns.Add("LastModifiedDate", typeof(DateTime));
                dataTable.Columns.Add("FullPath", typeof(String));

                session.Open(sessionOptions);
                RemoteDirectoryInfo dirListing = session.ListDirectory(Path);
                Regex regex = null;
                if (!String.IsNullOrEmpty(FilterPattern))
                {
                    regex = new Regex(FilterPattern);
                }
                foreach (RemoteFileInfo fileInfo in dirListing.Files)
                {
                    if (regex == null || regex.IsMatch(fileInfo.Name))
                    {
                        dataTable.Rows.Add(new object[] { fileInfo.Name, fileInfo.Length, fileInfo.LastWriteTime, String.Format("{0}/{1}", requestUri.ToString(), fileInfo.Name) });
                    }
                }

                if (dataTable.Rows.Count > 0)
                {
                    if (!String.IsNullOrEmpty(SortOrder))
                    {
                        if (String.Compare(SortOrder, "asc", true) == 0)
                        {
                            DataView defaultView = dataTable.DefaultView;
                            defaultView.Sort = "LastModifiedDate ASC";
                            dataTable = defaultView.ToTable();
                        } if (String.Compare(SortOrder, "desc", true) == 0)
                        {
                            DataView defaultView = dataTable.DefaultView;
                            defaultView.Sort = "LastModifiedDate DESC";
                            dataTable = defaultView.ToTable();
                        }
                    }
                }
                return dataTable;
            }
        }
Exemplo n.º 24
0
        public void Open(SessionOptions sessionOptions)
        {
            using (Logger.CreateCallstackAndLock())
            {
                CheckNotDisposed();

                if (Opened)
                {
                    throw new InvalidOperationException("Session is already opened");
                }

                try
                {
                    SetupTempPath();

                    _process = new ExeSessionProcess(this);

                    _process.OutputDataReceived += ProcessOutputDataReceived;

                    _process.Start();

                    GotOutput();

                    // setup batch mode
                    WriteCommand("option batch on");
                    WriteCommand("option confirm off");

                    if (ReconnectTime != TimeSpan.MaxValue)
                    {
                        WriteCommand(string.Format(CultureInfo.InvariantCulture, "option reconnecttime {0}", (int)ReconnectTime.TotalSeconds));
                    }

                    WriteCommand("open " + SessionOptionsToOpenArguments(sessionOptions));

                    string logExplanation =
                        string.Format(CultureInfo.CurrentCulture,
                            "(response log file {0} was not created). This could indicate lack of write permissions to the log folder or problems starting WinSCP itself.",
                            XmlLogPath);

                    // Wait until the log file gets created or WinSCP terminates (in case of fatal error)
                    do
                    {
                        if (_process.HasExited && !File.Exists(XmlLogPath))
                        {
                            string[] output = new string[Output.Count];
                            Output.CopyTo(output, 0);
                            Logger.WriteCounters();
                            Logger.WriteProcesses();
                            _process.WriteStatus();
                            throw new SessionLocalException(this,
                                string.Format(CultureInfo.CurrentCulture,
                                    "WinSCP process terminated with exit code {0} and output \"{1}\", without responding {2}",
                                    _process.ExitCode, string.Join(Environment.NewLine, output), logExplanation));
                        }

                        Thread.Sleep(50);

                        CheckForTimeout(
                            string.Format(CultureInfo.CurrentCulture,
                                "WinSCP has not responded in time {0}",
                                logExplanation));

                    } while (!File.Exists(XmlLogPath));

                    _logReader = new SessionLogReader(this);

                    _reader = _logReader.WaitForNonEmptyElementAndCreateLogReader("session", LogReadFlags.ThrowFailures);

                    using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
                    {
                        ReadElement(groupReader, LogReadFlags.ThrowFailures);
                    }
                }
                catch(Exception e)
                {
                    Logger.WriteLine("Exception: {0}", e);
                    Cleanup();
                    throw;
                }
            }
        }
Exemplo n.º 25
0
        private string SessionOptionsToOpenSwitches(SessionOptions sessionOptions)
        {
            using (Logger.CreateCallstack())
            {
                List<string> switches = new List<string>();

                if (!string.IsNullOrEmpty(sessionOptions.SshHostKeyFingerprint) ||
                    sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey)
                {
                    if (!sessionOptions.IsSsh)
                    {
                        throw new ArgumentException("SessionOptions.SshHostKey or SessionOptions.GiveUpSecurityAndAcceptAnySshHostKey is set, but SessionOptions.Protocol is not Protocol.Sftp nor Protocol.Scp.");
                    }
                    string sshHostKeyFingerprint = sessionOptions.SshHostKeyFingerprint;
                    if (sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey)
                    {
                        Logger.WriteLine("WARNING! Giving up security and accepting any key as configured");
                        sshHostKeyFingerprint = AddStarToList(sshHostKeyFingerprint);
                    }
                    switches.Add(FormatSwitch("hostkey", sshHostKeyFingerprint));
                }
                else
                {
                    if (sessionOptions.IsSsh && DefaultConfiguration)
                    {
                        throw new ArgumentException("SessionOptions.Protocol is Protocol.Sftp or Protocol.Scp, but SessionOptions.HostKey is not set.");
                    }
                }

                if (!string.IsNullOrEmpty(sessionOptions.SshPrivateKeyPath))
                {
                    if (!sessionOptions.IsSsh)
                    {
                        throw new ArgumentException("SessionOptions.SshPrivateKey is set, but SessionOptions.Protocol is not Protocol.Sftp nor Protocol.Scp.");
                    }
                    switches.Add(FormatSwitch("privatekey", sessionOptions.SshPrivateKeyPath));
                }

                if (sessionOptions.FtpSecure != FtpSecure.None)
                {
                    if (sessionOptions.Protocol != Protocol.Ftp)
                    {
                        throw new ArgumentException("SessionOptions.FtpSecure is not FtpSecure.None, but SessionOptions.Protocol is not Protocol.Ftp.");
                    }

                    switch (sessionOptions.FtpSecure)
                    {
                        case FtpSecure.Implicit:
                            switches.Add(FormatSwitch("implicit"));
                            break;

                        case FtpSecure.ExplicitSsl:
                            switches.Add(FormatSwitch("explicitssl"));
                            break;

                        case FtpSecure.ExplicitTls:
                            switches.Add(FormatSwitch("explicittls"));
                            break;

                        default:
                            throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.FtpSecure));
                    }
                }

                if (!string.IsNullOrEmpty(sessionOptions.TlsHostCertificateFingerprint) ||
                    sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate)
                {
                    if (sessionOptions.FtpSecure == FtpSecure.None)
                    {
                        throw new ArgumentException("SessionOptions.TlsHostCertificateFingerprint or SessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate is set, but SessionOptions.FtpSecure is FtpSecure.None.");
                    }
                    string tlsHostCertificateFingerprint = sessionOptions.TlsHostCertificateFingerprint;
                    if (sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate)
                    {
                        Logger.WriteLine("WARNING! Giving up security and accepting any certificate as configured");
                        tlsHostCertificateFingerprint = AddStarToList(tlsHostCertificateFingerprint);
                    }
                    switches.Add(FormatSwitch("certificate", tlsHostCertificateFingerprint));
                }

                if (sessionOptions.Protocol == Protocol.Ftp)
                {
                    switches.Add(FormatSwitch("passive", (sessionOptions.FtpMode == FtpMode.Passive)));
                }

                switches.Add(FormatSwitch("timeout", (int)sessionOptions.Timeout.TotalSeconds));

                return string.Join(" ", switches.ToArray());
            }
        }
Exemplo n.º 26
0
        public void Open(SessionOptions sessionOptions)
        {
            using (Logger.CreateCallstackAndLock())
            {
                CheckNotDisposed();

                if (Opened)
                {
                    throw new InvalidOperationException("Session is already opened");
                }

                try
                {
                    SetupTempPath();

                    _process = new ExeSessionProcess(this);

                    _process.OutputDataReceived += ProcessOutputDataReceived;

                    _process.Start();

                    GotOutput();

                    // setup batch mode
                    WriteCommand("option batch on");
                    WriteCommand("option confirm off");

                    object reconnectTimeValue;
                    if (ReconnectTime != TimeSpan.MaxValue)
                    {
                        reconnectTimeValue = (int)ReconnectTime.TotalSeconds;
                    }
                    else
                    {
                        reconnectTimeValue = "off";
                    }
                    string reconnectTimeCommand =
                        string.Format(CultureInfo.InvariantCulture, "option reconnecttime {0}", reconnectTimeValue);
                    WriteCommand(reconnectTimeCommand);

                    string command;
                    string log;
                    SessionOptionsToOpenCommand(sessionOptions, out command, out log);
                    WriteCommand(command, log);

                    string logExplanation =
                        string.Format(CultureInfo.CurrentCulture,
                            "(response log file {0} was not created). This could indicate lack of write permissions to the log folder or problems starting WinSCP itself.",
                            XmlLogPath);

                    // Wait until the log file gets created or WinSCP terminates (in case of fatal error)
                    do
                    {
                        if (_process.HasExited && !File.Exists(XmlLogPath))
                        {
                            string[] output = new string[Output.Count];
                            Output.CopyTo(output, 0);
                            Logger.WriteCounters();
                            Logger.WriteProcesses();
                            _process.WriteStatus();
                            string exitCode = string.Format(CultureInfo.CurrentCulture, "{0}", _process.ExitCode);
                            if (_process.ExitCode < 0)
                            {
                                exitCode = string.Format(CultureInfo.CurrentCulture, "{0} ({1:X})", exitCode, _process.ExitCode);
                            }
                            throw new SessionLocalException(this,
                                string.Format(CultureInfo.CurrentCulture,
                                    "WinSCP process terminated with exit code {0} and output \"{1}\", without responding {2}",
                                    exitCode, string.Join(Environment.NewLine, output), logExplanation));
                        }

                        Thread.Sleep(50);

                        CheckForTimeout(
                            string.Format(CultureInfo.CurrentCulture,
                                "WinSCP has not responded in time {0}",
                                logExplanation));

                    } while (!File.Exists(XmlLogPath));

                    _logReader = new SessionLogReader(this);

                    _logReader.WaitForNonEmptyElement("session", LogReadFlags.ThrowFailures);

                    // special variant of ElementLogReader that throws when closing element (</session>) is encountered
                    _reader = new SessionElementLogReader(_logReader);

                    // Skip "open" command <group>
                    using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
                    {
                        ReadElement(groupReader, LogReadFlags.ThrowFailures);
                    }

                    WriteCommand("pwd");

                    using (ElementLogReader groupReader = _reader.WaitForGroupAndCreateLogReader())
                    using (ElementLogReader cwdReader = groupReader.WaitForNonEmptyElementAndCreateLogReader("cwd", LogReadFlags.ThrowFailures))
                    {
                        while (cwdReader.Read(0))
                        {
                            string value;
                            if (cwdReader.GetEmptyElementValue("cwd", out value))
                            {
                                _homePath = value;
                            }
                        }

                        groupReader.ReadToEnd(LogReadFlags.ThrowFailures);
                    }

                }
                catch(Exception e)
                {
                    Logger.WriteLine("Exception: {0}", e);
                    Cleanup();
                    throw;
                }
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Can only be called once
        /// </summary>
        public void Init()
        {
            if (_initialized) throw new ApplicationException("Transfer already initialized");

            _log.InfoFormat("Initializing transfer for job #{0} in path {1}", Job.Id, TransferSource);

            Options = new SessionOptions
            {
                Protocol = (Protocol)Enum.Parse(typeof(Protocol), Job.Protocol),
                HostName = Job.Host,
                UserName = Job.HostUsername,
                Password = Cryptor.Decrypt(Job.HostPassword),
                SshHostKeyFingerprint = Job.HostKeyFingerprint
            };

            Watcher = new FileSystemWatcher(TransferSource, "*");
            Watcher.IncludeSubdirectories = true;
            Watcher.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite;

            FileSystemEventHandler onChanged = (sender, args) =>
            {
                _log.DebugFormat("Something {0} at {1}", args.ChangeType, args.FullPath);
                Start();
            };
            RenamedEventHandler onRenamed = (sender, args) =>
            {
                _log.DebugFormat("Something was renamed at {0}", args.FullPath);
                Start();
            };
            ErrorEventHandler onError = (sender, args) =>
            {
                _log.Error("An error occured while transfering", args.GetException());
            };

            Watcher.Changed += onChanged;
            Watcher.Created += onChanged;
            Watcher.Deleted += onChanged;
            Watcher.Renamed += onRenamed;

            Watcher.Error += onError;

            Watcher.EnableRaisingEvents = true;

            _log.InfoFormat("Started listening in {0}", TransferSource);

            _initialized = true;

            if (Job.Running)
            {
                _log.InfoFormat("Job #{0} was previously marked as running. Probably service was abruptly closed. Starting the sync...", Job.Id);
                Start();
            }
        }
Exemplo n.º 28
0
        private void SessionOptionsToOpenCommand(SessionOptions sessionOptions, out string command, out string log)
        {
            using (Logger.CreateCallstack())
            {
                if (sessionOptions.WebdavSecure)
                {
                    if (sessionOptions.Protocol != Protocol.Webdav)
                    {
                        throw new ArgumentException("SessionOptions.WebdavSecure is set, but SessionOptions.Protocol is not Protocol.Webdav.");
                    }
                }

                string head;
                switch (sessionOptions.Protocol)
                {
                    case Protocol.Sftp:
                        head = "sftp://";
                        break;

                    case Protocol.Scp:
                        head = "scp://";
                        break;

                    case Protocol.Ftp:
                        head = "ftp://";
                        break;

                    case Protocol.Webdav:
                        if (!sessionOptions.WebdavSecure)
                        {
                            head = "http://";
                        }
                        else
                        {
                            head = "https://";
                        }
                        break;

                    default:
                        throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.Protocol));
                }

                bool hasUsername = !string.IsNullOrEmpty(sessionOptions.UserName);
                if (hasUsername)
                {
                    head += UriEscape(sessionOptions.UserName);
                }

                string url = head;
                string logUrl = head;

                if (sessionOptions.SecurePassword != null)
                {
                    if (!hasUsername)
                    {
                        throw new ArgumentException("SessionOptions.Password is set, but SessionOptions.UserName is not.");
                    }
                    url += ":" + UriEscape(sessionOptions.Password);
                    logUrl += ":***";
                }

                string tail = string.Empty;

                if (hasUsername)
                {
                    tail += "@";
                }

                if (string.IsNullOrEmpty(sessionOptions.HostName))
                {
                    throw new ArgumentException("SessionOptions.HostName is not set.");
                }

                // We should wrap IPv6 literals to square brackets, instead of URL-encoding them,
                // but it works anyway...
                tail += UriEscape(sessionOptions.HostName);

                if (sessionOptions.PortNumber != 0)
                {
                    tail += ":" + sessionOptions.PortNumber.ToString(CultureInfo.InvariantCulture);
                }

                if (!string.IsNullOrEmpty(sessionOptions.WebdavRoot))
                {
                    if (sessionOptions.Protocol != Protocol.Webdav)
                    {
                        throw new ArgumentException("SessionOptions.WebdavRoot is set, but SessionOptions.Protocol is not Protocol.Webdav.");
                    }

                    tail += sessionOptions.WebdavRoot;
                }

                url += tail;
                logUrl += tail;

                string arguments = SessionOptionsToOpenSwitches(sessionOptions);

                Tools.AddRawParameters(ref arguments, sessionOptions.RawSettings, "-rawsettings");

                if (!string.IsNullOrEmpty(arguments))
                {
                    arguments = " " + arguments;
                }

                // Switches should (and particularly the -rawsettings MUST) come after the URL
                command = "open \"" + Tools.ArgumentEscape(url) + "\"" + arguments;
                log = "open \"" + Tools.ArgumentEscape(logUrl) + "\"" + arguments;
            }
        }
Exemplo n.º 29
0
        public int removeFTPFiles(String HostName, String UserName, String Password, String remoteFilePath)
        {
            int result = 0;
            Session session = null;
            try
            {
                // Setup session options               
                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Ftp,
                    HostName = HostName,
                    UserName = UserName,
                    Password = Password,
                    //HostName =  "119.59.73.48",
                    //UserName = "******",
                    //Password =  "******",
                    //  SshHostKeyFingerprint = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
                };

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

                    // Remove files                 

                    RemovalOperationResult removalResult = null;
                    removalResult = session.RemoveFiles(remoteFilePath);

                    // Throw on any error
                    removalResult.Check();
                    // Print results
                    foreach (RemovalEventArgs removal in removalResult.Removals)
                    {
                        Console.WriteLine("Remove of {0} succeeded", removal.FileName);
                    }

                }

                result = 0;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
                result = 1;
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }
            return result;
        }
        public string RunFtp(string hostIP, string port, string user, string pass, string remoteDirectory, string remoteFilePattern, string localFileDirectory, string pharmacyName, string localFileName, int numHoursGoback, string ram, ref DataTable tblExcel)
        {
            string result = "";
            string localFileDirWithDateTime;
            string filePrefix = "SFTPDownload";

            try
            {
                localFileDirWithDateTime = Helper.CreateDirectory(localFileDirectory, DateTime.Now, pharmacyName);
            }
            catch (Exception ex)
            {
                LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix,
                                     pharmacyName, "", DateTime.Now, "Failed trying to create a local Dir in " + localFileDirectory + ". Ftp for this pharm stopped.", ref tblExcel);
                return("Failure trying to create a directory in " + localFileDirectory + " for pharmacy " + pharmacyName + ". error:" + ex.Message);
            }

            try
            {//------------------------------------------------------------------------------------------------
                WinSCP.SessionOptions sessionOptions = new WinSCP.SessionOptions
                {
                    Protocol   = WinSCP.Protocol.Sftp,
                    HostName   = hostIP,
                    UserName   = user,
                    Password   = pass,
                    PortNumber = Convert.ToInt32(port)

                                 /* use these to connect to FTP, and leave out the fingerPrint.:
                                  *
                                  * _with1.Protocol = Protocol.Ftp;
                                  * _with1.FtpSecure = FtpSecure.Explicit;
                                  *
                                  */
                };
                string fingerprint = null;
                using (WinSCP.Session session = new WinSCP.Session())
                {
                    fingerprint = session.ScanFingerprint(sessionOptions);
                }
                if (fingerprint == null)
                {
                    throw new Exception("Couldnt determine Host Fingerprint");
                }
                else
                {
                    sessionOptions.SshHostKeyFingerprint = fingerprint;
                }


                using (WinSCP.Session session = new WinSCP.Session())
                {
                    sessionOptions.Timeout = TimeSpan.FromMinutes(6);  // 6 min timeout
                    //session.ExecutablePath = @"C:\Software\v11\winscp.exe";
                    session.Open(sessionOptions);

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

                    WinSCP.TransferOperationResult transferResult = default(WinSCP.TransferOperationResult);
                    transferResult = session.GetFiles(remoteDirectory + remoteFilePattern, localFileDirectory, false, transferOptions);

                    transferResult.Check();
                    //THrows the first error if not successful
                    foreach (WinSCP.TransferEventArgs transfer in transferResult.Transfers)
                    {
                        string downfileName = transfer.FileName;

                        DateTime remoteWriteTime =
                            session.GetFileInfo(downfileName).LastWriteTime;               //get the DateTime of the file.

                        if (remoteWriteTime >= DateTime.Now.AddHours(numHoursGoback * -1)) // ignore if older that the num Hours Goback spec by user
                        {
                            string localFilename = localFileDirWithDateTime + downfileName;
                            //try
                            //{

                            result += downfileName + "\r\n";
                            LogObj.WriteExcelrow("Success", enMsgType.enMsgType_Info, filePrefix,
                                                 pharmacyName, downfileName, remoteWriteTime, "", ref tblExcel);
                            // }
                            //catch (Exception ex)
                            //{
                            //    LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix,
                            //                                    pharmacyName, downfileName, remoteWriteTime, ex.Message, ref tblExcel);

                            //    return "Failure occurred trying to Download SecureFtpWinSCP file " + downfileName + " for HostIp " + hostIP + " directory " + remoteDirectory + " files " + remoteFilePattern + " error:" + ex.Message + "\r\n";
                            //}
                        }
                        else
                        {
                            result += "Should be Ignored" + downfileName + " but still nowloaded." + "\r\n";

                            LogObj.WriteExcelrow("Success", enMsgType.enMsgType_Info, filePrefix,
                                                 pharmacyName, downfileName, remoteWriteTime, " but still nowloaded.", ref tblExcel);

                            //LogObj.WriteExcelrow("Ignored", enMsgType.enMsgType_Info, filePrefix,
                            //                                    pharmacyName, downfileName, file.Attributes.LastWriteTime, "its too old", ref tblExcel);
                        }
                    }
                }
                //-------------------------------------------------------------------------------------------------------------------


                return("Successfully downloaded to local dir " + localFileDirectory + " the following files: " + result);
            }
            catch (WinSCP.SessionRemoteException ex)
            {
                LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix, pharmacyName, "", DateTime.Now, "Check the remote settings. " + ex.Message, ref tblExcel);
                return("Failure occurred trying to connect to download SFtp for HostIp " + hostIP + " directory " + remoteDirectory + remoteFilePattern + " error:" + ex.Message + "\r\n");
            }

            catch (System.TimeoutException ex)
            {
                LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix, pharmacyName, "", DateTime.Now, ex.Message, ref tblExcel);
                return("Failure occurred trying to connect to download SFtp for HostIp " + hostIP + " directory " + remoteDirectory + remoteFilePattern + " error:" + ex.Message + "\r\n");
            }


            catch (Exception ex)
            {
                LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix, pharmacyName, "", DateTime.Now, ex.Message, ref tblExcel);

                return("Failure occurred trying to connect to download SFtp for HostIp " + hostIP + " directory " + remoteDirectory + remoteFilePattern + " error:" + ex.Message + "\r\n");
            }
        }
        private static void UploadFile(string fileToUpload)
        {
            SessionOptions sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Ftp,
                HostName = CloudshareManager.cloudFoldersInfo.data.host,
                UserName = CloudshareManager.cloudFoldersInfo.data.user,
                Password = CloudshareManager.cloudFoldersInfo.data.password
            };
            using (Session session = new Session())
            {
                // Connect
                session.DisableVersionCheck = true;
                session.Open(sessionOptions);

                // Upload files
                TransferOptions transferOptions = new TransferOptions();
                transferOptions.TransferMode = TransferMode.Binary;

                var a = session.ListDirectory("/");
                CloudshareManager.remoteUserFolderName = a.Files[2].Name;

                TransferOperationResult transferResult;
                transferResult = session.PutFiles(fileToUpload, "/" + a.Files[2].Name + "/*.*", false, transferOptions);

                // Throw on any error
                transferResult.Check();
            }
        }
Exemplo n.º 32
0
        private int Upload(String HostName, String UserName, String Password, String remotePath, String localFilePath)
        {
            int result = 0;
            Session session = null;
            try
            {
                // Setup session options               
                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Ftp,
                    HostName = HostName,
                    UserName = UserName,
                    Password = Password,
                    //HostName =  "119.59.73.48",
                    //UserName = "******",
                    //Password =  "******",
                    //  SshHostKeyFingerprint = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
                };

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



                    // upload files
                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Ascii;


                    TransferOperationResult transferResult = null;

                    transferResult = session.PutFiles(localFilePath, remotePath, false, transferOptions);


                    // Throw on any error
                    transferResult.Check();
                    // Print results
                    foreach (TransferEventArgs transfer in transferResult.Transfers)
                    {
                        Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
                    }

                }

                result = 0;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
                result = 1;
            }
            finally
            {
                if (session != null)
                {
                    session.Dispose();
                }
            }
            return result;
        }
Exemplo n.º 33
0
        private string SessionOptionsToOpenArguments(SessionOptions sessionOptions)
        {
            using (Logger.CreateCallstack())
            {
                string url;
                switch (sessionOptions.Protocol)
                {
                    case Protocol.Sftp:
                        url = "sftp://";
                        break;

                    case Protocol.Scp:
                        url = "scp://";
                        break;

                    case Protocol.Ftp:
                        url = "ftp://";
                        break;

                    default:
                        throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not supported", sessionOptions.Protocol));
                }

                bool hasUsername = !string.IsNullOrEmpty(sessionOptions.UserName);
                if (hasUsername)
                {
                    url += UriEscape(sessionOptions.UserName);
                }

                if (!string.IsNullOrEmpty(sessionOptions.Password))
                {
                    if (!hasUsername)
                    {
                        throw new ArgumentException("SessionOptions.Password is set, but SessionOptions.UserName is not.");
                    }
                    url += ":" + UriEscape(sessionOptions.Password);
                }

                if (hasUsername)
                {
                    url += "@";
                }

                if (string.IsNullOrEmpty(sessionOptions.HostName))
                {
                    throw new ArgumentException("SessionOptions.HostName is not set.");
                }

                url += UriEscape(sessionOptions.HostName);

                if (sessionOptions.PortNumber != 0)
                {
                    url += ":" + sessionOptions.PortNumber.ToString(CultureInfo.InvariantCulture);
                }

                string arguments = SessionOptionsToOpenSwitches(sessionOptions);

                arguments += (!string.IsNullOrEmpty(arguments) ? " " : "") + "\"" + ArgumentEscape(url) + "\"";

                if (sessionOptions.RawSettings.Count > 0)
                {
                    arguments += " -rawsettings";
                    foreach (KeyValuePair<string, string> rawSetting in sessionOptions.RawSettings)
                    {
                        arguments += string.Format(CultureInfo.InvariantCulture, " {0}=\"{1}\"", rawSetting.Key, ArgumentEscape(rawSetting.Value));
                    }
                }

                return arguments;
            }
        }
Exemplo n.º 34
-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();
                }
            }

        }