Example #1
11
        public static void CopyFileFromRemoteToLocal(string host, string user, string password, string localPath, string remotePath)
        {
            using (SftpClient client = new SftpClient(host, user, password))
            {
                client.KeepAliveInterval = TimeSpan.FromSeconds(60);
                client.ConnectionInfo.Timeout = TimeSpan.FromMinutes(180);
                client.OperationTimeout = TimeSpan.FromMinutes(180);
                client.Connect();
                bool connected = client.IsConnected;
                // RunCommand(host, user, password, "sudo chmod 777 -R " + remotePath);
                var file = File.OpenWrite(localPath);
                client.DownloadFile(remotePath, file);

                file.Close();
                client.Disconnect();
            }
        }
 public bool UploadFile(string filePath)
 {
     ConnectionInfo connectionInfo = new PasswordConnectionInfo(_address, ConstFields.SFTP_PORT, _username, _password);
     try
     {
         using (var sftp = new SftpClient(connectionInfo))
         {
             sftp.Connect();
             using (var file = File.OpenRead(filePath))
             {
                 if (!sftp.Exists(ConstFields.TEMP_PRINT_DIRECTORY))
                 {
                     sftp.CreateDirectory(ConstFields.TEMP_PRINT_DIRECTORY);
                 }
                 sftp.ChangeDirectory(ConstFields.TEMP_PRINT_DIRECTORY);
                 string filename = Path.GetFileName(filePath);
                 sftp.UploadFile(file, filename);
             }
             sftp.Disconnect();
         }
     }
     catch (Renci.SshNet.Common.SshConnectionException)
     {
         Console.WriteLine("Cannot connect to the server.");
         return false;
     }
     catch (System.Net.Sockets.SocketException)
     {
         Console.WriteLine("Unable to establish the socket.");
         return false;
     }
     catch (Renci.SshNet.Common.SshAuthenticationException)
     {
         Console.WriteLine("Authentication of SSH session failed.");
         return false;
     }
     return true;
 }
        private void PollHandler()
        {
            var exchange = new Exchange(_processor.Route);
            var ipaddress = _processor.UriInformation.GetUriProperty("host");
            var username = _processor.UriInformation.GetUriProperty("username");
            var password = _processor.UriInformation.GetUriProperty("password");
            var destination = _processor.UriInformation.GetUriProperty("destination");
            var port = _processor.UriInformation.GetUriProperty<int>("port");
            var interval = _processor.UriInformation.GetUriProperty<int>("interval", 100);
            var secure = _processor.UriInformation.GetUriProperty<bool>("secure");

            do
            {
                Thread.Sleep(interval);
                try
                {
                    if (secure)
                    {
                        SftpClient sftp = null;
                        sftp = new SftpClient(ipaddress, port, username, password);
                        sftp.Connect();

                        foreach (var ftpfile in sftp.ListDirectory("."))
                        {
                            var destinationFile = Path.Combine(destination, ftpfile.Name);
                            using (var fs = new FileStream(destinationFile, FileMode.Create))
                            {
                                var data = sftp.ReadAllText(ftpfile.FullName);
                                exchange.InMessage.Body = data;

                                if (!string.IsNullOrEmpty(data))
                                {
                                    sftp.DownloadFile(ftpfile.FullName, fs);
                                }
                            }
                        }
                    }
                    else
                    {
                        ReadFtp(exchange);
                    }
                }
                catch (Exception exception)
                {
                    var msg = exception.Message;
                }
            } while (true);
        }
 private void sendSFTP(string filePath, string fileName)
 {
     SftpClient sftp = new SftpClient("194.2.93.194", "userece", "AdminPOCNUC01");
     sftp.Connect();
     using (FileStream filestream = File.OpenRead(filePath))
     {
         sftp.UploadFile(filestream, "/"+fileName, null);
         sftp.Disconnect();
     }
 }
		public bool TryGetFileFromFtp(string fileName, DateTime lastUpdated)
		{
			if (!DirectoryUtil.VerifyDirectory(fileName))
			{
				return false;
			}

			var fileToDownload =  fileName;
			Log.Debug(string.Format("Attempting to download file " + fileToDownload));
			
			try
			{
				Log.Debug("Opening FTP Connection to " + Hostname);
				using (var client = new SftpClient(Hostname, Username, Password))
				{
					client.Connect();
					Log.Debug(string.Format("Connection to {0} opened.", Hostname));
					var fileUpdated = client.GetLastWriteTime(fileName);
					Log.Debug(string.Format("File {0} was last modified on {1}.", fileName, DateUtil.ToIsoDate(fileUpdated)));

					if (fileUpdated <= lastUpdated)
					{
						Log.Info(string.Format("Did not download file {0}, it was last modified {1} and we last processed it on {2}.",
																		fileName, DateUtil.ToIsoDate(fileUpdated), DateUtil.ToIsoDate(lastUpdated)), this);
						return false;
					}

					var outputPath = string.Format("{0}\\{1}", UserCsvImportSettings.CsvFolderPath, fileName);
					Log.Debug(string.Format("Downloading file {0} and saving to path {1}.", fileName, outputPath));
					using (var fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
					{
						client.DownloadFile(fileName, fileStream);
						Log.Debug("File successfully written to " + fileStream.Name);
					}
					Log.Debug("File Download complete.");
					Log.Debug("Updating timestamp.");
					File.SetLastWriteTime(outputPath, fileUpdated);
					Log.Debug("File timestamp set to " + fileUpdated.ToString());
				}
			}
			catch (Exception e)
			{
				Log.Error("File did not download successfully.", this);
				Log.Error(string.Format("Could not download file {0} from {1} using user {2}.", fileToDownload, Hostname, Username), e,
					this);
				return false;
				 
			}

			return true;
		}
Example #6
1
        public static IEnumerable<SftpFile> GetList(string host, string folder, string userName, string password)
        {

            using (var sftp = new SftpClient(host, userName, password))
            {
                sftp.ErrorOccurred += Sftp_ErrorOccurred;
                sftp.Connect();

                var toReturn = sftp.ListDirectory(folder).ToList();

                sftp.Disconnect();

                return toReturn;
            }
        }
Example #7
1
        protected override void ProcessRecord()
        {
            if (keyfile.Equals(""))
            {
                //###########################################
                //### Connect using Username and Password ###
                //###########################################
                ConnectionInfo connectInfo;
                var KIconnectInfo = new KeyboardInteractiveAuthenticationMethod(credential.GetNetworkCredential().UserName);
                foreach (var computer in computername)
                {
                    if (proxyserver != "")
                    {
                        // Set the proper proxy type
                        var ptype = Renci.SshNet.ProxyTypes.Http;
                        WriteVerbose("A Proxy Server has been specified");
                        switch (proxytype)
                        {
                            case "HTTP":
                                ptype = Renci.SshNet.ProxyTypes.Http;
                                break;
                            case "Socks4":
                                ptype = Renci.SshNet.ProxyTypes.Socks4;
                                break;
                            case "Socks5":
                                ptype = Renci.SshNet.ProxyTypes.Socks5;
                                break;
                        }

                        var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password);

                        WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName);
                        connectInfo = new ConnectionInfo(computer,
                            port,
                            credential.GetNetworkCredential().UserName,
                            ptype,
                            proxyserver,
                            proxyport,
                            proxycredential.GetNetworkCredential().UserName,
                            proxycredential.GetNetworkCredential().Password,
                            KIconnectInfo,
                            PassconnectInfo);

                    }
                    else
                    {
                        WriteVerbose("Using Username and Password authentication for connection.");
                        // Connection info for Keyboard Interactive

                        var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password);

                        WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName);
                        connectInfo = new Renci.SshNet.ConnectionInfo(computer, credential.GetNetworkCredential().UserName,
                                    PassconnectInfo,
                                    KIconnectInfo);
                    }

                    // Event Handler for interactive Authentication
                    KIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                                prompt.Response = credential.GetNetworkCredential().Password;
                        }
                    };

                    try
                    {
                        //Ceate instance of SFTP Client with connection info
                        var Client = new SftpClient(connectInfo);

                        // Handle host key
                        Client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                        {
                            var sb = new StringBuilder();
                            foreach (var b in e.FingerPrint)
                            {
                                sb.AppendFormat("{0:x}:", b);
                            }
                            string FingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);
                           // this.Host.UI.WriteVerboseLine("Key algorithm of " + Client.ConnectionInfo.CurrentHostKeyAlgorithm);
                            //this.Host.UI.WriteVerboseLine("Key exchange alhorithm " + Client.ConnectionInfo.CurrentKeyExchangeAlgorithm);
                            //this.Host.UI.WriteVerboseLine("Host key fingerprint: " + FingerPrint);
                            if (SSHHostKeys.ContainsKey(computer))
                            {
                                if (SSHHostKeys[computer] == FingerPrint)
                                {
                                    //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer);
                                }
                            }
                            else
                            {
                                int choice;
                                if (acceptkey)
                                {
                                    choice = 0;
                                }
                                else
                                {
                                    Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>();
                                    choices.Add(new ChoiceDescription("Y"));
                                    choices.Add(new ChoiceDescription("N"));

                                    choice = this.Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + FingerPrint, choices, 1);
                                }
                                if (choice == 0)
                                {
                                    var keymng = new TrustedKeyMng();
                                    //this.Host.UI.WriteVerboseLine("Saving fingerprint " + FingerPrint + " for host " + computer);
                                    keymng.SetKey(computer, FingerPrint);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    e.CanTrust = false;
                                }
                            }
                        };
                        // Set the connection timeout
                        Client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(connectiontimeout);

                        // Set Keepalive for connections
                        Client.KeepAliveInterval = TimeSpan.FromSeconds(keepaliveinterval);

                        // Connect to  host using Connection info
                        Client.Connect();
                        WriteObject(SSHModHelper.AddToSFTPSessionCollection(Client, this.SessionState), true);

                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            else
            {
                //##########################
                //### Connect using Keys ###
                //##########################

                WriteVerbose("Using SSH Key authentication for connection.");
                var fullPath = Path.GetFullPath(keyfile);
                if (File.Exists(fullPath))
                {
                    foreach (var computer in computername)
                    {
                        PrivateKeyConnectionInfo connectionInfo;
                        if (proxyserver != "")
                        {
                            // Set the proper proxy type
                            var ptype = Renci.SshNet.ProxyTypes.Http;
                            WriteVerbose("A Proxy Server has been specified");
                            switch (proxytype)
                            {
                                case "HTTP":
                                    ptype = Renci.SshNet.ProxyTypes.Http;
                                    break;
                                case "Socks4":
                                    ptype = Renci.SshNet.ProxyTypes.Socks4;
                                    break;
                                case "Socks5":
                                    ptype = Renci.SshNet.ProxyTypes.Socks5;
                                    break;
                            }

                            if (credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), credential.GetNetworkCredential().Password);

                                if (proxycredential.UserName == "")
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        credential.GetNetworkCredential().UserName,
                                        ptype,
                                        proxyserver,
                                        proxyport,
                                        sshkey);
                                }
                                else
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        credential.GetNetworkCredential().UserName,
                                        ptype,
                                        proxyserver,
                                        proxyport,
                                        proxycredential.GetNetworkCredential().UserName,
                                        proxycredential.GetNetworkCredential().Password,
                                        sshkey);
                                }
                            }
                        }
                        else
                        {
                            WriteVerbose("Using SSH Key authentication for connection.");
                            if (credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), credential.GetNetworkCredential().Password);
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }

                        }
                        try
                        {
                            //Ceate instance of SSH Client with connection info
                            var Client = new SftpClient(connectionInfo);

                            // Handle host key
                            Client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                            {
                                var sb = new StringBuilder();
                                foreach (var b in e.FingerPrint)
                                {
                                    sb.AppendFormat("{0:x}:", b);
                                }
                                string FingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);
                                //this.Host.UI.WriteVerboseLine("Key algorithm of " + Client.ConnectionInfo.CurrentHostKeyAlgorithm);
                                //this.Host.UI.WriteVerboseLine("Key exchange alhorithm " + Client.ConnectionInfo.CurrentKeyExchangeAlgorithm);
                                //this.Host.UI.WriteVerboseLine("Host key fingerprint: " + FingerPrint);
                                if (SSHHostKeys.ContainsKey(computer))
                                {
                                    if (SSHHostKeys[computer] == FingerPrint)
                                    {
                                        //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer);
                                        e.CanTrust = true;
                                    }
                                    else
                                    {
                                        throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer);
                                    }
                                }
                                else
                                {
                                    int choice;
                                    if (acceptkey)
                                    {
                                        choice = 0;
                                    }
                                    else
                                    {
                                        Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>();
                                        choices.Add(new ChoiceDescription("Y"));
                                        choices.Add(new ChoiceDescription("N"));

                                        choice = this.Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + FingerPrint, choices, 1);
                                    }
                                    if (choice == 0)
                                    {
                                        var keymng = new TrustedKeyMng();
                                        //this.Host.UI.WriteVerboseLine("Saving fingerprint " + FingerPrint + " for host " + computer);
                                        keymng.SetKey(computer, FingerPrint);
                                        e.CanTrust = true;
                                    }
                                    else
                                    {
                                        e.CanTrust = false;
                                    }
                                }
                            };
                            // Set the connection timeout
                            Client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(connectiontimeout);

                            // Connect to  host using Connection info
                            Client.Connect();
                            WriteObject(SSHModHelper.AddToSFTPSessionCollection(Client, this.SessionState), true);

                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    } // for each computer
                } // file exists
                else
                {
                    throw new System.IO.FileNotFoundException("Key file " + fullPath + " was not found.");
                }

            } // End process record
        }
