protected override long PutFile(List <String> lines, string fname) { byte[] bytes = ToByteArray(lines); _sftp.Connect(_ftpCredentials.Hostname); _sftp.Login(_ftpCredentials.Username, _ftpCredentials.Password); MemoryStream stream = new MemoryStream(bytes); long nbytes = _sftp.PutFile(stream, _ftpCredentials.OutboundDir + "/" + fname); // disconnect _sftp.Disconnect(); return(nbytes); }
/// <summary> /// Connect to the host. /// </summary> public void Connect() { if (!_sftp.Connected) { _sftp.Connect(_sshConnection.Port); } }
/// <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(); } )); }
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(""); }
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 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); }
public void GetResponse() { try { _sftp.Connect(); if (_sftp.Connected) { _sftp.Get(_fileConnInfo.RemoteFilePath, _fileConnInfo.LocalFilePath); } } catch (Tamir.SharpSsh.jsch.JSchException ex) { Log.Error(ex.Message); throw; } catch (Tamir.SharpSsh.jsch.SftpException ex) { Log.Error(ex.message); throw; } catch (Exception ex) { Log.Error(ex.Message); throw; } }
/* method that get the new order from sftp server */ private void GetOrder(string filePath, IEnumerable <string> fileList) { // connection to sftp server and read all the list of file sftp.Connect(); // download the files from the given list foreach (string file in fileList.Where(file => file != "." && file != "..")) { sftp.Get(SHIPMENT_DIR + '/' + file, filePath + "\\" + file); // after download the file delete it on the server (no need it anymore) ServerDelete.Delete(sftp.Host, sftp.Username, sftp.Password, SHIPMENT_DIR + '/' + file); } sftp.Close(); }
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 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); }
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); } }
public override void Open() { DbDebugHelper.OnSftpUpdate("connecting..."); _sftp.Connect(_info.Port); DbDebugHelper.OnSftpUpdate("connected."); _db = new SftpDb(FullPath); }
/// <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 Exception Connectclient() { //connect to client try { client.Connect(loginData.Url); } catch (Exception ex) { client.Disconnect(); return(ex); } //authenticate user try { client.Authenticate(loginData.Username, loginData.Password); } catch (Exception ex) { client.Disconnect(); return(ex); } return(null); }
/// <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 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); }
/* 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(); }
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); }
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; } }
/// <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); } }
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]"); }
public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction) { ConnectionManager cSSH = getConnectionManager(connections, _SSHconnMgrName); List <KeyValuePair <string, string> > connParams = (List <KeyValuePair <string, string> >)cSSH.AcquireConnection(transaction); string host = connParams.Find(t => t.Key == "Host").Value; string username = connParams.Find(t => t.Key == "Username").Value; string password = connParams.Find(t => t.Key == "Password").Value; int port = Convert.ToInt32(connParams.Find(t => t.Key == "Port").Value); if (_operation == SSHFTPOperation.SendFiles) { ConnectionManager cSend = getConnectionManager(connections, _sendFilesSourceConnectionManagerName); string sourceFile = cSend.AcquireConnection(transaction).ToString(); SshTransferProtocolBase sshCp; sshCp = new Sftp(host, username); sshCp.Password = password; string localFile = sourceFile; string remoteFile = getRemotePathAndFile(_sendFilesDestinationDirectory, Path.GetFileName(sourceFile)); try { sshCp.Connect(); sshCp.Put(localFile, remoteFile); } catch { throw; } finally { sshCp.Close(); } } if (_operation == SSHFTPOperation.ReceiveFiles) { ConnectionManager cReceive = getConnectionManager(connections, _receiveFilesDestinationConnectionManagerName); string destinationDirectory = cReceive.AcquireConnection(transaction).ToString(); SshTransferProtocolBase sshCp; sshCp = new Sftp(host, username); sshCp.Password = password; try { sshCp.Connect(); sshCp.Get(_receiveFilesSourceFile, destinationDirectory); } catch { throw; } finally { sshCp.Close(); } } return(DTSExecResult.Success); }
public bool GetFiles() { bool status = true; Sftp sftp = new Sftp(m_sftpSite, m_sftpSiteUserName); try { // add our private key to connect // put these in the config file sftp.AddIdentityFile(@"d:\apps\RSAKeys\opensshkey"); // connect sftp.Connect(); // get a directory list ArrayList rFiles = sftp.GetFileList(m_sftpSiteRemoteFolder); foreach (string file in rFiles) { if (file.Equals(".") || file.Equals("..")) { continue; } // get the file and put in the watch folder to be processed sftp.Get(m_sftpSiteRemoteFolder + file, m_moveToProcessFolder + file); // update our database that we have downloaded the file from the server // this.updateDb( file ); // delete the file on the remote server after pulling it over // sftp.Delete(f); } sftp.Close(); status = true; } catch (Tamir.SharpSsh.jsch.SftpException se) { LogMsg("NEXCEPTION:SftpMgr::GetFile():ECaught:" + se.Message); } catch (Tamir.SharpSsh.jsch.JSchException jse) { LogMsg("NEXCEPTION:SftpMgr::GetFile():ECaught:" + jse.Message); } catch (Tamir.SharpSsh.SshTransferException ste) { LogMsg("NEXCEPTION:SftpMgr::GetFile():ECaught:" + ste.Message); } catch (SystemException se) { LogMsg("NEXCEPTION:SftpMgr::GetFile():ECaught:" + se.Message); } return(status); } // getFile()
/* * This method uploads the file to the web server from where Twilio API can access it for phone calls * It uses an external library Rebex which has a very simple implementation for SFTP */ public void Sftp() { Sftp client = new Sftp(); client.Connect("mobile.sheridanc.on.ca"); client.Login("username", "password"); // enter your SFTP credentials client.PutFile(@"E:\C#\ReminderApp\ReminderApp\bin\Debug\voice.xml", "/home/ahmasaad/public_html/Twilio/voice.xml"); //local and server paths statusLabel.Text = "Call initiating...."; statusLabel.ForeColor = Color.Blue; }
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(); }
private void UploadFile(JobInitResult jobResult, FileInfo toBeConverted) { Licensing.Key = DocumentConverterSettings.Default.SftpLicenseKey; using (var client = new Sftp()) { client.Connect(jobResult.UploadUrl, jobResult.Port); client.Login(jobResult.User, jobResult.Password); client.PutFile(toBeConverted.FullName, $"{client.GetCurrentDirectory()}{toBeConverted.Name}"); } }
private static void SubirArchivoSftp(string archivo, string rutaDestino) { Sftp client = new Sftp(sftpServidor, sftpUsuario, sftpPassword); client.Connect(); if (client.Connected) { client.Put(archivo, rutaDestino); } }
private void init_Sftp() { //fortify漏洞-----------------------------------------------add by bruce 20131220 _password = AntiXSS.GetSafeHtmlFragment(_password); //fortify漏洞-----------------------------------------------add by bruce 20131220 _sftp = new Sftp(_hostName, _userName, _password); if (_port > 0) { _sftp.Connect(_port); } }
private void OpenSFTPConnection() { _wrapper.Connect(Properties.Settings.Default.SFTPPort); if (!_wrapper.Connected) { GlobalContext.ExitApplication(string.Format("Unable to connect to FTP Server {0}:{1} using credentials user:{2}, pass:{3}", Properties.Settings.Default.SFTPHost, Properties.Settings.Default.SFTPPort, Properties.Settings.Default.SFTPUser, Properties.Settings.Default.SFTPPass), 1); } }
public void ssh_command(string type, string host, string user, string password, string command) { if (type == "list dir") { Sftp sftp = new Sftp(host, user, password); try { sftp.Connect(); ArrayList analyses = sftp.GetFileList(command); if (analyses.Count > 0) { foreach (string run in analyses) { if (run.Length > 10) { this.stdRunsList.Items.Add(run); } } count_label.Text = "Count: " + stdRunsList.Items.Count.ToString(); connected(); } } catch { ConnectionError.Visible = true; pwdBox.ResetText(); } finally { sftp.Close(); } } else if (type == "kill") { ssh.Write(command); terminalThread.CancelAsync(); } else { try { ssh = new SshStream(host, user, password); abort = false; stopWatch.Start(); terminalThread.RunWorkerAsync(); checkThread.RunWorkerAsync(); ssh.Write(command); } catch (Exception ex) { MessageBox.Show(ex.Message, "Minion - Stream Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }