private Exception Connectclient() { //initialize new Sftp connection client = new Sftp(); client.Timeout = -1; client.ReconnectionMaxRetries = 10; //connect to client try { client.Connect(Packet.LoginData.Url); } catch (Exception ex) { client.Disconnect(); return(ex); } //authenticate user try { client.Authenticate(Packet.LoginData.Username, Packet.LoginData.Password); } catch (Exception ex) { client.Disconnect(); return(ex); } return(null); }
/// <summary> /// Get all file names in a directory /// </summary> /// <returns> /// Array of file names as strings /// </returns> public async Task <string[]> DirectoryListAsync(string fileNamePrefix, string folderName) { return(await Task.Run( () => { List <string> fileNames = new List <string>(); using (Sftp client = new Sftp()) { client.Connect(SftpUri); client.Login(Username, Password); client.ChangeDirectory(folderName); SftpItemCollection list = client.GetList(); foreach (SftpItem item in list) { if (item.Name.ToUpper().StartsWith(fileNamePrefix.ToUpper())) { fileNames.Add(item.Name); } } } return fileNames.ToArray(); } )); }
public void ShouldSetPassword() { string p = "password"; Sftp ssh = Sftp.Server("localhost").Password(p); Expect.AreEqual(ssh.Config.Password, p, "Password was not set properly"); }
private string IsSFtpServerAvailable(LoginData loginData) { Sftp ftpClient = new Sftp(); try { ftpClient.Connect(loginData.Url); } catch (Exception ex) { return(string.Format("- Cannot connect to ftp server '{0}'", loginData.Url)); } if (!ftpClient.IsConnected) { return(string.Format("- Cannot connect to ftp server '{0}'", loginData.Url)); } try { ftpClient.Authenticate(loginData.Username, loginData.Password); } catch (Exception ex) { ftpClient.Disconnect(); return(string.Format("- Invalid credentials for server '{0}', username '{1}'", loginData.Url, loginData.Username)); } ftpClient.Disconnect(); return(""); }
public static Dictionary <string, string> GetGdmXAuth(MeeGoDevice targetDevice) { Sftp sftp = null; try { sftp = new Sftp(targetDevice.Address, targetDevice.Username, targetDevice.Password); sftp.Connect(); var files = sftp.GetFileList("/var/run/gdm/auth-for-" + targetDevice.Username + "*"); sftp.Close(); if (files.Count == 1) { return(new Dictionary <string, string> () { { "XAUTHLOCALHOSTNAME", "localhost" }, { "DISPLAY", ":0.0" }, { "XAUTHORITY", "/var/run/gdm/" + files[0] + "/database" } }); } } catch (Exception ex) { LoggingService.LogError("Error getting xauth via sftp", ex); if (sftp != null) { try { sftp.Close(); } catch (Exception ex2) { LoggingService.LogError("Error closing sftp connection", ex2); } } } return(null); }
/// <summary> /// Create a stream for writing to an SFTP resource. /// </summary> /// <param name="sftp"></param> /// <param name="channel"></param> /// <param name="handle"></param> internal SftpStream(Sftp sftp, byte[] handle) : base() { this.sftp = sftp; this.handle = handle; this.reader = false; }
/* the only function in the class that delete file on the sftp server */ public static void Delete(string host, string username, string password, string fileName) { JSch js = new JSch(); // declare sftp connection Sftp sftp = new Sftp(host, username, password); sftp.Connect(); // Create a session with SFTP credentials Session session = js.getSession(sftp.Username, sftp.Host); // Get a UserInfo object UserInfo ui = new UInfo(sftp.Password); // Pass user info to session session.setUserInfo(ui); // Open the session session.connect(); // Tell it is an SFTP Channel channel = session.openChannel("sftp"); ChannelSftp cSftp = (ChannelSftp)channel; cSftp.connect(); // Delete the file cSftp.rm(fileName); // disconnection channel.disconnect(); cSftp.exit(); sftp.Close(); }
static void Main(string[] args) { Sftp sftp = new Sftp(SFTPConnectSample.Properties.Settings.Default.HostName, SFTPConnectSample.Properties.Settings.Default.UserName, SFTPConnectSample.Properties.Settings.Default.Password); sftp.Connect(); #region Require if you want to delete Files JSch objjsh = new JSch(); Session session = objjsh.getSession(SFTPConnectSample.Properties.Settings.Default.UserName, SFTPConnectSample.Properties.Settings.Default.HostName); // Get a UserInfo object UserInfo ui = new UInfo(SFTPConnectSample.Properties.Settings.Default.Password);; // Pass user info to session session.setUserInfo(ui); // Open the session session.connect(); Channel channel = session.openChannel("sftp"); ChannelSftp cSftp = (ChannelSftp)channel; cSftp.connect(); #endregion ArrayList res = sftp.GetFileList(SFTPConnectSample.Properties.Settings.Default.FromPath + "*.xml"); foreach (var item in res) { if (item.ToString() != "." && item.ToString() != "..") { //File Copy from Remote sftp.Get(SFTPConnectSample.Properties.Settings.Default.FromPath + item, Path.Combine(Application.StartupPath, SFTPConnectSample.Properties.Settings.Default.DirectoryPath + "/" + item)); //File Delete from Remote cSftp.rm(SFTPConnectSample.Properties.Settings.Default.FromPath + item); //Upload File sftp.Put(Path.Combine(Path.Combine(Application.StartupPath, "XMLFiles"), item.ToString()), SFTPConnectSample.Properties.Settings.Default.ToPath + item); } } channel.disconnect(); cSftp.exit(); sftp.Close(); }
private async Task <Message> ReadAsync(string path, string fileName) { var stream = new MemoryStream(); var fullPath = Path.Combine(path, fileName).Replace('\\', '/'); using (var sftpClient = new Sftp()) { sftpClient.TransferType = _transferType; await sftpClient.ConnectAsync(_serverAddress, _port); await sftpClient.LoginAsync(_userName, _password); await sftpClient.GetFileAsync(fullPath, stream); await sftpClient.DisconnectAsync(); } // Rewind the stream: stream.Position = 0; return(new Message { ContentStream = stream }); }
public static bool ValidateClinicSftpDetails(List <ProgramProperty> listPropsForClinic, bool doTestConnection = true) { //No need to check RemotingRole;no call to db. string sftpAddress = listPropsForClinic.Find(x => x.PropertyDesc == "SftpServerAddress")?.PropertyValue; int sftpPort; if (!int.TryParse(listPropsForClinic.Find(x => x.PropertyDesc == "SftpServerPort")?.PropertyValue, out sftpPort) || sftpPort < ushort.MinValue || //0 sftpPort > ushort.MaxValue) //65,535 { sftpPort = 22; //default to port 22 } string userName = listPropsForClinic.Find(x => x.PropertyDesc == "SftpUsername")?.PropertyValue; string userPassword = listPropsForClinic.Find(x => x.PropertyDesc == "SftpPassword")?.PropertyValue; if (string.IsNullOrWhiteSpace(sftpAddress) || string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(userPassword)) { return(false); } if (doTestConnection) { return(Sftp.IsConnectionValid(sftpAddress, userName, userPassword, sftpPort)); } return(true); }
private static bool ValidarConexionSftp() { Sftp client = new Sftp(sftpServidor, sftpUsuario, sftpPassword); _log.DebugFormat("Validando conexion Sftp. Servidor:{0}, Usuario:{1}, Password: {2}", sftpServidor, sftpUsuario, sftpPassword); try { client.Connect(); if (client.Connected) { _log.DebugFormat("Conexion exitosa"); return(true); } else { _log.DebugFormat("No se pudo establecer la conexion"); } }catch (Exception ex) { _log.Error(ex.Message); } return(false); }
/* constructor that initialize folders for xml feed */ public ShopCa() { #region Folder Check // check and generate folders if (!Directory.Exists(rootDir)) { Directory.CreateDirectory(rootDir); } newOrderDir = rootDir + "\\ShopCaNewOrders"; if (!Directory.Exists(newOrderDir)) { Directory.CreateDirectory(newOrderDir); } completeOrderDir = rootDir + "\\ShopCaCompleteOrders"; if (!Directory.Exists(completeOrderDir)) { Directory.CreateDirectory(completeOrderDir); } #endregion // get credentials for shop.ca sftp log on and initialize the field using (SqlConnection connection = new SqlConnection(Credentials.AscmCon)) { SqlCommand command = new SqlCommand("SELECT Field1_Value, Username, Password From ASCM_Credentials WHERE Source='Shop.ca - SFTP'", connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); reader.Read(); // initialize Sftp sftp = new Sftp(reader.GetString(0), reader.GetString(1), reader.GetString(2)); } }
/// <summary> /// Upload a file to destinationDirectory of Exact targets Sftp location /// </summary> /// <param name="pathOfFileToBeTransfered"></param> /// <param name="address"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="destinationDirectory"></param> public void UploadFile(string pathOfFileToBeTransfered, string address, string username, string password, string destinationDirectory) { Sftp fileTransfer = null; if (string.IsNullOrWhiteSpace(pathOfFileToBeTransfered)) { throw new ArgumentNullException("pathOfFileToBeTransfered"); } try { SshParameters connectionParameters = new SshParameters(address, username, password); using (fileTransfer = new Sftp(connectionParameters)) { fileTransfer.Connect(); fileTransfer.SetBinaryMode(); fileTransfer.RemoteDir = destinationDirectory; fileTransfer.Upload(pathOfFileToBeTransfered); } return; } finally { if (fileTransfer != null && fileTransfer.IsConnected) { fileTransfer.Disconnect(); } fileTransfer = null; } }
private void DownloadAndStoreFile(ConversionStartResult conversionResult, DirectoryInfo targetFolder) { Licensing.Key = DocumentConverterSettings.Default.SftpLicenseKey; try { using (var client = new Sftp()) { client.Connect(conversionResult.UploadUrl, conversionResult.Port); client.Login(conversionResult.User, conversionResult.Password); var remotePath = $"{client.GetCurrentDirectory()}{conversionResult.ConvertedFileName}"; var targetPath = Path.Combine(targetFolder.FullName, $"{conversionResult.ConvertedFileName}"); if (!client.FileExists(remotePath)) { Console.WriteLine($"ERROR: File {conversionResult.ConvertedFileName} not found on SFTP server."); } var length = client.GetFile(remotePath, targetPath); Console.WriteLine($"Converted file {targetPath} and downloaded {length} bytes"); } } catch (Exception e) { Console.WriteLine(e); } }
private async Task UploadFile(JobInitResult jobInitResult, FileInfo toBeConverted) { Licensing.Key = sftpLicenseKey; using (var client = new Sftp()) { await client.ConnectAsync(jobInitResult.UploadUrl, jobInitResult.Port); await client.LoginAsync(jobInitResult.User, jobInitResult.Password); var uploadName = $"{client.GetCurrentDirectory()}{toBeConverted.Name}"; Log.Verbose("Uploading file {FullName} to {UploadName}", toBeConverted.FullName, uploadName); if (toBeConverted.Exists) { await client.PutFileAsync(toBeConverted.FullName, uploadName); Log.Verbose("Upload successfull"); } else { Log.Verbose("File {FullName} does not exist, or cannot be accessed.", toBeConverted.FullName); throw new FileNotFoundException("File could not be uploaded, because source file is not accessible or cannot be found", toBeConverted.FullName); } } }
public void CanUploadToRootDir() { using (var file = new DummyFile(1024 * 1024 * 3)) { Sftp.UploadFile(Cs, file.FileInfo.FullName, true); } }
private void efwSimpleButton2_Click(object sender, EventArgs e) { try { string sftpURL = "14.63.165.36"; string sUserName = "******"; string sPassword = "******"; int nPort = 22023; string sftpDirectory = "/domalifefiles/files/product/domamall"; // 저장 경로 string LocalDirectory = "D:\\temp"; //Local directory from where the files will be uploaded string FileName = "test1.jpg"; //File name, which one will be uploaded Sftp sSftp = new Sftp(sftpURL, sUserName, sPassword); sSftp.Connect(nPort); // sSftp.Mkdir("/domalifefiles/files/product/domamall/temp"); sSftp.Put(LocalDirectory + "/" + FileName, sftpDirectory + "/" + FileName); sSftp.Close(); } catch (Exception ex) { return; } }
public async Task <bool> SaveToCache(IBus bus, CacheRetentionCategory retentionCategory, string file) { if (!File.Exists(file)) { throw new FileNotFoundException("Unable to upload file to cache because file was not found", file); } var cacheConnectionInfoRequest = new CacheConnectionInfoRequest(); var requestClient = CreateRequestClient <CacheConnectionInfoRequest, CacheConnectionInfoResponse>(bus, BusConstants.CacheConnectionInfoRequestQueue); var response = await requestClient.Request(cacheConnectionInfoRequest); try { using (var client = new Sftp()) { client.Connect(response.Machine, (int)response.Port); Log.Information("connected to {host}:{port}", response.Machine, response.Port); client.Login(retentionCategory.ToString(), response.Password); Log.Information("{username} logged in successfully ", retentionCategory); client.Upload(file, "/", TraversalMode.NonRecursive, TransferMethod.Copy, ActionOnExistingFiles.OverwriteAll); return(true); } } catch (Exception ex) { Log.Error(ex, "Unexpexted error while uploading to cache"); } return(false); }
/// <summary> /// 登录到Sftp服务器 /// </summary> /// <param name="config">Sftp参数</param> /// <returns></returns> public OperationReturn LogOn(SftpHelperConfig config) { OperationReturn optReturn = new OperationReturn(); optReturn.Result = true; optReturn.Code = 0; try { if (mSftp != null) { try { if (mSftp.Connected) { mSftp.Connected = false; } mSftp = null; } catch { } } mSftp = new Sftp(); mSftp.OnSSHServerAuthentication += (s, se) => se.Accept = true; mSftp.SSHHost = config.ServerHost; mSftp.SSHPort = config.ServerPort; mSftp.SSHUser = config.LoginUser; switch (config.AuthType) { case 1: mSftp.SSHAuthMode = SftpSSHAuthModes.amPassword; mSftp.SSHPassword = config.LoginPassword; break; case 2: mSftp.SSHAuthMode = SftpSSHAuthModes.amPublicKey; mSftp.SSHCert = new Certificate(CertStoreTypes.cstPFXFile, config.CertFile, config.CertPassword, config.CertPassword); break; case 3: mSftp.SSHAuthMode = SftpSSHAuthModes.amMultiFactor; mSftp.SSHPassword = config.LoginPassword; mSftp.SSHCert = new Certificate(CertStoreTypes.cstPFXFile, config.CertFile, config.CertPassword, config.CertSubject); break; default: optReturn.Result = false; optReturn.Code = Defines.RET_CONFIG_INVALID; optReturn.Message = string.Format("Auth type not support.\t{0}", config.AuthType); return(optReturn); } mSftp.SSHLogon(config.ServerHost, config.ServerPort); return(optReturn); } catch (Exception ex) { optReturn.Result = false; optReturn.Code = Defines.RET_FAIL; optReturn.Message = ex.Message; return(optReturn); } }
public void ShouldSetSshUserName() { string un = "userTest"; Sftp ssh = Sftp.Server("localhost").UserName(un); Expect.AreEqual(ssh.Config.UserName, un, "UserName was not set properly"); }
public void CanUploadToSubSubDir() { using (var file = new DummyFile(1024 * 1024 * 3)) { Sftp.UploadFile(Cs, file.FileInfo.FullName, true, "a/b/c"); } }
private void Form1_Load(object sender, EventArgs e) { /* * // Get a UserInfo object * UserInfo ui = new UInfo(SFTPConnectSample.Properties.Settings.Default.Password); ; * // Pass user info to session * session.setUserInfo(ui); * // Open the session * session.connect(); * Channel channel = session.openChannel("sftp"); * ChannelSftp cSftp = (ChannelSftp)channel; * cSftp.connect(); */ try { sftp = new Sftp(SFTPshare.Properties.Settings.Default.HostName, SFTPshare.Properties.Settings.Default.UserName, SFTPshare.Properties.Settings.Default.Password); } catch (Exception) { MessageBox.Show("Error instantiating sftp"); } try { sftp.AddIdentityFile(privateKeyPath); } catch (Exception) { MessageBox.Show("Error connecting with private key"); } try { sftp.Connect(); } catch (Exception) { } //ArrayList res = sftp.GetFileList("."); //ArrayList Newres = sftp.GetFileList("."); //filesRecap = sftp.GetFileList("."); }
public static List <string> SFTPScanDirs(Sftp sftpHandler, string initialPath, int recursionLevel) { var outListFiles = new List <string>(); var pathElements = initialPath.Split('/'); var dirpath = initialPath.Substring(0, initialPath.LastIndexOf('/')); if (string.IsNullOrWhiteSpace(dirpath)) { dirpath += "/"; } var pattern = pathElements[pathElements.Length - 1]; var bHasPattern = pattern.Contains("*") || pattern.Contains("?"); if (!bHasPattern) { dirpath += pattern; } SFTPScanDirs(sftpHandler, dirpath, recursionLevel, ref outListFiles); return((bHasPattern) ? outListFiles.LikeDir(pattern) : outListFiles); }
/// <summary> /// 推至遠程 /// </summary> private void ToPut() { try { //fortify漏洞-----------------------------------------------add by bruce 20131220 _password = AntiXSS.GetSafeHtmlFragment(_password); //fortify漏洞-----------------------------------------------add by bruce 20131220 //開始進行SFTP程序 _sftp = new Sftp(_hostName, _userName, _password); _sftp.Connect(_port); System.Threading.Thread.Sleep(3000); _sftp.Put(_fromFilePath, _toFilePath); System.Threading.Thread.Sleep(3000); _sftp.Close(); //write log string msg = ""; msg = "遠程" + _hostName + _toFilePath + ", 檔案已產生。"; Console.WriteLine(msg); LogController.WriteLog("SimpleSftp.Put", msg); } catch (Exception ex) { LogController.WriteLog("SimpleSftp.Put", ex.ToString()); throw ex; } }
public async Task <List <ReceiveFileResult> > ReceiveFilesAsync(string path, string fileMask, bool receiveMultiple = true) { var handledFiles = new List <ReceiveFileResult>(); using (var client = new Sftp()) { client.TransferType = _transferType; await client.ConnectAsync(_serverAddress, _port, SslMode.None); await client.LoginAsync(_userName, _password); // Get files from the specified path using the given file name mask: var items = await client.GetListAsync(path); var files = items.GetFiles(fileMask); // Ignore files that are already transfering / failed and sort the remaining by filename var sortedFiles = files.Where(f => !(f.StartsWith(".") && f.EndsWith(".tmp"))).OrderBy(f => f).ToList(); if (!receiveMultiple && (sortedFiles.Count > 1)) { // only process the first file var singleFile = sortedFiles.First(); sortedFiles = new List <string> { singleFile }; } // Try to rename the files with temporary names: foreach (var file in sortedFiles) { var result = new ReceiveFileResult { FileName = file, TempFileName = $".{Guid.NewGuid()}.tmp", Path = path, IsError = false }; try { await client.RenameAsync(Path.Combine(path, result.FileName).Replace('\\', '/'), Path.Combine(path, result.TempFileName).Replace('\\', '/')); } catch (Exception ex) { result.IsError = true; result.Message = $"Renaming the file '{result.FileName}' to '{result.TempFileName}' failed: {ex.Message}."; } handledFiles.Add(result); } await client.DisconnectAsync(); } return(handledFiles); }
/// <summary> /// Uploads the file FTP. /// </summary> /// <param name="passKey">The pass key.</param> /// <param name="server">The server.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <param name="claim">The claim.</param> /// <param name="folder">The folder.</param> /// <param name="fileName">Name of the file.</param> /// <returns>The <see cref="bool"/>.</returns> public bool UploadFileFTP(string passKey, string server, string username, string password, byte[] claim, string folder, string fileName) { if (!ValidationAndEncryptDecrypt.ValidateKey(passKey)) { return(false); } string tempDir = "C:\\DrScribe\\GatewayEDI\\" + username + "\\claims\\"; if (!Directory.Exists(tempDir)) { Directory.CreateDirectory(tempDir); } try { var arraySize = claim.GetUpperBound(0); try { if (File.Exists(tempDir + "\\" + fileName.Replace(".tmp", ".txt"))) { File.Delete(tempDir + "\\" + fileName.Replace(".tmp", ".txt")); } } catch (Exception e) { WriteEventLogEntry(e); } FileStream fs = new FileStream(tempDir + "\\" + fileName.Replace(".tmp", ".txt"), FileMode.OpenOrCreate, FileAccess.Write); fs.Write(claim, 0, arraySize); fs.Close(); SshTransferProtocolBase sshCp = new Sftp(server, username); sshCp.Password = password; sshCp.Connect(); string serverFile = fileName.Replace(".tmp", ".txt"); if (folder != string.Empty) { serverFile = "/" + folder + "/" + serverFile; } sshCp.Put(tempDir + "\\" + fileName.Replace(".tmp", ".txt"), serverFile); sshCp.Close(); sshCp.Destroy(); File.Delete(tempDir + fileName.Replace(".tmp", ".txt")); return(true); } catch { return(false); } }
public void CanUpload2FilesToRootDir() { using (var file1 = new DummyFile(1024 * 1024 * 3)) using (var file2 = new DummyFile(1024 * 1024 * 3)) { Sftp.UploadFiles(Cs, file1.FileInfo.DirectoryName, SearchPattern, true); } }
/// <summary> /// Creates a stream for reading from an SFTP resource. /// </summary> /// <param name="sftp"></param> /// <param name="channel"></param> /// <param name="handle"></param> /// <param name="length"></param> public SftpStream(Sftp sftp, byte[] handle, ulong length) : base() { this.sftp = sftp; this.handle = handle; this.length2 = (long)(this.length = length); this.reader = true; }
static void Main(string[] args) { Sftp sftp = new Sftp("[SERVER]", "[USERNAME]", string.Empty); sftp.AddIdentityFile("[Path to Private kEY]"); sftp.Connect(); sftp.Put(@"D:\temp\blog\feed.csv", "[PATH OF FILE ON SERVER]"); sftp.Delete("[PATH OF FILE ON SERVER]"); }
static void Main(string[] args) { Sftp sftp = new Sftp(); sftp.host = "12.3.456.7"; sftp.keyFilelocation = @"C:\SFTP\arquivo Chave"; sftp.DownloadAll(@"/Arquivos/Files", @"/ArquivosLidos/Files", @"C:\SFTP\download\"); sftp.uploadFile(@"C:\SFTP\upload\arquivo.txt", @"/Arquivos/UploadFiles/"); }
public SFTPUtil(String host, String user, String pass) { this.host = host; this.user = user; this.pass = pass; sftp = new Sftp(host, user, pass); sftp.Connect(); }
public SftpClient() { _sftpClient = new Sftp(); _sftpClient.OnSSHServerAuthentication += sftp_OnSSHServerAuthentication; }