Example #8
0
 private async Task _ensureConnected(CancellationToken ctk)
 {
     if (!_client.IsConnected)
     {
         await Task.Run(() => _client.Connect(), ctk);
     }
 }
        private async Task DownloadFilesWithSftpAsync(Endpoint endpoint, string decodedPass)
        {
            var client = new SftpClient(endpoint.Url, endpoint.Username, decodedPass);
            client.Connect();

            SftpFile[] filesOnServer =
                (await this.ListRemoteDirectoriesAsync(client, endpoint.RemoteDirectory)).Where(
                    x => !this.excludedListOfFiles.Any(y => x.Name.Equals(y))).ToArray();

            var primaryLocalDirectory = endpoint.Destinations.FirstOrDefault(x => x.Type == DestinationType.Primary);
            var archiveLocalDirectory = endpoint.Destinations.FirstOrDefault(x => x.Type == DestinationType.Archive);

            var primaryAndArchiveAreNotExisting = primaryLocalDirectory == null || archiveLocalDirectory == null;
            if (primaryAndArchiveAreNotExisting)
            {
                progress.ReportLine("You haven't provided the primary or archive folder");
                return;
            }

            var filteredLocalFiles = FilterLocalFiles(filesOnServer, GetFilesListInFolder(primaryLocalDirectory.Name));

            await this.GetFilesAsync(filteredLocalFiles, endpoint.RemoteDirectory, primaryLocalDirectory.Name, client).ContinueWith(x => client.Disconnect());

            this.ArchiveFiles(GetFilesListInFolder(primaryLocalDirectory.Name), primaryLocalDirectory, archiveLocalDirectory);
        }
