当前位置: 首页>>代码示例>>C#>>正文


C# SftpClient.Connect方法代码示例

本文整理汇总了C#中Renci.SshNet.SftpClient.Connect方法的典型用法代码示例。如果您正苦于以下问题:C# SftpClient.Connect方法的具体用法?C# SftpClient.Connect怎么用?C# SftpClient.Connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Renci.SshNet.SftpClient的用法示例。


在下文中一共展示了SftpClient.Connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CopyFileFromRemoteToLocal

        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();
            }
        }
开发者ID:wangn6,项目名称:rep2,代码行数:17,代码来源:SSHWrapper.cs

示例2: PollHandler

        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);
        }
开发者ID:ojoadeolagabriel,项目名称:TqWorkflow-beta,代码行数:48,代码来源:FtpConsumer.cs

示例3: Uploadfiles

        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();
                }
            }
        }
开发者ID:rconnelly,项目名称:ach.fulfillment,代码行数:31,代码来源:UploadAchFilesJob.cs

示例4: sendSFTP

 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();
     }
 }
开发者ID:CapG,项目名称:POC_WIPlugin_DatasExporter,代码行数:10,代码来源:IVRExportAsset.cs

示例5: CopyFileFromLocalToRemote

 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();
     }
 }
开发者ID:wangn6,项目名称:rep2,代码行数:15,代码来源:SSHWrapper.cs

示例6: GetList

        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;
            }
        }
开发者ID:vchelaru,项目名称:FlatRedBall,代码行数:15,代码来源:SftpManager.cs

示例7: UploadFile

 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;
 }
开发者ID:wj88808886,项目名称:OSU_PrintingHelper_Windows,代码行数:38,代码来源:NetworkHandler.cs

示例8: ProcessRecord

        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)
//.........这里部分代码省略.........
开发者ID:victorvogelpoel,项目名称:Posh-SSH,代码行数:101,代码来源:poshssh.cs

示例9: DownloadFilesWithSftpAsync

        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);
        }
开发者ID:dev4s,项目名称:2015-file-synchronizer,代码行数:25,代码来源:Synchronizer.cs

示例10: SshFactory

 public SshFactory(String host, String username, String password)
 {
     _connection = new SshClient(host, username, password);
     _connection.Connect();
     _sftp = new SftpClient(_connection.ConnectionInfo);
     _sftp.Connect();
 }
开发者ID:a1binos,项目名称:SystemInteract.Net,代码行数:7,代码来源:SshFactory.cs

示例11: beginCracking

        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);
                }
            }
        }
开发者ID:koufengwei,项目名称:Brake,代码行数:54,代码来源:CrackProcess.cs

示例12: SFTP

        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);
        }
开发者ID:1aurent,项目名称:CloudBackup,代码行数:11,代码来源:SFTP.cs

示例13: UploadFile

        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();
            }
        }
开发者ID:vchelaru,项目名称:FlatRedBall,代码行数:11,代码来源:SftpManager.cs

示例14: DeleteRemoteDirectory

        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();

            }
        }
开发者ID:vchelaru,项目名称:FlatRedBall,代码行数:12,代码来源:SftpManager.cs

示例15: TryGetFileFromFtp

		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;
		}
开发者ID:csulham,项目名称:Sitecore.SharedSource.UserCsvImport,代码行数:51,代码来源:SshFileDownloader.cs


注:本文中的Renci.SshNet.SftpClient.Connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。