Example #10
0
        /// <summary>
        /// List all entries of a folder.
        /// </summary>
        /// <param name="path">The folder path to list</param>
        /// <param name="ctk"></param>
        /// <returns>
        /// All entries found (files, folders, symlinks)
        /// </returns>
        public async Task <IEnumerable <FtpEntry> > ListDirectoryAsync(string path = "./", CancellationToken ctk = default(CancellationToken))
        {
            await Task.Yield();

            var ftpPath = path.GetFtpPath();

            _logger.Trace("Listing directory: {0} -> {1}", path, ftpPath);

            using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5)))
                using (var linked = CancellationTokenSource.CreateLinkedTokenSource(ctk, cts.Token))
                {
                    var result = new List <FtpEntry>();

                    using (var sFtpClient = new Renci.SshNet.SftpClient(new ConnectionInfo(Host, Port, Credentials.UserName, new PasswordAuthenticationMethod(Credentials.UserName, Credentials.Password))))
                    {
                        sFtpClient.Connect();
                        var rawLs = await sFtpClient.ListDirectoryAsync(path);

                        _logger.Trace("Starting parsing response for path {0}", path);
                        result = _parse(rawLs, linked.Token);
                    }

                    linked.Token.ThrowIfCancellationRequested();

                    return(result);
                }
        }
Example #11
0
 public SshFactory(String host, String username, String password)
 {
     _connection = new SshClient(host, username, password);
     _connection.Connect();
     _sftp = new SftpClient(_connection.ConnectionInfo);
     _sftp.Connect();
 }
        private void checkFingerpint(ConnectionInfo con, string knownHostsPath)
        {
            _knownHosts = new KnownHostStore(knownHostsPath);
            using (Renci.SshNet.SftpClient client1 = new Renci.SshNet.SftpClient(con))
            {
                client1.HostKeyReceived += (sender, eventArgs) =>
                {
                    eventArgs.CanTrust = CanTrustHost(client1.ConnectionInfo.Host, eventArgs);
                };

                try
                {
                    client1.Connect();
                    this.fingerprint = true;
                }
                catch (Exception)
                {
                    this.error.setError("SF012", "unknown host");
                    this.channel     = null;
                    this.fingerprint = false;
                }
                finally
                {
                    client1.Disconnect();
                }
            }
        }
Example #13
0
        public void beginCracking()
        {
            log("beginning cracking process..");
            var connectionInfo = new PasswordConnectionInfo (xml.Config.host, xml.Config.port, "root", xml.Config.Password);
            using (var sftp = new SftpClient(connectionInfo))
            {
                using (var ssh = new SshClient(connectionInfo))
                {
                    PercentStatus("Establishing SSH connection", 5);
                    ssh.Connect();
                    PercentStatus("Establishing SFTP connection", 10);
                    sftp.Connect();

                    log("Cracking " + ipaInfo.AppName);
                    PercentStatus("Preparing IPA", 25);
                    String ipalocation = AppHelper.extractIPA(ipaInfo);
                    using (var file = File.OpenRead(ipalocation))
                    {
                        log("Uploading IPA to device..");
                        PercentStatus("Uploading IPA", 40);
                        sftp.UploadFile(file, "Upload.ipa");

                    }
                    log("Cracking! (This might take a while)");
                    PercentStatus("Cracking", 50);
                    String binaryLocation = ipaInfo.BinaryLocation.Replace("Payload/", "");
                    String TempDownloadBinary = Path.Combine(AppHelper.GetTemporaryDirectory(), "crackedBinary");
                    var crack = ssh.RunCommand("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary");
                    log("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary");
                    log("cracking output: " + crack.Result);

                    using (var file = File.OpenWrite(TempDownloadBinary))
                    {
                        log("Downloading cracked binary..");
                        PercentStatus("Downloading cracked binary", 80);
                        try
                        {
                            sftp.DownloadFile("/tmp/crackedBinary", file);
                        }
                        catch (SftpPathNotFoundException e)
                        {
                            log("Could not find file, help!!!!!");
                            return;
                        }
                    }

                    PercentStatus("Repacking IPA", 90);
                    String repack = AppHelper.repack(ipaInfo, TempDownloadBinary);
                    PercentStatus("Done!", 100);

                    log("Cracking completed, file at " + repack);
                }
            }
        }
Example #14
0
        public SFTP(Uri targetServer,string password)
        {
            _sftp = new SftpClient(targetServer.Host,targetServer.Port,
                targetServer.UserInfo,
                password);

            log.InfoFormat("SFTP - Connecting to {0}", targetServer);
            _sftp.Connect();
            log.InfoFormat("SFTP - Changing dir to {0}", targetServer.LocalPath);
            _sftp.ChangeDirectory(targetServer.LocalPath);
        }
Example #15
0
        public static void UploadFile(string localFileToUpload, string host, string targetFile, string userName, string password)
        {
            using (var sftp = new SftpClient(host, userName, password))
            {
                sftp.OperationTimeout = new TimeSpan(0, 0, seconds: 40);
                sftp.Connect();
                UploadFileWithOpenConnection(localFileToUpload, targetFile, sftp);

                sftp.Disconnect();
            }
        }
Example #16
0
        public static void DeleteRemoteDirectory(string host, string directory, string username, string password)
        {
            using (var sftp = new SftpClient(host, username, password))
            {
                sftp.Connect();

                sftp.DeleteDirectory(directory);

                sftp.Disconnect();

            }
        }
Example #17
0
        public void Connect()
        {
            if(Protocol == SSHTransferProtocol.SCP)
            {
                ScpClt = new ScpClient(Host, Port, User, Password);
                ScpClt.Connect();
            }

            if (Protocol == SSHTransferProtocol.SFTP)
            {
                SftpClt = new SftpClient(Host, Port, User, Password);
                SftpClt.Connect();
            }
        }
Example #18
0
 public async Task UploadFileAsync(string path, byte[] content, CancellationToken ctk = default)
 {
     using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5)))
         using (var linked = CancellationTokenSource.CreateLinkedTokenSource(ctk, cts.Token))
         {
             using (var sFtpClient = new Renci.SshNet.SftpClient(new ConnectionInfo(Host, Port, Credentials.UserName, new PasswordAuthenticationMethod(Credentials.UserName, Credentials.Password))))
             {
                 sFtpClient.Connect();
                 using (var ms = new MemoryStream(content))
                 {
                     await sFtpClient.UploadAsync(ms, path);
                 }
             }
         }
 }
Example #19
0
 public static void CopyFileFromLocalToRemote(string host, string user, string password, string localPath, string remotePath)
 {
     using (SftpClient client = new SftpClient(host, user, password))
     {
         client.KeepAliveInterval = TimeSpan.FromSeconds(60);
         client.ConnectionInfo.Timeout = TimeSpan.FromMinutes(180);
         client.OperationTimeout = TimeSpan.FromMinutes(180);
         client.Connect();
         bool connected = client.IsConnected;
         // RunCommand(host, user, password, "sudo chmod 777 -R " + remotePath);
         FileInfo fi = new FileInfo(localPath);
         client.UploadFile(fi.OpenRead(), remotePath + fi.Name, true);
         client.Disconnect();
     }
 }
Example #20
0
        /// <summary>
        /// authenticates and returns an sftp client connection
        /// via ssh.NET
        /// </summary>
        /// <returns>
        /// the sftp client
        /// </returns>
        private Renci.SshNet.SftpClient GetSftpClient()
        {
            if (_client == null || !_client.IsConnected)
            {
                var connectionInfo = new ConnectionInfo(
                    _host,
                    _username,
                    new PasswordAuthenticationMethod(_username, _password));

                _client = new Renci.SshNet.SftpClient(connectionInfo);
                _client.Connect();
            }

            return(_client);
        }
Example #21
0
 /// <summary>
 /// Defines a SFTP Client transaction
 /// </summary>
 /// <param name="_cred">The SSH transaction credentials</param>
 /// <param name="task">The Transaction task</param>
 public static void SFTPTransactionVoid(SiteCredentials _cred, Action <Renci.SshNet.SftpClient> task)
 {
     using (var client = new Renci.SshNet.SftpClient(_cred.Host, _cred.Port, _cred.User, _cred.Password))
     {
         try
         {
             client.Connect();
             task(client);
             client.Disconnect();
         }
         catch (System.Exception exc)
         {
             Console.WriteLine(exc.Message);
         }
     }
 }
 /// <summary>
 /// Sync output of current compilation to <paramref name="dir"/>
 /// </summary>
 /// <param name="dir"></param>
 /// <returns></returns>
 private bool SyncTo(string dir)
 {
     // Copy files over
     using (var sftp = new SftpClient(Machine, Port, Username, Password))
     {
         sftp.Connect();
         if (!sftp.IsConnected)
         {
             return false;
         }
         // Perform recursive copy of all the folders under `dir`. This is required
         // as the sftp client only synchronize directories at their level only, no
         // subdirectory.
         var dirs = new Queue<DirectoryInfo>();
         dirs.Enqueue(new DirectoryInfo(dir));
         var parentPath = new UDirectory(dir);
         while (dirs.Count != 0)
         {
             var currentDir = dirs.Dequeue();
             var currentPath = new UDirectory(currentDir.FullName);
             foreach (var subdir in currentDir.EnumerateDirectories())
             {
                 dirs.Enqueue(subdir);
             }
             // Get the destination path by adding to `Location` the relative path of `dir` to `currentDir`.
             var destination = UPath.Combine(new UDirectory(Location.ItemSpec), currentPath.MakeRelative(parentPath));
             Log.LogMessage("Synchronizing " + currentPath + " with " + destination.FullPath);
             // Try to create a remote directory. If it throws an exception, we will assume
             // for now that the directory already exists. See https://github.com/sshnet/SSH.NET/issues/25
             try
             {
                 sftp.CreateDirectory(destination.FullPath);
                 Log.LogMessage("Creating remote directory " + destination.FullPath);
             }
             catch (SshException)
             {
                 // Do nothing, as this is when the directory already exists
             }
             // Synchronize files.
             foreach (var file in sftp.SynchronizeDirectories(currentPath.FullPath, destination.FullPath, "*"))
             {
                 Log.LogMessage("Updating " + file.Name);
             }
         }
         return true;
     }
 }
Example #23
0
        internal BasicRemoteOperations(IDeploymentContext context, IHost host)
        {
            Context = context;

            Sftp = new SftpClient(host.Hostname, host.Username, host.Password)
                {
                    OperationTimeout = TimeSpan.FromMinutes(2),
                    ConnectionInfo = {Timeout = TimeSpan.FromMinutes(2)},
                    BufferSize = 1024*16
                };
            Sftp.Connect();

            Shell = new SshClient(host.Hostname, host.Username, host.Password);
            Shell.Connect();
            ShellStream = Shell.CreateShellStream(
                String.Format("{0}@{1}", host.Username, host.Hostname), 0, 0, 0, 0, 1024);
        }
Example #24
0
        /// <summary>
        /// Defines a SFTP Client transaction
        /// </summary>
        /// <param name="_cred">The SSH transaction credentials</param>
        /// <param name="task">The Transaction task</param>
        /// <returns>The transaction result</returns>
        public static Object SFTPTransaction(SiteCredentials _cred, Func <Renci.SshNet.SftpClient, Object> task)
        {
            Object result = null;

            using (var client = new Renci.SshNet.SftpClient(_cred.Host, _cred.Port, _cred.User, _cred.Password))
            {
                try
                {
                    client.Connect();
                    result = task(client);
                    client.Disconnect();
                }
                catch (System.Exception exc)
                {
                    Console.WriteLine(exc.Message);
                }
            }
            return(result);
        }
Example #25
0
        /// <summary>
        /// Test the credentials connection
        /// </summary>
        /// <param name="_cred">The credential connections</param>
        /// <param name="errMsg">The error message</param>
        /// <returns>True if the credentials are valid to connect to the host</returns>
        public static Boolean TestConnection(SiteCredentials _cred, out string errMsg)
        {
            Boolean result = true;

            errMsg = String.Empty;
            using (var client = new Renci.SshNet.SftpClient(_cred.Host, _cred.Port, _cred.User, _cred.Password))
            {
                try
                {
                    client.Connect();
                    client.Disconnect();
                }
                catch (System.Exception exc)
                {
                    errMsg = Message.MSG_ERR_NO_CONN + ".\n" + exc.Message;
                    result = false;
                }
            }
            return(result);
        }
Example #26
0
        RenciSftpClient InstantiateClient()
        {
            var connectionInfo = new ConnectionInfo(Options.Host, Options.UserName, new PasswordAuthenticationMethod(Options.UserName, Options.Password));
            var client         = new RenciSftpClient(connectionInfo);

            client.Connect();
            if (!client.ConnectionInfo.IsAuthenticated)
            {
                throw new Exception("SFTP: Could not authenticate");
            }

            if (!string.IsNullOrWhiteSpace(Options.RemoteWorkingDirectory))
            {
                client.ChangeDirectory(Options.RemoteWorkingDirectory);
                if (client.WorkingDirectory != Options.RemoteWorkingDirectory)
                {
                    throw new Exception("SFTP: Do not match");
                }
            }

            return(client);
        }
Example #27
0
 /// <inheritdoc />
 public void CheckConnection()
 {
     _sftpClient.Connect();
     _sftpClient.Disconnect();
 }
        public void CreateConnection()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(_connectivitySettings.PrivateKeyPath))
                {
                    #region guard clause

                    if (string.IsNullOrWhiteSpace(_connectivitySettings.Host) ||
                        string.IsNullOrWhiteSpace(_connectivitySettings.UserName) ||
                        string.IsNullOrWhiteSpace(_connectivitySettings.Password))
                    {
                        Exception connectivityException = new Exception($"One or more connectivity-settings are incorrect: Host={_connectivitySettings.Host}, UserName={_connectivitySettings.UserName}, password=*******");
                        _logger.LogError(connectivityException, connectivityException.Message);
                        throw connectivityException;
                    }

                    #endregion guard clause

                    // connect using just username/password:
                    _sftpClient = new Renci.SshNet.SftpClient(
                        _connectivitySettings.Host,
                        _connectivitySettings.Port,
                        _connectivitySettings.UserName,
                        _connectivitySettings.Password);
                }
                else
                {
                    #region guard clause

                    if (string.IsNullOrWhiteSpace(_connectivitySettings.Host) ||
                        string.IsNullOrWhiteSpace(_connectivitySettings.UserName) ||
                        String.IsNullOrWhiteSpace(_connectivitySettings.Password) ||
                        string.IsNullOrWhiteSpace(_connectivitySettings.PrivateKeyPath))

                    {
                        Exception connectivityException = new Exception($"One or more connectivity-settings are incorrect: Host={_connectivitySettings.Host}, UserName={_connectivitySettings.UserName}, privateKeyPath={_connectivitySettings.PrivateKeyPath}");
                        _logger.LogError(connectivityException, connectivityException.Message);
                        throw connectivityException;
                    }

                    #endregion guard clause

                    // connect using just username/private key file/password as pass-phrase:
                    _logger.LogInformation($"Will log on with keyfile {_connectivitySettings.PrivateKeyPath}, with the pass-phrase given.");

                    VerifyPrivateKeyFileIsReadable(_connectivitySettings.PrivateKeyPath);
                    VerifyPrivateKeyIsNotPuttyFormat(_connectivitySettings.PrivateKeyPath);

                    PrivateKeyFile keyFile = new PrivateKeyFile(File.OpenRead(_connectivitySettings.PrivateKeyPath),
                                                                @_connectivitySettings.Password);

                    _sftpClient = new Renci.SshNet.SftpClient(
                        _connectivitySettings.Host,
                        _connectivitySettings.Port,
                        _connectivitySettings.UserName,
                        keyFile);
                }

                _logger.LogInformation($"Will connect to {_connectivitySettings.Host}, port {_connectivitySettings.Port}...");

                // Retry, waiting a specified duration between each retry
                var policy = Policy
                             .Handle <SocketException>()
                             .WaitAndRetry(DEFAULT_NUMBER_OF_CONNECTION_RETRIES,
                                           retryNumber => TimeSpan.FromSeconds(retryNumber * DEFAULT_WAIT_SECONDS),
                                           (ex, tsp) =>
                {
                    // method to call on retries.
                    // TODO: implement logging here.
                    System.Diagnostics.Debug.WriteLine($"Trying again in {tsp}");
                });
                policy.Execute(() => _sftpClient.Connect());
            }
            catch (Exception exception) when(exception.Message == @"Invalid private key file.")  // Catch specific key file error, redirect to possible solution.
            {
                // The SSH.Net component supports RSA and DSA private key in both OpenSSH and SSH.COM format.
                // Some tools, such as PuTTYgen, generates key-files that need to be converted to another format in order to work with SSH.Net.

                Exception innerException = new Exception($@"Invalid key file, possible https://stackoverflow.com/questions/43915130/does-ssh-net-accept-only-openssh-format-of-private-key-if-not-what-are-the-res issue.", exception);
                // wrap exception in own specific exception.
                DotNetSftpClientException dotNetSftpClientException =
                    new DotNetSftpClientException("DotNetSftpClient error, see inner Exception for details", innerException);

                throw dotNetSftpClientException;
            }
            catch (Exception exception)
            {
                // wrap exception in own specific exception.
                DotNetSftpClientException dotNetSftpClientException =
                    new DotNetSftpClientException("DotNetSftpClient error, see inner Exception for details", exception);

                throw dotNetSftpClientException;
            }
        }
Example #29
0
 public void ftpConnect()
 {
     ftp = new SftpClient(connectionInfo);
     ftp.Connect();
 }
Example #30
0
        public override async Task Connect(bool reconnecting = false)
        {
            Notifications.ChangeTrayText(reconnecting ? MessageType.Reconnecting : MessageType.Connecting);
            Log.Write(l.Debug, "{0} client...", reconnecting ? "Reconnecting" : "Connecting");

            ConnectionInfo connectionInfo;

            if (Controller.IsPrivateKeyValid)
            {
                connectionInfo = new PrivateKeyConnectionInfo(Controller.Account.Host, Controller.Account.Port,
                                                              Controller.Account.Username,
                                                              new PrivateKeyFile(Controller.Account.PrivateKeyFile, Controller.Account.Password));
            }
            else
            {
                connectionInfo = new PasswordConnectionInfo(Controller.Account.Host, Controller.Account.Port,
                                                            Controller.Account.Username, Controller.Account.Password);
            }
            connectionInfo.Encoding = this.Charset;

            connectionInfo.AuthenticationBanner += (o, x) =>
                                                   Log.Write(l.Warning, x.BannerMessage);

            _sftpc = new Renci.SshNet.SftpClient(connectionInfo);

            _sftpc.HostKeyReceived += (o, x) =>
            {
                var fingerPrint = x.FingerPrint.GetCertificateData();

                // if ValidateCertificate handler isn't set, accept the certificate and move on
                if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint))
                {
                    Log.Write(l.Client, "Trusted: {0}", fingerPrint);
                    x.CanTrust = true;
                    return;
                }

                var e = new ValidateCertificateEventArgs
                {
                    Fingerprint = fingerPrint,
                    Key         = x.HostKeyName,
                    KeySize     = x.KeyLength.ToString()
                };
                // Prompt user to validate
                ValidateCertificate?.Invoke(null, e);
                x.CanTrust = e.IsTrusted;
            };

            var caughtException = default(Exception);
            await Task.Run(() =>
            {
                try
                {
                    _sftpc.Connect();
                }
                catch (SshAuthenticationException ex)
                {
                    ex.LogException();
                    caughtException = new AuthenticationException(ex.Message, ex.InnerException);
                }
                catch (SshConnectionException ex)
                {
                    ex.LogException();
                    caughtException = new CertificateDeclinedException(ex.Message, ex.InnerException);
                }
                catch (Exception ex)
                {
                    ex.LogException();
                    caughtException = ex;
                }
            });

            if (caughtException != default(Exception))
            {
                throw caughtException;
            }

            _sftpc.ErrorOccurred += async(o, e) =>
            {
                if (!IsConnected)
                {
                    Notifications.ChangeTrayText(MessageType.Nothing);
                }

                OnConnectionClosed(new ConnectionClosedEventArgs {
                    Text = e.Exception.Message
                });

                if (e.Exception is SftpPermissionDeniedException)
                {
                    Log.Write(l.Warning, "Permission denied error occured");
                }
                if (e.Exception is SshConnectionException)
                {
                    await Reconnect();
                }
            };

            Controller.HomePath = WorkingDirectory;

            if (IsConnected)
            {
                if (!string.IsNullOrWhiteSpace(Controller.Paths.Remote) && !Controller.Paths.Remote.Equals("/"))
                {
                    WorkingDirectory = Controller.Paths.Remote;
                }
            }

            Log.Write(l.Debug, "Client connected sucessfully");
            Notifications.ChangeTrayText(MessageType.Ready);

            if (Settings.IsDebugMode)
            {
                LogServerInfo();
            }
        }
Example #31
0
        public static void DeleteRemoteFile(string host, string file, string username, string password)
        {
            using (var sftp = new SftpClient(host, username, password))
            {
                sftp.Connect();

                sftp.Delete(file);

                sftp.Disconnect();

            }
        }
Example #32
0
        public SecureCopier(ResourceNode node)
        {
            Log.Info("SCP: Establishing connection to node " + node.ResourceName + "." + node.NodeName);

            var nodeAddress = node.NodeAddress; // todo : OR ExecutionUrl????!!!!!
            var addrParts   = node.NodeAddress.Split(':');

            int port = DEFAULT_SCP_PORT;

            if (addrParts.Length == 2)
            {
                int.TryParse(addrParts[1], out port);
                nodeAddress = addrParts[0];
            }

            // if resource asks us for password interactively:
            var interactiveAuthMethod = new KeyboardInteractiveAuthenticationMethod(node.Credentials.Username);

            interactiveAuthMethod.AuthenticationPrompt += delegate(object sender, Renci.SshNet.Common.AuthenticationPromptEventArgs e)
            {
                foreach (var prompt in e.Prompts)
                {
                    Log.Debug("Interactive request by resource node " + node.NodeName + ": '" + prompt.Request + "'");

                    if (prompt.Request.ToLowerInvariant().Contains("password"))
                    {
                        Log.Debug("Responding by password");
                        prompt.Response = node.Credentials.Password;
                    }
                }
            };

            ConnectionInfo connectionInfo;

            if (!String.IsNullOrWhiteSpace(node.Credentials.CertFile))
            {
                connectionInfo = new ConnectionInfo(nodeAddress, port, node.Credentials.Username,
                                                    new PrivateKeyAuthenticationMethod(
                                                        node.Credentials.Username,
                                                        new PrivateKeyFile(node.Credentials.CertFile, node.Credentials.Password)
                                                        )
                                                    );
            }
            else
            {
                connectionInfo = new ConnectionInfo(nodeAddress, port, node.Credentials.Username,
                                                    new PasswordAuthenticationMethod(node.Credentials.Username, node.Credentials.Password),
                                                    interactiveAuthMethod
                                                    );
            }

            try
            {
                _sftpClient = new SftpClient(connectionInfo);
                _sftpClient.Connect();

                _scp = null;
            }
            catch (Exception e)
            {
                Log.Warn("Unable to use sftp. Rolling bask to SCP for resource node " + node.ResourceName + "." + node.NodeName + ": " + e.ToString());
                _sftpClient = null;

                _scp = new Scp(nodeAddress, node.Credentials.Username, node.Credentials.Password);
                _scp.Connect(port);
            }
        }
Example #33
0
        public Task<bool> ConnectAsync(string password)
        {
            Task<bool> task = new Task<bool>(() =>
            {
                try
                {

                    SecureString securePasswod = DecryptString(password);
                    _sftp = new SftpClient(Host, UserName, ToInsecureString(securePasswod));
                    _sftp.OperationTimeout = new TimeSpan(0, 0, 10);
                    _sftp.Connect();

                    _ssh = new SshClient(Host, UserName, ToInsecureString(securePasswod));
                    _ssh.Connect();

                    IsConnected = true;
                    return true;
                }
                catch (Exception)
                {
                    IsConnected = false;
                    return false;
                }
            });
            task.Start();
            return task;
        }
Example #34
0
        protected void NBR_Send(int msgid, string m_ftp_host, string m_ftp_username, string m_ftp_password, string m_sftp_path, string m_messagename)
        {
            var m_headline = "";

            string m_customer = "NBR";
            var m_msgid = msgid.ToString();
            String connectionString = ConfigurationManager.ConnectionStrings["azureConnectionString"].ConnectionString;
            try
            {
                // Connect to the database and run the query.
                SqlConnection con = new SqlConnection(connectionString);
                string strSQL = "Select headline from story where storyid = " + msgid;
                SqlCommand cmd = new SqlCommand(strSQL, con);
                cmd.CommandType = CommandType.Text;
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    m_headline = (dr["headline"].ToString());
                }
                cmd.Dispose();
                con.Close();
                con.Dispose();
            }
            catch (Exception ex)
            {
                // The connection failed. Display an error message.
                PublishLog(m_msgid, m_headline, m_customer, ex.Message, "Pub Error");
            }
            //PublishLog(m_msgid, m_headline, m_customer, "NBR NEW SFTP Step 1", "Step 1 OK");

            string m_msg_file = m_msgid + "_NBR.xml";
            string m_fileroot = "http://businessdesk.blob.core.windows.net/messages/";
            string m_file = m_fileroot + m_msg_file;
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=businessdesk;AccountKey=zWYFxlr7zhbMhXLptJ2lvtrORvoPTVunsDAf/v8B0tDsUWMigwFOJs9wEZ62XU6UdFWM1BQJ/SN9dZ0JsWVlpw==");
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference("messages");
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(m_msg_file);
            string pathToFiles = Server.MapPath("/Stories/");

            string m_File = pathToFiles + m_msg_file;

            //PublishLog(m_msgid, m_File, m_customer, "NBR Before Blob Download", "Blob ");

            try
            {
                using (var fileStream = File.OpenWrite(m_File))
                {
                    blockBlob.DownloadToStream(fileStream);
                }
            }
            catch (Exception ex)
            {
                PublishLog(m_msgid, "Blob Error", m_customer, ex.Message, "Blob");
            }
            //PublishLog(m_msgid, m_File, m_customer, "NBR After Blob Download", "Blob");

            string host = "sftp.nbr.co.nz";
            string username = "******";
            string password = "******";
            var proxy_host = "us-east-1-static-brooks.quotaguard.com";
            var proxy_username = "******";
            var proxy_password = "******";
            int port = 22;
            ConnectionInfo infoConnection = new ConnectionInfo(host, port, username, ProxyTypes.Socks5, proxy_host, 1080, proxy_username, proxy_password, new PasswordAuthenticationMethod(username, password));
            //PublishLog(m_msgid, m_headline, m_customer, "NBR NEW SFTP con init OK", "Init OK");
            try
            {
                SftpClient client = new SftpClient(infoConnection);
                client.Connect();
                // PublishLog(m_msgid, m_headline, m_customer, "NBR NEW SFTP Connx OK", "Connx OK");

                using (var fileStream = new FileStream(m_File, FileMode.Open))
                {

                    client.UploadFile(fileStream, m_msg_file, true);

                }
                PublishLog(m_msgid, m_headline, m_customer, "NBR NEW SFTP Pub OK", "Publish OK");

            }
            catch (WebException ex)
            {
                PublishLog(m_msgid, m_headline, m_customer, ex.Message, "NBR Pub Error");
            }
        }
Example #35
0
        public void Connect()
        {
            if (sshConnection != null) {
            if (sshConnection.IsConnected) {
              try {
            sshConnection.Disconnect();
              } catch { }
            }
            sshConnection = null;
              }

              if (sshServer != "" && sshUsername != "" && sshPassword != "") {
            sshConnection = new SftpClient(sshServer, sshPort, sshUsername, sshPassword);
            // connect in a different thread, we don't want to block the main thread
            new Thread(new ThreadStart(delegate
            {
              bool ok = false;
              try {
            sshConnection.Connect();
            ok = true;
              } catch (Exception ex) {
            Tray.ShowBalloonTip(5000, "SFTP", "Failed to connect to SFTP server: \"" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message) + "\"", ToolTipIcon.Error);
            sshConnection = null;
              }
              if (connectionDoneCallback != null) {
            connectionDoneCallback(ok);
            connectionDoneCallback = null;
              }
            })).Start();
              }
        }
Example #36
0
        /// <summary>
        /// Connect to the remote servers, with the details from Profile
        /// </summary>
        /// <param name="reconnecting">True if this is an attempt to re-establish a closed connection</param>
        public void Connect(bool reconnecting = false)
        {
            Notifications.ChangeTrayText(reconnecting ? MessageType.Reconnecting : MessageType.Connecting);
            Log.Write(l.Debug, "{0} client...", reconnecting ? "Reconnecting" : "Connecting");

            if (FTP)
            {
                _ftpc = new FtpClient { Host = controller.Account.Host, Port = controller.Account.Port };

                // Add accepted certificates
                _ftpc.ClientCertificates.AddRange(Certificates);

                if (controller.Account.Protocol == FtpProtocol.FTPS)
                {
                    _ftpc.ValidateCertificate += (sender, x) =>
                    {
                        var fingerPrint = new X509Certificate2(x.Certificate).Thumbprint;

                        if (_ftpc.ClientCertificates.Count <= 0 && x.PolicyErrors != SslPolicyErrors.None)
                        {
                            Certificates.Add(x.Certificate);
                            x.Accept = false;
                            return;
                        }

                        // if ValidateCertificate handler isn't set, accept the certificate and move on
                        if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint))
                        {
                            Log.Write(l.Client, "Trusted: {0}", fingerPrint);
                            x.Accept = true;
                            return;
                        }

                        var e = new ValidateCertificateEventArgs
                        {
                            Fingerprint = fingerPrint,
                            SerialNumber = x.Certificate.GetSerialNumberString(),
                            Algorithm = x.Certificate.GetKeyAlgorithmParametersString(),
                            ValidFrom = x.Certificate.GetEffectiveDateString(),
                            ValidTo = x.Certificate.GetExpirationDateString(),
                            Issuer = x.Certificate.Issuer
                        };
                        // Prompt user to validate
                        ValidateCertificate(null, e);
                        x.Accept = e.IsTrusted;
                    };

                    // Change Security Protocol
                    if (controller.Account.FtpsMethod == FtpsMethod.Explicit)
                        _ftpc.EncryptionMode = FtpEncryptionMode.Explicit;
                    else if (controller.Account.FtpsMethod == FtpsMethod.Implicit)
                        _ftpc.EncryptionMode = FtpEncryptionMode.Implicit;
                }

                _ftpc.Credentials = new NetworkCredential(controller.Account.Username, controller.Account.Password);

                try
                {
                    _ftpc.Connect();
                }
                catch (Exception exc)
                {
                    // Since the ClientCertificates are added when accepted in ValidateCertificate, the first
                    // attempt to connect will fail with an AuthenticationException. If this is the case, a
                    // re-connect is attempted, this time with the certificates properly set.
                    // This is a workaround to avoid storing Certificate files locally...
                    if (exc is System.Security.Authentication.AuthenticationException
                        && _ftpc.ClientCertificates.Count <= 0)
                        Connect();
                    else
                        throw;
                }
            }
            else // SFTP
            {
                ConnectionInfo connectionInfo;
                if (controller.isPrivateKeyValid)
                    connectionInfo = new PrivateKeyConnectionInfo(controller.Account.Host, controller.Account.Port, controller.Account.Username, new PrivateKeyFile(controller.Account.PrivateKeyFile, controller.Account.Password));
                else
                    connectionInfo = new PasswordConnectionInfo(controller.Account.Host, controller.Account.Port, controller.Account.Username, controller.Account.Password);

                _sftpc = new SftpClient(connectionInfo);
                _sftpc.ConnectionInfo.AuthenticationBanner += (o, x) => Log.Write(l.Warning, x.BannerMessage);

                _sftpc.HostKeyReceived += (o, x) =>
                {
                    var fingerPrint = x.FingerPrint.GetCertificateData();

                    // if ValidateCertificate handler isn't set, accept the certificate and move on
                    if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint))
                    {
                        Log.Write(l.Client, "Trusted: {0}", fingerPrint);
                        x.CanTrust = true;
                        return;
                    }

                    var e = new ValidateCertificateEventArgs
                    {
                        Fingerprint = fingerPrint,
                        Key = x.HostKeyName,
                        KeySize = x.KeyLength.ToString()
                    };
                    // Prompt user to validate
                    ValidateCertificate(null, e);
                    x.CanTrust = e.IsTrusted;
                };

                _sftpc.Connect();

                _sftpc.ErrorOccurred += (o, e) =>
                {
                    if (!isConnected) Notifications.ChangeTrayText(MessageType.Nothing);
                    if (ConnectionClosed != null) ConnectionClosed(null, new ConnectionClosedEventArgs { Text = e.Exception.Message });

                    if (e.Exception is Renci.SshNet.Common.SftpPermissionDeniedException)
                        Log.Write(l.Warning, "Permission denied error occured");
                    if (e.Exception is Renci.SshNet.Common.SshConnectionException)
                        Reconnect();
                };
            }

            controller.HomePath = WorkingDirectory;

            if (isConnected)
                if (!string.IsNullOrWhiteSpace(controller.Paths.Remote) && !controller.Paths.Remote.Equals("/"))
                    WorkingDirectory = controller.Paths.Remote;

            Log.Write(l.Debug, "Client connected sucessfully");
            Notifications.ChangeTrayText(MessageType.Ready);

            if (Settings.IsDebugMode)
                LogServerInfo();

            // Periodically send NOOP (KeepAlive) to server if a non-zero interval is set
            SetKeepAlive();
        }
Example #37
0
        private static bool SshUpload(Uri url)
        {
            Console.WriteLine("Select SSH method");

            using (var sftp = new SftpClient(url.Host , url.IsDefaultPort?22:url.Port, ConfigurationManager.AppSettings["UserName"], ConfigurationManager.AppSettings["Password"]))
            {
                try
                {
                    sftp.Connect();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Can't connect to {0}",url);
                    Console.WriteLine("Details :{0}", e.Message);
                    return false;
                }

                using (var file = File.OpenRead(_fileNameZip))
                {
                    Console.WriteLine("Uploading...");
                    sftp.UploadFile(file,
                        String.Format("{0}{1}", ConfigurationManager.AppSettings["RemotePath"],
                            Path.GetFileName(_fileNameZip)), true);
                }
                Console.WriteLine("Disconnect");
                sftp.Disconnect();
            }

            return true;
        }
Example #38
-1
        public Response UploadSFTP(DataExtensionImport dataExtensionImport)
        {
            var response = new Response { Success = true, Warning = false };
            try
            {
                const int port = 22;
                const string host = "ftp.s6.exacttarget.com";
                const string username = "******";
                const string password = "******";
                const string workingdirectory = "/Import//";

                using (var client = new SftpClient(host, port, username, password))
                {
                    client.Connect();
                    client.ChangeDirectory(workingdirectory);

                    string extension = Path.GetExtension(dataExtensionImport.Ruta);
                    string nombreArchivo = string.Format("{0}{1}", dataExtensionImport.Nombre, extension);
                    using (var fileStream = new FileStream(dataExtensionImport.Ruta, FileMode.Open))
                    {

                        client.BufferSize = 4 * 1024; // bypass Payload error large files
                        client.UploadFile(fileStream, nombreArchivo);
                    }
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return response;
        }
        //turn this into some kind of interface
        public GatherResults DownloadQtyFiles(IVendorDirectory dir)
        {
            var files = new List<File>();

            using (var sftp = new SftpClient(_config.QtyFileHost,
                _config.QtyFilePort,
                _config.QtyFileUsername,
                _config.QtyFilePassword))
            {
                sftp.Connect();

                dir.EnsureExists();

                var localFile = dir.GetNewRawFile(FileTypes.Qty);
                using (var stream = new FileStream(localFile.Name.GetPath(), FileMode.Create))
                {
                    sftp.DownloadFile(_config.QtyFileName, stream);
                }
                files.Add(localFile);

                sftp.Disconnect();
            }

            return new GatherResults
            {
                VendorHandle = dir.VendorHandle,
                Files = files
            };
        }
Example #40
-1
        public void Initialize()
        {
            if (SftpClient != null)
                return;

            SftpClient = new SftpClient(Host, Port, User, Password);
            SftpClient.Connect();

            // Try to setup a ssh connection to speedup file listing
            try
            {
                SshClient = new SshClient(Host, Port, User, Password);
                SshClient.Connect();
            }
            catch
            {
                SshClient = null;
            }
        }
 /// <summary>
 /// This function will connect to the SFTP server for Wells Fargo
 /// </summary>
 private static void sftpConnect()
 {
     client = new Renci.SshNet.SftpClient(sftpHost, sftpPort, sftpUsername, new PrivateKeyFile(new MemoryStream(Encoding.ASCII.GetBytes(sftpKeyFile))));
     try
     {
         client.Connect();
         client.ChangeDirectory(downloadPath);
     }
     catch (Exception e)
     {
         appendToBody(String.Format("Download client threw an exception: {0}", e.Message.ToString()));
         Console.WriteLine(string.Format("exception...{0}", e));
     }
 }
Example #42
-1
        private bool Sftp(string server, int port, bool passive, string username, string password, string filename, int counter, byte[] contents, out string error, bool rename)
        {
            bool failed = false;
            error = "";
            try
            {
                int i = 0;
                filename = filename.Replace("{C}", counter.ToString(CultureInfo.InvariantCulture));
                if (rename)
                    filename += ".tmp";

                while (filename.IndexOf("{", StringComparison.Ordinal) != -1 && i < 20)
                {
                    filename = String.Format(CultureInfo.InvariantCulture, filename, Helper.Now);
                    i++;
                }

                var methods = new List<AuthenticationMethod> { new PasswordAuthenticationMethod(username, password) };

                var con = new ConnectionInfo(server, port, username, methods.ToArray());
                using (var client = new SftpClient(con))
                {
                    client.Connect();

                    var filepath = filename.Trim('/').Split('/');
                    var path = "";
                    for (var iDir = 0; iDir < filepath.Length - 1; iDir++)
                    {
                        path += filepath[iDir] + "/";
                        try
                        {
                            client.CreateDirectory(path);
                        }
                        catch
                        {
                            //directory exists
                        }
                    }
                    if (path != "")
                    {
                        client.ChangeDirectory(path);
                    }

                    filename = filepath[filepath.Length - 1];

                    using (Stream stream = new MemoryStream(contents))
                    {
                        client.UploadFile(stream, filename);
                        if (rename)
                        {
                            try
                            {
                                //delete target file?
                                client.DeleteFile(filename.Substring(0, filename.Length - 4));
                            }
                            catch (Exception)
                            {
                            }
                            client.RenameFile(filename, filename.Substring(0, filename.Length - 4));
                        }
                    }

                    client.Disconnect();
                }

                MainForm.LogMessageToFile("SFTP'd " + filename + " to " + server + " port " + port, "SFTP");
            }
            catch (Exception ex)
            {
                error = ex.Message;
                failed = true;
            }
            return !failed;
        }
        public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction) {

            try {
                using (var sftp = new SftpClient(Host, Port, Username, Password))
                {
                    sftp.Connect();

                    using (var file = File.OpenWrite(TargetPath))
                    {
                        sftp.DownloadFile(SourcePath, file);
                    }

                    return DTSExecResult.Success;
                }   
            } catch (Exception ex) {
                log.Write(string.Format("{0}.Execute", GetType().FullName), ex.ToString());
                return DTSExecResult.Failure;
            }
        }
        private void Uploadfiles(PasswordConnectionInfo connectionInfo, IEnumerable<AchFileEntity> achFilesToUpload)
        {
            using (var sftp = new SftpClient(connectionInfo))
            {          
                try
                {
                    sftp.Connect();

                    foreach (var achfile in achFilesToUpload)
                    {
                        using (var stream = new MemoryStream())
                        {
                            var fileName = achfile.Name + ".ach";

                            var writer = new StreamWriter(stream);
                           // writer.Write(achfile.AchFileBody);
                            writer.Flush();
                            stream.Position = 0;

                            sftp.UploadFile(stream, fileName);
                            this.Manager.ChangeAchFilesStatus(achfile, AchFileStatus.Uploaded);
                            this.Manager.UnLock(achfile);
                        }
                    }
                }
                finally
                {
                    sftp.Disconnect();
                }
            }
        }