private int Download(String HostName, String UserName, String Password, String remoteFilePath, String localPath) { int result = 0; Session session = null; // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Ftp, HostName = HostName, UserName = UserName, Password = Password, //HostName = "119.59.73.48", //UserName = "******", //Password = "******", // SshHostKeyFingerprint = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx" }; try { using (session = new Session()) { // Connect session.ReconnectTime = new TimeSpan(0, 0, 30); session.Open(sessionOptions); // Download files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; // transferOptions.ResumeSupport.State = TransferResumeSupportState.Smart; //transferOptions.ResumeSupport.Threshold = 1000; TransferOperationResult transferResult = null; Retry: try { transferResult = session.GetFiles(remoteFilePath, localPath, false, transferOptions); // Throw on any error transferResult.Check(); // Print results foreach (TransferEventArgs transfer in transferResult.Transfers) { Console.WriteLine("Download of {0} succeeded", transfer.FileName); } result = 0; } catch (Exception e) { Console.WriteLine("Error: {0}", e); goto Retry; // result = 1; } } } finally { if (session != null) { session.Dispose(); } } return result; }
public void ScpFile(string sourceFile, string destinationFile) { using (var session = new Session()) { session.Open(sessionOptions); var transferResult = session.GetFiles(sourceFile, destinationFile); if (transferResult.Failures.Count > 0) { throw new ApplicationException(transferResult.Failures.ToString()); } } }
private void button1_Click(object sender, EventArgs e) { try { // FolderBrowserDialog ofd = new FolderBrowserDialog(); // ofd.ShowDialog(); string folderToUpload = @"C:\Users\canpy_000\OneDrive\Documents\GitHub\groupVolumeControl(SPIRE)\Installer\Release\*"; // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = "coderguydev.com", UserName = usr, Password = pw, SshHostKeyFingerprint = "ssh-rsa 2048 0d:3c:74:bb:7f:8b:6b:3c:a0:cb:aa:e3:75:a7:30:52" }; using (Session session = new Session()) { // Connect session.Open(sessionOptions); RemoteDirectoryInfo targetServerDir = session.ListDirectory("/opt/mean/public/VolumeControlUtility/CurrentVersion/"); Console.WriteLine(targetServerDir.ToString()); // Upload files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; //transferResult = session.PutFiles(@"d:\toupload\*", "/home/user/", false, transferOptions); transferResult = session.PutFiles(folderToUpload, "/opt/mean/public/VolumeControlUtility/CurrentVersion/", false, transferOptions); // Throw on any error transferResult.Check(); // Print results foreach (TransferEventArgs transfer in transferResult.Transfers) { Console.WriteLine("Upload of {0} succeeded", transfer.FileName); } } } catch (Exception err) { Console.WriteLine("Error: {0}", err); } }
public List<String> GetRSLList(string winSCPPath, string rslFilePath, string windowsOutput) { List<String> rslList = null; String windowsOutputPath = windowsOutput + @"GFT_DiffTool_Output\"; if (File.Exists(windowsOutputPath + "rsls.txt")) { rslList = new List<string>(); string line; try { using (var reader = File.OpenText(windowsOutputPath + "rsls.txt")) { rslList = new List<String>(); while ((line = reader.ReadLine()) != null) { rslList.Add(line); } } } catch (Exception e) { throw new Exception(String.Format("Could not open file: {0}\n\n{1}", windowsOutputPath + "rsls.txt", e.Message)); } } else { using (Session session = new Session()) { try { session.ExecutablePath = winSCPPath; session.Open(winSCPSessionOptions); } catch (Exception e) { throw new Exception("Could not open a WinSCP session!\n\n" + e.Message); } try { DirectoryInfo dir = new DirectoryInfo(windowsOutputPath); if (!dir.Exists) { dir.Create(); } } catch (Exception e) { throw new Exception(String.Format("Could not create the following directory: {0}\n\n{1}", windowsOutputPath, e.Message)); } string rslFile = rslFilePath.Split('/')[rslFilePath.Split('/').Length - 1]; TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; try { transferResult = session.GetFiles(rslFilePath, windowsOutputPath + rslFile, false, transferOptions); transferResult.Check(); } catch (Exception e) { throw new Exception(String.Format("Could not transfer the file \"{0}\" in Unix server to the Windows output as {1}\n\n{2}", rslFilePath, windowsOutputPath + rslFile, e.Message)); } try { if (File.Exists(windowsOutputPath + "rsls.txt")) { File.Delete(windowsOutputPath + "rsls.txt"); } } catch (Exception e) { throw new Exception(String.Format("Could not delete the following file: {0}\n\n{1}", windowsOutputPath + "rsls.txt", e.Message)); } try { string line; using (var reader = File.OpenText(windowsOutputPath + rslFile)) using (var sw = new StreamWriter(windowsOutputPath + "rsls.txt")) { rslList = new List<String>(); while ((line = reader.ReadLine()) != null) { line = line.Trim(); if (!String.IsNullOrEmpty(line) && !line.StartsWith("//")) { String rsl = line.Split(' ')[0].Split('\t')[0]; if (rsl.EndsWith(".rsl")) { rslList.Add(rsl); sw.WriteLine(rsl); } } } } } catch (Exception e) { throw new Exception(String.Format("Could not create the following file: {0}\n\n{1}", windowsOutputPath + "rsls.txt", e.Message)); } try { File.Delete(windowsOutputPath + rslFile); } catch (Exception e) { throw new Exception(String.Format("Could not delete the following file: {0}\n\n{1}", windowsOutputPath + rslFile, e.Message)); } } } return rslList; }
public static int Main() { try { Helper.AddtoLogFile("-------Program Starts Running----------"); // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = ConfigurationManager.AppSettings["HostName"].ToString(), UserName = ConfigurationManager.AppSettings["UserName"].ToString(), Password = ConfigurationManager.AppSettings["Password"].ToString(), SshHostKeyFingerprint = ConfigurationManager.AppSettings["SshHostKeyFingerprint"].ToString() }; using (Session session = new Session()) { // Connect session.Open(sessionOptions); Helper.AddtoLogFile("-------Session instance successfully Created.----------"); List<SFTPmap> ImportFilePaths = DBProvider.Instance.DownloadParameters(); Helper.AddtoLogFile("All File Paths are download."); foreach (SFTPmap item in ImportFilePaths) { if (!string.IsNullOrEmpty(item.FolderNameAlias)) { try { Helper.AddtoLogFile("Looping for " + item.FolderNameAlias); Helper.AddtoLogFile("File Path " + item.FilePath); string LocalPath = item.FilePath; string RemotePath = ConfigurationManager.AppSettings["RemotePath"].ToString() + item.FolderNameAlias; RemoteDirectoryInfo directory = session.ListDirectory(RemotePath); LocalPath = LocalPath + item.FolderName + "\\"; foreach (RemoteFileInfo fileInfo in directory.Files) { if (!Directory.Exists(LocalPath)) { Directory.CreateDirectory(LocalPath); } if (!File.Exists(LocalPath + fileInfo.Name)) { try { if (fileInfo.Name != "..") { session.GetFiles(RemotePath + "/" + fileInfo.Name, LocalPath + fileInfo.Name).Check(); Console.WriteLine("File Tranfer successful from " + RemotePath + "/" + fileInfo.Name + " to " + LocalPath + fileInfo.Name); Helper.AddtoLogFile("File Tranfer successful from " + RemotePath + "//" + fileInfo.Name + " to " + LocalPath + fileInfo.Name); } } catch (Exception Ex) { Console.WriteLine("Error Occurse:" + Ex.ToString()); Helper.AddtoLogFile("Error Occurse:" + Ex.ToString()); } } } // Upload files - //TransferOptions transferOptions = new TransferOptions(); //transferOptions.TransferMode = TransferMode.Binary; //TransferOperationResult transferResult; //transferResult = session.GetFiles(RemotePath + "*", LocalPath, false, transferOptions); //// Throw on any error //transferResult.Check(); //// Print results //foreach (TransferEventArgs transfer in transferResult.Transfers) //{ // Console.WriteLine("Download of {0} succeeded", transfer.FileName); // Helper.AddtoLogFile("Download of " + transfer.FileName + " succeeded"); //} } catch (Exception ex) { Helper.AddtoLogFile("Error:" + ex.ToString()); } } } } Helper.AddtoLogFile("-------Program End----------"); return 0; } catch (Exception e) { Console.WriteLine("Error: {0}", e); Helper.AddtoLogFile("Error:" + e.ToString()); Helper.AddtoLogFile("-------Program End----------"); return 1; } }
public List<String> GetHeaders(string winSCPPath, string csvDirectory, string csvFile, string rslReport, string parameters, string windowsOutputPath) { List<String> headerList = null; String reportHeaderFileName = rslReport + "-headers.txt"; using (Session session = new Session()) { try { session.ExecutablePath = winSCPPath; session.Open(winSCPSessionOptions); } catch (Exception e) { throw new Exception("Could not open a WinSCP session!\n\n" + e.Message); } try { DirectoryInfo dir = new DirectoryInfo(windowsOutputPath); if (!dir.Exists) { dir.Create(); } } catch (Exception e) { throw new Exception(String.Format("Could not create the following directory: {0}\n\n{1}", windowsOutputPath, e.Message)); } String newCsvFileName = rslReport + ".csv"; TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; try { transferResult = session.GetFiles(csvDirectory + csvFile, windowsOutputPath + newCsvFileName, false, transferOptions); transferResult.Check(); } catch (Exception e) { throw new Exception(String.Format("Could not transfer the file \"{0}\" in Unix server to the Windows output as {1}\n\n{2}", csvDirectory + csvFile, windowsOutputPath + newCsvFileName, e.Message)); } try { session.ExecuteCommand("rm -f " + csvDirectory + csvFile); } catch (Exception e) { throw new Exception(String.Format("Could not execute de command: rm {0}\n\n{1}", csvDirectory + csvFile, e.Message)); } if (File.Exists(windowsOutputPath + newCsvFileName)) { headerList = new List<string>(); string line; try { using (var reader = File.OpenText(windowsOutputPath + newCsvFileName)) { line = reader.ReadLine(); if (line != null) { line = line.Replace("\"", ""); headerList = line.Split(',').ToList(); } } } catch (Exception e) { throw new Exception(String.Format("Could not open file: {0}\n\n{1}", windowsOutputPath + newCsvFileName, e.Message)); } try { File.Delete(windowsOutputPath + newCsvFileName); } catch (Exception e) { throw new Exception(String.Format("Could not delete the following file: {0}\n\n{1}", windowsOutputPath + newCsvFileName, e.Message)); } } using (var sw = new StreamWriter(windowsOutputPath + reportHeaderFileName)) { foreach (string s in headerList) { sw.WriteLine(s); } } } return headerList; }
/// <summary> /// Downloads audio from the robot /// </summary> /// <param name="sender"> object that called the method </param> /// <param name="e"> any additional arguments </param> void bgWorker_DoWork(object sender, DoWorkEventArgs e) { // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = ipString, UserName = "******", Password = "******", SshHostKeyFingerprint = "ssh‐rsa 20487c:48:34:e3:c0:7a:92:8e:2f:95:79:0e:12:69:79:e7", }; using (Session session = new Session()) { // tell library path to the winSCP executable session.ExecutablePath = System.IO.Directory.GetCurrentDirectory() + "\\winSCPexe.exe"; // Connect session.Open(sessionOptions); //Set up transfer TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; // generate a file based on date and time string time = Convert.ToString(DateTime.UtcNow.ToFileTime()); string destination = "C:\\NAOcam\\" + "NAO_Audio_" + time + ".ogg"; // download files TransferOperationResult transferResult; transferResult = session.GetFiles("/home/nao/temp.ogg", @destination, true, transferOptions); // Throw on any error transferResult.Check(); } }
private void button1_Click(object sender, EventArgs e) { using (WinSCP.Session session = new WinSCP.Session()) { fingerprint = session.ScanFingerprint(sessionOptions, "MD5"); sessionOptions.SshHostKeyFingerprint = fingerprint; session.Open(sessionOptions); TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; string sourcePath = @"c:\test\setup-x86_64.exe"; string destinationPath = @"/c:/MalCode/"; string textBxInput = this.txtBxFilename.Text; if (!string.IsNullOrEmpty(textBxInput)) { sourcePath = @"c:\test\" + textBxInput; } TransferOperationResult transferResult; transferResult = session.PutFiles(sourcePath, destinationPath, false, transferOptions); transferResult.Check(); foreach (TransferEventArgs transfer in transferResult.Transfers) { System.Console.WriteLine("Upload of {0} succeeded ", transfer.FileName); } } }
public static void Sync() { var optoins = new SessionOptions() { Protocol = Protocol.Ftp, FtpSecure = WinSCP.FtpSecure.ExplicitTls, HostName = Config.FTP_HOSTNAME, PortNumber = Config.FTP_PORT, UserName = Config.FTP_USER, Password = Config.FTP_PWD, }; using (var session = new Session()) { Logger.Debug("About to try to connect to the TRTH server...",typeof(FTPSynchroniser)); session.Open(optoins); Logger.Debug("Synchronising directories...",typeof(FTPSynchroniser)); var result = session.SynchronizeDirectories(SynchronizationMode.Local, Config.DIR_SYNC_TO, Config.DIR_REMOTE, false); Logger.Debug(string.Format("FTP Sync Result = {0}", result), typeof (FTPSynchroniser)); foreach (var file in result.Downloads) Logger.DebugFormat(typeof (FTPSynchroniser), "Downloaded {0}", file); } }
private ArrayList ListFiles(String HostName, String UserName, String Password, String remotePath) { //int result = 0; Session session = null; ArrayList fileNameList = new ArrayList(); try { // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Ftp, HostName = HostName, UserName = UserName, Password = Password, //HostName = "119.59.73.48", //UserName = "******", //Password = "******", // SshHostKeyFingerprint = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx" }; using (session = new Session()) { // Connect session.Open(sessionOptions); RemoteDirectoryInfo dirInfo = session.ListDirectory(remotePath); foreach (RemoteFileInfo file in dirInfo.Files) { if (!file.IsDirectory) { fileNameList.Add(file.Name); } // Console.WriteLine("File Name: {0},LastWriteTime: {1},IsDirectory: {2},File Length: {3},", file.Name, file.LastWriteTime, file.IsDirectory, file.Length); } } // return 0; } catch (Exception e) { Console.WriteLine("Error: {0}", e); // return 1; } finally { if (session != null) { session.Dispose(); } } return fileNameList; }
public static int Main() { try { // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Scp, HostName = ConfigurationManager.AppSettings["hostName"], PortNumber = Convert.ToInt32(ConfigurationManager.AppSettings["portNumber"]), UserName = ConfigurationManager.AppSettings["userName"], Password = ConfigurationManager.AppSettings["storedProcedure"], SshHostKeyFingerprint = ConfigurationManager.AppSettings["SshHostKeyFingerprint"], SshPrivateKeyPath = ConfigurationManager.AppSettings["SshPrivateKeyPath"], }; using (Session session = new Session()) { string fileName = ConfigurationManager.AppSettings["fileName"]; string localPath = ConfigurationManager.AppSettings["localPath"]; string remotePath = ConfigurationManager.AppSettings["remotePath"]; // Connect session.Open(sessionOptions); Console.WriteLine("## SCP Host Connection Success"); string getFrom = localPath + fileName; string putToo = remotePath; TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; transferResult = session.PutFiles(getFrom, remotePath, false, transferOptions); transferResult.Check(); foreach (TransferEventArgs transfer in transferResult.Transfers) { Console.WriteLine("Upload of {0} succeeded", transfer.FileName); Console.WriteLine("Upload of {0} succeeded", transfer.Destination); Console.WriteLine("Response: ", transfer.Error); } Console.WriteLine("## SCP Host Transfer Success"); System.Environment.Exit(0); } return 1; } catch (Exception e) { Console.WriteLine("Error: {0}", e); Console.Read(); return 1; } }
public int Execute() { try { // Setup session options String hostname = Params.sftpauth.Split('@')[1]; String username = Params.sftpauth.Split(':')[0]; String password = Params.sftpauth.Split('@')[0].Split(':')[1]; SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = hostname, UserName = username, Password = password, SshHostKeyFingerprint = Params.fingerprint }; //Console.WriteLine("Host {0} user {1} pw {2}", hostname, username, password); using (Session session = new Session()) { session.Open(sessionOptions); TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; if (Params.RecordInitialFileList.Equals("true", StringComparison.InvariantCultureIgnoreCase)) { RecordInitialFileList(Params.DownloadedFiles +"_" + System.Guid.NewGuid().ToString() + ".txt", ListFiles(session, Params.RemoteDir)); session.Close(); return 0; } List<FileObject> newfiles = GetNewFileNames(ReadLocalFileNames(Params.DownloadedFiles), ListFiles(session, Params.RemoteDir)); foreach (FileObject item in newfiles) { DownLoadFile(session, transferOptions, Params.RemoteDir + item.Name, Params.LocalDir); AppendToFile(Params.DownloadedFiles, item.Name); } session.Close(); } return 0; } catch (Exception e) { Console.WriteLine("Error: {0}", e); Logger.Error(e.Message); throw e; } }
public static void WriteConfig(string HostName, string UserName, string Password, string file) { try { // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Scp, HostName = HostName, UserName = UserName, Password = Password, GiveUpSecurityAndAcceptAnySshHostKey = true }; using (Session session = new WinSCP.Session()) { Form1 FormHandle = new Form1(); // Connect session.Open(sessionOptions); // Upload files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; transferResult = session.PutFiles(file, "/config/cgminer.conf", false, transferOptions); // Throw on any error transferResult.Check(); // Print results foreach (TransferEventArgs transfer in transferResult.Transfers) { Form1.gui.UpdateTextBox("Upload of " + transfer.FileName + " succeeded"); } } } catch (Exception e) { Console.WriteLine("Error: {0}", e); MessageBox.Show("ERROR: " + e, "AntMiner Controller", MessageBoxButtons.YesNo, MessageBoxIcon.Question); } }
private void SFTPDownload(SessionOptions so, string OPFolderName, List <string> IPDir, List <string> OPdir) { try { session = new WinSCP.Session(); session.Open(so); for (int i = 0; i < IPDir.Count; i++) { string localPath = $"{OPFolderName}{OPdir[i]}"; localPath = DeserialiseXMLFromStr(localPath); Directory.CreateDirectory(localPath); string remotePath = IPDir[i]; remotePath = DeserialiseXMLFromStr(remotePath); // Enumerate files and directories to download IEnumerable <RemoteFileInfo> fileInfos = session.EnumerateRemoteFiles(remotePath, null, EnumerationOptions.EnumerateDirectories | EnumerationOptions.AllDirectories); foreach (RemoteFileInfo fileInfo in fileInfos) { string localFilePath = session.TranslateRemotePathToLocal(fileInfo.FullName, remotePath, localPath); if (fileInfo.IsDirectory) { // Create local subdirectory, if it does not exist yet Directory.CreateDirectory(localFilePath); } else { WriteToLogBox($"Downloading file {fileInfo.FullName}..."); // Download file string remoteFilePath = session.EscapeFileMask(fileInfo.FullName); TransferOperationResult transferResult = session.GetFiles(remoteFilePath, localFilePath); if (!transferResult.IsSuccess) { WriteToLogBox($"Error downloading file {fileInfo.FullName}: {transferResult.Failures[0].Message}"); } } } } } catch (Exception e) { WriteToLogBox($"Error: {e}"); } finally { session.Close(); session.Dispose(); GC.Collect(); } }
// --------------------------------------------------------[] private static Response<MipTestConnectionResult> DoTestConnection( string password ) { try { var sessionOptions = SessionOptions( password ); using( var session = new Session() ) { session.Open( sessionOptions ); } } catch( Exception exception ) { return new Response< MipTestConnectionResult >( exception ); } return new Response< MipTestConnectionResult > { Result = new MipTestConnectionResult { Value = true } }; }
public bool Connect() { try { if (!Connected) { _session.Open(_sessionOptions); } return(true); } catch (Exception ex) { return(false); } }
// --------------------------------------------------------[] private static RemoteFileInfoCollection GetRemoteDirFiles( string remoteDir ) { try { using( var session = new Session() ) { var sessionOptions = SessionOptions(); session.Open( sessionOptions ); return session.ListDirectory( remoteDir ).Files; } } catch( Exception exception ) { if( !exception.Message.Contains( "Error listing directory" ) ) { throw; } } return new RemoteFileInfoCollection(); }
public static Tuple <int, string> m_fTestSFTP(LogTyper lt = LogTyper.LogLogger) { int status = 0; string msg = string.Empty; try { ///链接(S)FTP SessionOptions sessionOptions = new SessionOptions(); sessionOptions.Protocol = (Protocol)(int.Parse(m_cConfigConstants.m_sProtocol)); sessionOptions.HostName = m_cConfigConstants.m_sIP; sessionOptions.PortNumber = int.Parse(m_cConfigConstants.m_sPort); sessionOptions.UserName = m_cConfigConstants.m_sUa; sessionOptions.FtpMode = (FtpMode)(int.Parse(m_cConfigConstants.m_sMode)); if (!string.IsNullOrWhiteSpace(m_cConfigConstants.m_sPwd)) { sessionOptions.Password = m_cConfigConstants.m_sPwd; } if (!string.IsNullOrWhiteSpace(m_cConfigConstants.m_sKey)) { sessionOptions.SshHostKeyFingerprint = m_cConfigConstants.m_sKey; } ///放入测试 using (WinSCP.Session session = new WinSCP.Session()) { session.Open(sessionOptions); status = 0; msg = "(S)FTP测试链接成功"; } } catch (Exception ex) { status = 1; msg = ex.Message; object m_oObject = new { title = "(S)FTP测试", ex = ex }; Log.Instance.Debug(m_oObject); } return(new Tuple <int, string>(status, msg)); }
public static int Main(string[] args) { try { // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = ConfigurationManager.AppSettings["HostName"].ToString(), UserName = ConfigurationManager.AppSettings["UserName"].ToString(), Password = ConfigurationManager.AppSettings["Password"].ToString(), SshHostKeyFingerprint = ConfigurationManager.AppSettings["SshHostKeyFingerprint"].ToString() }; string LocalPath = ConfigurationManager.AppSettings["LocalPath"].ToString(); string RemotePath = ConfigurationManager.AppSettings["RemotePath"].ToString(); using (Session session = new Session()) { // Connect session.Open(sessionOptions); // Upload files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; transferResult = session.PutFiles(LocalPath + "*", RemotePath, false, transferOptions); // Throw on any error transferResult.Check(); // Print results foreach (TransferEventArgs transfer in transferResult.Transfers) { Console.WriteLine("Upload of {0} succeeded", transfer.FileName); } } return 0; } catch (Exception e) { Console.WriteLine("Error: {0}", e); Console.ReadKey(); return 1; } }
private void button1_Click(object sender, EventArgs e) { SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = "sftp.maitsa.com", UserName = "******", SshHostKeyFingerprint = null, //RUTA DEL ARCHIVO DE LA KEY PARA CONEXION AL SFTOP SshPrivateKeyPath = @"C:\NOVOTIC\CLIENTES\IDRTEXT\SFTP MAITSA\private-key.ppk", }; using (Session session = new Session()) { session.ScanFingerprint(sessionOptions, "SHA-256"); sessionOptions.SshHostKeyFingerprint = session.ScanFingerprint(sessionOptions, "SHA-256"); Console.WriteLine(session.ScanFingerprint(sessionOptions, "SHA-256")); session.Open(sessionOptions); string xmlLogPath = session.XmlLogPath; object p = xmlLogPath; Console.WriteLine(p.ToString()); TransferOptions oTransferOptions = new TransferOptions(); oTransferOptions.TransferMode = WinSCP.TransferMode.Binary; TransferOperationResult transferResult; transferResult = session.GetFiles("/sftp-maitsa/customs-broker-integration/api/prod/idrtext/processed/PO626/*", @"C:\NOVOTIC\CLIENTES\IDRTEXT\SFTP MAITSA\", false, oTransferOptions); transferResult.Check(); foreach (TransferEventArgs transfer in transferResult.Transfers) { Console.WriteLine("Download of {0} succeeded", transfer.FileName); } } }
private async Task UploadsFTPwitWinSCP() { cts = new CancellationTokenSource(); int delayTimeMilliseconds = 1000; await Task.Delay(delayTimeMilliseconds); SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = "182.23.64.244", UserName = "******", Password = "******", SshHostKeyFingerprint = "ssh-rsa 2048 Lut0jkyMwlKFD3bCRZsDduOMArHdfcpxTRaSab5EK68=" //SshPrivateKeyPath = keyPath }; using (WinSCP.Session session = new WinSCP.Session()) { session.FileTransferProgress += SessionFileTransferProgress; // Connect session.Open(sessionOptions); richTextBox1.AppendText("\n" + "Transmitting Data..."); // Upload files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; transferResult = session.PutFiles(@"" + txt_FileTo.Text + "\\*.xml", "/AWB/", false, transferOptions); // Throw on any error transferResult.Check(); foreach (TransferEventArgs transfer in transferResult.Transfers) { jumlahSucces++; } } richTextBox1.AppendText("\n" + "Finish Upload File \n" + "Total :" + jumlahSucces + " Files Succesfully Uploaded in sFTP");; }
private void button1_Click_3(object sender, EventArgs e) { using (WinSCP.Session session = new WinSCP.Session()) { fingerprint = session.ScanFingerprint(sessionOptions, "MD5"); sessionOptions.SshHostKeyFingerprint = fingerprint; session.Open(sessionOptions); TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; session.RemoveFiles(@"/c:/MalCode/WinForm.exe"); //transferResult.Check(); //foreach (TransferEventArgs transfer in transferResult.Transfers) //{ // System.Console.WriteLine("Upload of {0} succeeded ", transfer.FileName); //} } }
private void btnDownload_Click(object sender, EventArgs e) { using (WinSCP.Session session = new WinSCP.Session()) { fingerprint = session.ScanFingerprint(sessionOptions, "MD5"); sessionOptions.SshHostKeyFingerprint = fingerprint; session.Open(sessionOptions); TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; transferResult = session.GetFiles(@"/c:/MalCode/HiWinForm.exe", @"c:\test\", false, transferOptions); transferResult.Check(); foreach (TransferEventArgs transfer in transferResult.Transfers) { System.Console.WriteLine("Upload of {0} succeeded ", transfer.FileName); } } }
private void btnFileExists_Click(object sender, EventArgs e) { using (WinSCP.Session session = new WinSCP.Session()) { fingerprint = session.ScanFingerprint(sessionOptions, "MD5"); sessionOptions.SshHostKeyFingerprint = fingerprint; session.Open(sessionOptions); TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; if (session.FileExists(@"/c:/sbmon_complete")) { MessageBox.Show("File {0} exists", @"/c:/sbmon_complete"); } else { MessageBox.Show("File does not exist"); } } }
void synchroniseAllFiles() { Console.WriteLine("Upload files started..."); ServicePointManager.ServerCertificateValidationCallback = (s, certificate, chain, sslPolicyErrors) => true; try { using (WinSCP.Session session = new WinSCP.Session()) { session.FileTransferProgress += SessionFileTransferProgress; // Connect session.Open(_sessionOptions); string localDir = _rootPath; WinSCP.SynchronizationResult result = session.SynchronizeDirectories(WinSCP.SynchronizationMode.Remote, localDir, "Ents/Logs", false); if (result.IsSuccess) { Console.WriteLine("Directories successfully synchronised!"); } else { for (int i = 0; i < result.Failures.Count; i++) { Console.WriteLine("Error: {0}", result.Failures[i].Message); } } } } catch (Exception excp) { Console.WriteLine("Exception: {0}, {1}", excp.Message, excp.StackTrace); } }
public int removeFTPFiles(String HostName, String UserName, String Password, String remoteFilePath) { int result = 0; Session session = null; try { // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Ftp, HostName = HostName, UserName = UserName, Password = Password, //HostName = "119.59.73.48", //UserName = "******", //Password = "******", // SshHostKeyFingerprint = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx" }; using (session = new Session()) { // Connect session.Open(sessionOptions); // Remove files RemovalOperationResult removalResult = null; removalResult = session.RemoveFiles(remoteFilePath); // Throw on any error removalResult.Check(); // Print results foreach (RemovalEventArgs removal in removalResult.Removals) { Console.WriteLine("Remove of {0} succeeded", removal.FileName); } } result = 0; } catch (Exception e) { Console.WriteLine("Error: {0}", e); result = 1; } finally { if (session != null) { session.Dispose(); } } return result; }
public static int Main(string[] args) { //connectToDb(); Console.WriteLine("Let's reorganize some files!"); try { // Setup session SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = ConfigurationManager.AppSettings["hostName"], UserName = ConfigurationManager.AppSettings["userName"], Password = ConfigurationManager.AppSettings["password"], SshHostKeyFingerprint = ConfigurationManager.AppSettings["sshHostKeyFingerprint"] }; using (Session session = new Session()) { // Connect session.Open(sessionOptions); Console.WriteLine("Connected to session."); // TODO: make source path editable String path = "/home/cetus/shared/HARP Deployment and Recovery Files"; Console.WriteLine("Source path is {0}", path); RemoteDirectoryInfo directory = session.ListDirectory(path); List<RemoteFileInfo> sourceFiles = new List<RemoteFileInfo>(); // to hold file names that will be sorted foreach (RemoteFileInfo fileInfo in directory.Files) { if (!(Regex.IsMatch(fileInfo.Name, @"^\.")) && !(Regex.IsMatch(fileInfo.Name, @"^\d")) && fileInfo.IsDirectory) { sourceFiles.Add(fileInfo); } } Console.WriteLine("Files found, processing and sorting."); // Sort files alphabetically sourceFiles.Sort(delegate (RemoteFileInfo x, RemoteFileInfo y) { if (x.Name == null && y.Name == null) return 0; else if (x.Name == null) return -1; else if (y.Name == null) return 1; else return y.Name.CompareTo(x.Name); }); // Destination path of where the directories holding the targets willbe temporarily held until transferred back to session String destPath = "C:/Users/Harp/Desktop/temp"; // TODO: make destination path editable Console.WriteLine("Destination path is {0}", destPath); FileTransferManager fileTransfer = new FileTransferManager(path, destPath, session); Boolean doneTargets = false; while (!doneTargets) { Console.WriteLine("Create new target? (Y/N)"); String response = Console.ReadLine(); switch (response) { case "Y": fileTransfer.createNewTarget(); break; case "N": doneTargets = true; break; default: break; } } Boolean done = false; int i = 0; while (!done) { Console.WriteLine("[E]xit [Y]es [Any key to continue]"); RemoteFileInfo aSourceFile = sourceFiles[i]; Console.WriteLine("Would you like to organize {0}(Y/N)?", aSourceFile.Name); String answer = Console.ReadLine(); switch (answer) { case "Y": fileTransfer.setCurrentTransferSrc(aSourceFile); // set the path to the current source fileTransfer.checkDestinationDir(); // set path to destination of transfer fileTransfer.setTargetSrcPaths(); // set the paths of the targets fileTransfer.configureTargetRules(); // configure target rules fileTransfer.transferTargets(); // transfer the target files break; case "N": break; case "E": done = true; break; default: continue; } i++; } return 0; } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Error: {0}", e); return 1; } }
private int Upload(String HostName, String UserName, String Password, String remotePath, String localFilePath) { int result = 0; Session session = null; try { // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Ftp, HostName = HostName, UserName = UserName, Password = Password, //HostName = "119.59.73.48", //UserName = "******", //Password = "******", // SshHostKeyFingerprint = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx" }; using (session = new Session()) { // Connect session.Open(sessionOptions); // upload files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Ascii; TransferOperationResult transferResult = null; transferResult = session.PutFiles(localFilePath, remotePath, false, transferOptions); // Throw on any error transferResult.Check(); // Print results foreach (TransferEventArgs transfer in transferResult.Transfers) { Console.WriteLine("Upload of {0} succeeded", transfer.FileName); } } result = 0; } catch (Exception e) { Console.WriteLine("Error: {0}", e); result = 1; } finally { if (session != null) { session.Dispose(); } } return result; }
// --------------------------------------------------------[] private static void SftpUploadFiles( string localPath, string remotePath ) { using( var session = new Session() ) { var sessionOptions = SessionOptions(); var transferOptions = TransferOptions(); session.Open( sessionOptions ); var transferResult = session.PutFiles( localPath, remotePath, false, transferOptions ); transferResult.Check(); } }
private bool FtpUploadAll(string localSaveFolder) { var resultFlag = true; if (!ConfigUtil.Ftp2Bi) { ALogger.LogInfo("FTP2BI Setting is false"); return true; } try { var sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, GiveUpSecurityAndAcceptAnySshHostKey = true, HostName = ConfigUtil.GetFtpHost(), UserName = ConfigUtil.EDWFTPUser, Password = ConfigUtil.EDWFTPPassword, PortNumber = ConfigUtil.EDWFTPPort }; using (var session = new Session { ExecutablePath = Path.Combine("winscp", "WinSCP.exe"), Timeout = TimeSpan.FromSeconds(30), }) { try { session.Open(sessionOptions); var remoteFilePath = ""; var archiveFolder = Path.Combine(localSaveFolder, "Archive"); foreach (var fileInfo in GetFTPFileList(localSaveFolder)) { try { remoteFilePath = Path.Combine(ConfigUtil.GetFtpPath(), fileInfo.Name).Replace('\\', '/'); var result = session.PutFiles(fileInfo.FullName, remoteFilePath); if (result.IsSuccess) { ALogger.LogInfo("successfully upload file, {0} to {1}", fileInfo.FullName, remoteFilePath); var newPath = Path.Combine(archiveFolder, fileInfo.Name); if (!Directory.Exists(archiveFolder)) Directory.CreateDirectory(archiveFolder); try { File.Move(fileInfo.FullName, newPath); } catch (Exception) { } } else { ALogger.LogError("failed to upload file, {0} to {1}", fileInfo.FullName, remoteFilePath); foreach (var failed in result.Failures) { ALogger.LogError("\t\t###{0}###", failed); } } } catch (Exception ex) { ALogger.LogError("failed to upload file, {0} with error {1}", remoteFilePath, ex.Message); resultFlag = false; } } } catch (Exception ex) { ALogger.LogError("FtpUpload: exception {0}", ex.Message); resultFlag = false; } } } catch (Exception e) { ALogger.LogError("FtpUpload(): exception, {0}", e.Message); resultFlag = false; } return resultFlag; }
public static void synchro(string typeSynchro) { try { string repertoireLocal = FSFLauncherCore.cheminARMA3 + @"\@FSF\"; string repertoireDistant=""; fenetrePrincipale.textBox11.Text = "Synchronisation procedure " + typeSynchro + " en cours :" + Environment.NewLine; fenetrePrincipale.textBox11.Text += "────────────────────────────" + Environment.NewLine; fenetrePrincipale.textBox11.Text += Environment.NewLine + "IMPORTANT : " + Environment.NewLine + "Pour stopper la synchronisation en cours, il vous faut Arreter le processus WinSCP.exe en faisant appel à la combinaison de touche" + Environment.NewLine + " CTRL + MAJ + ESC (onglet processus)." + Environment.NewLine; // Setup session options SessionOptions sessionOptions = new SessionOptions { }; switch (typeSynchro) { case "beta": SessionOptions sessionOptions1 = new SessionOptions { Protocol = Protocol.Ftp, HostName = constCheminFTP, UserName = constLoginFTP, Password = constMdpFTP }; repertoireDistant = "/@FSF/"; sessionOptions = sessionOptions1; break; case "officielle": SessionOptions sessionOptions2 = new SessionOptions { Protocol = Protocol.Ftp, HostName = constCheminFTP, UserName = constLoginFTP, Password = constMdpFTP }; repertoireDistant = "/@FSF_OFFICIELLE/"; sessionOptions = sessionOptions2; break; } using (Session session = new Session()) { switch (typeSynchro) { default: Directory.CreateDirectory(repertoireLocal + "@TEMPLATE"); Directory.CreateDirectory(repertoireLocal + "@CLIENT"); Directory.CreateDirectory(repertoireLocal + "@TEST"); Directory.CreateDirectory(repertoireLocal + "@UNITS"); Directory.CreateDirectory(repertoireLocal + "@MATERIEL"); Directory.CreateDirectory(repertoireLocal + "@ISLANDS"); Directory.CreateDirectory(repertoireLocal + "@FRAMEWORK"); break; } // Will continuously report progress of synchronization session.FileTransferred += FileTransferred; session.FileTransferProgress += FileTransferProgress; // session log session.DebugLogPath = FSFLauncherCore.cheminARMA3 + @"\userconfig\FSF-LauncherA3\log.txt"; // Connect session.Open(sessionOptions); TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; SynchronizationResult synchronizationResult; fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "**** SYNCHRO @TEMPLATE ******" + Environment.NewLine); synchronizationResult = session.SynchronizeDirectories( SynchronizationMode.Local, repertoireLocal + "@TEMPLATE", repertoireDistant + "@TEMPLATE", true, false, SynchronizationCriteria.Size); effaceProgressBar(); fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "**** SYNCHRO @FRAMEWORK ******" + Environment.NewLine); synchronizationResult = session.SynchronizeDirectories( SynchronizationMode.Local, repertoireLocal + "@FRAMEWORK", repertoireDistant + "@FRAMEWORK", true, false, SynchronizationCriteria.Size); effaceProgressBar(); fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "**** SYNCHRO @CLIENT ******" + Environment.NewLine); synchronizationResult = session.SynchronizeDirectories( SynchronizationMode.Local, repertoireLocal + "@CLIENT", repertoireDistant + "@CLIENT", true, false, SynchronizationCriteria.Size); effaceProgressBar(); fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "**** SYNCHRO @TEST ******" + Environment.NewLine); synchronizationResult = session.SynchronizeDirectories( SynchronizationMode.Local, repertoireLocal + "@TEST", repertoireDistant + "@TEST", true, false, SynchronizationCriteria.Size); effaceProgressBar(); fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "**** SYNCHRO @UNITS ******" + Environment.NewLine); synchronizationResult = session.SynchronizeDirectories( SynchronizationMode.Local, repertoireLocal + "@UNITS", repertoireDistant + "@UNITS", true, false, SynchronizationCriteria.Size); effaceProgressBar(); fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "**** SYNCHRO @MATERIEL ******" + Environment.NewLine); synchronizationResult = session.SynchronizeDirectories( SynchronizationMode.Local, repertoireLocal + "@MATERIEL", repertoireDistant + "@MATERIEL", true, false, SynchronizationCriteria.Size); effaceProgressBar(); fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "**** SYNCHRO @ISLANDS ******" + Environment.NewLine); synchronizationResult = session.SynchronizeDirectories( SynchronizationMode.Local, repertoireLocal + "@ISLANDS", repertoireDistant + "@ISLANDS", true, false, SynchronizationCriteria.Size); effaceProgressBar(); // Throw on any error synchronizationResult.Check(); fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "->fichier " + repertoireLocal + "Organisation.txt mis a jour." + Environment.NewLine); downloadnouvelleVersion("Organisation.txt", FSFLauncherCore.constCheminFTP + repertoireDistant, FSFLauncherCore.constLoginFTP, FSFLauncherCore.constMdpFTP, repertoireLocal); downloadnouvelleVersion("version.xml", FSFLauncherCore.constCheminFTP + repertoireDistant, FSFLauncherCore.constLoginFTP, FSFLauncherCore.constMdpFTP, repertoireLocal); } } catch (Exception z) { fenetrePrincipale.textBox11.Text += "Error: " + z; } fenetrePrincipale.textBox11.AppendText(Environment.NewLine + "_______________" + Environment.NewLine); fenetrePrincipale.textBox11.Text += "Fin de la synchro"; Interface.AlerteVersionArma3(); Interface.AlerteVersionSynchro(); }
public DataTable Load() { StringBuilder requestUri = new StringBuilder(); SessionOptions sessionOptions = new SessionOptions { HostName = Server, UserName = Username, Password = Password, }; sessionOptions.Protocol = WinSCP.Protocol.Ftp; if (!String.IsNullOrEmpty(Path)) { if (!Path.StartsWith("/") && !Path.StartsWith(".")) { requestUri.Append("/"); } requestUri.Append(Path); } // sessionOptions.SshHostKeyFingerprint = SshHostKeyFingerprint; if (!String.IsNullOrEmpty(Path)) { if (!Path.StartsWith("/") && !Path.StartsWith(".")) { requestUri.Append("/"); } requestUri.Append(Path); } using (Session session = new Session()) { if (!String.IsNullOrEmpty(WinscpPath)) { session.ExecutablePath = WinscpPath; } // prepare for output DataTable dataTable = new DataTable(); dataTable.Columns.Add("Name", typeof(String)); dataTable.Columns.Add("Size", typeof(long)); dataTable.Columns.Add("LastModifiedDate", typeof(DateTime)); dataTable.Columns.Add("FullPath", typeof(String)); session.Open(sessionOptions); RemoteDirectoryInfo dirListing = session.ListDirectory(Path); Regex regex = null; if (!String.IsNullOrEmpty(FilterPattern)) { regex = new Regex(FilterPattern); } foreach (RemoteFileInfo fileInfo in dirListing.Files) { if (regex == null || regex.IsMatch(fileInfo.Name)) { dataTable.Rows.Add(new object[] { fileInfo.Name, fileInfo.Length, fileInfo.LastWriteTime, String.Format("{0}/{1}", requestUri.ToString(), fileInfo.Name) }); } } if (dataTable.Rows.Count > 0) { if (!String.IsNullOrEmpty(SortOrder)) { if (String.Compare(SortOrder, "asc", true) == 0) { DataView defaultView = dataTable.DefaultView; defaultView.Sort = "LastModifiedDate ASC"; dataTable = defaultView.ToTable(); } if (String.Compare(SortOrder, "desc", true) == 0) { DataView defaultView = dataTable.DefaultView; defaultView.Sort = "LastModifiedDate DESC"; dataTable = defaultView.ToTable(); } } } return dataTable; } }
public void TestSessionOpen() { using (var s = new Session()) s.Open("sftp"); // uses conn string called sftp in app.config }
private void Run() { FileTransferredEventHandler onFileTransferred = (sender, args) => { _log.DebugFormat("Transferred {0} to {1}", args.FileName, args.Destination); if (args.Error != null) _log.Error("Error while transferring file " + args.FileName, args.Error); }; ThreadPool.QueueUserWorkItem((state) => { using (_currSession = new Session()) { try { _currSession.FileTransferred += onFileTransferred; _currSession.Open(Options); _log.InfoFormat("Session was opened and going to sync directories from {0}...", TransferSource); var result = _currSession.SynchronizeDirectories( (SynchronizationMode)Enum.Parse(typeof(SynchronizationMode), Job.SyncMode), Job.Source, Job.Destination, Job.RemoveFiles); try { result.Check(); // it will throw on any error // only marking as stopped when everything went ok. // this way it will run again whenever the service restarts or a change happens on this same directory MarkAsStopped(); _log.InfoFormat("{0} was synced with success", TransferSource); } catch (Exception exception) { _log.Error("Some errors occured while syncing " + TransferSource, exception); } } catch (SessionLocalException sle) { // Probably aborted _log.Error("Something happened locally while syncing " + TransferSource, sle); ErrorHappened(sle.GetBaseException().Message); } catch (SessionRemoteException sre) { // Connection went down or refused _log.Error("Something happened remotely while syncing " + TransferSource, sre); ErrorHappened(sre.GetBaseException().Message); } catch (SessionException sessionException) { _log.Error("Unexpected session exception while syncing " + TransferSource, sessionException); ErrorHappened(sessionException.GetBaseException().Message); } catch (Exception exception) { _log.Error("Unexpected exception while syncing " + TransferSource, exception); ErrorHappened(exception.GetBaseException().Message); } _log.InfoFormat("Session for {0} ended", TransferSource); } _currSession = null; }); }
public static bool CheckForFiles() { string remoteDirectory = "/" + Properties.Settings.Default.FTPDownloadDir + "/"; string localDirectory = Properties.Settings.Default.RootFolderExt; bool bReturn = false; try { // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = Properties.Settings.Default.FTPAddress, UserName = Properties.Settings.Default.FTPUserName, Password = Properties.Settings.Default.FTPPassword, SshHostKeyFingerprint = Properties.Settings.Default.SshHostKeyFingerprint }; using (WinSCP.Session session = new WinSCP.Session()) { // Connect session.Open(sessionOptions); //List files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; RemoteDirectoryInfo files = session.ListDirectory(remoteDirectory); foreach (RemoteFileInfo file in files.Files) { if (file.Name.ToLower().Contains(".zip")) { GlobalServices.SetText("frmMain", "lFTPStatus", "Checking " + file.Name); if (!FileInloadStats.CheckRecordExists(file.Name)) { long total = file.Length > 0 ? file.Length : 1; int i = 0; GlobalServices.SetText("frmMain", "lFTPStatus", "Checking " + file.Name); //GlobalServices.SetProgressBar("frmMain", "pbProgress", 0, Convert.ToInt32(total), 0); GlobalServices.SetText("frmMain", "lFTPStatus", "Downloading File: " + file.Name); Console.WriteLine("Starting Download of file - " + file.Name + " Size - " + file.Length.ToString() + " Time - " + DateTime.Now.ToString()); // Download files TransferOperationResult transferOperationResult = session.GetFiles(session.EscapeFileMask(remoteDirectory + file.Name), localDirectory); // Check and throw if there are any errors with the transfer operation. transferOperationResult.Check(); if (transferOperationResult.IsSuccess) { var newFile = new FileInloadStats() { FileName = file.Name }; FileInloadStats.InsertRecord(newFile); Console.WriteLine("Completed Download of file - " + file.Name + " Size - " + file.Length.ToString() + " Time - " + DateTime.Now.ToString()); } } } } bReturn = true; } } catch (Exception e) { bReturn = false; return(bReturn); } return(bReturn); }
public int OpenSession(string _remoteRoot, string _localPath, string _ignoreCache) { RemoteRoot = _remoteRoot; IgnoreCache = _ignoreCache; LocalPath = _localPath; m_sessionInfo = new SessionInfo(); m_sessionInfo.Load(); try { m_session = new Session(); m_session.ExecutablePath = "../../../External/winscp573automation/WinSCP.exe"; m_session.Open(m_sessionInfo.SessionOptions); LOG.DebugFormat("Opened session at {0} with default settings", m_sessionInfo.SessionOptions.HostName); return 0; } catch (Exception e) { LOG.ErrorFormat("Error: {0}", e); return 1; } }
private static void UploadFile(string fileToUpload) { SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Ftp, HostName = CloudshareManager.cloudFoldersInfo.data.host, UserName = CloudshareManager.cloudFoldersInfo.data.user, Password = CloudshareManager.cloudFoldersInfo.data.password }; using (Session session = new Session()) { // Connect session.DisableVersionCheck = true; session.Open(sessionOptions); // Upload files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; var a = session.ListDirectory("/"); CloudshareManager.remoteUserFolderName = a.Files[2].Name; TransferOperationResult transferResult; transferResult = session.PutFiles(fileToUpload, "/" + a.Files[2].Name + "/*.*", false, transferOptions); // Throw on any error transferResult.Check(); } }
public string RunFtp(string hostIP, string port, string user, string pass, string remoteDirectory, string remoteFilePattern, string localFileDirectory, string pharmacyName, string localFileName, int numHoursGoback, string ram, ref DataTable tblExcel) { string result = ""; string localFileDirWithDateTime; string filePrefix = "SFTPDownload"; try { localFileDirWithDateTime = Helper.CreateDirectory(localFileDirectory, DateTime.Now, pharmacyName); } catch (Exception ex) { LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix, pharmacyName, "", DateTime.Now, "Failed trying to create a local Dir in " + localFileDirectory + ". Ftp for this pharm stopped.", ref tblExcel); return("Failure trying to create a directory in " + localFileDirectory + " for pharmacy " + pharmacyName + ". error:" + ex.Message); } try {//------------------------------------------------------------------------------------------------ WinSCP.SessionOptions sessionOptions = new WinSCP.SessionOptions { Protocol = WinSCP.Protocol.Sftp, HostName = hostIP, UserName = user, Password = pass, PortNumber = Convert.ToInt32(port) /* use these to connect to FTP, and leave out the fingerPrint.: * * _with1.Protocol = Protocol.Ftp; * _with1.FtpSecure = FtpSecure.Explicit; * */ }; string fingerprint = null; using (WinSCP.Session session = new WinSCP.Session()) { fingerprint = session.ScanFingerprint(sessionOptions); } if (fingerprint == null) { throw new Exception("Couldnt determine Host Fingerprint"); } else { sessionOptions.SshHostKeyFingerprint = fingerprint; } using (WinSCP.Session session = new WinSCP.Session()) { sessionOptions.Timeout = TimeSpan.FromMinutes(6); // 6 min timeout //session.ExecutablePath = @"C:\Software\v11\winscp.exe"; session.Open(sessionOptions); WinSCP.TransferOptions transferOptions = new WinSCP.TransferOptions(); transferOptions.TransferMode = WinSCP.TransferMode.Binary; WinSCP.TransferOperationResult transferResult = default(WinSCP.TransferOperationResult); transferResult = session.GetFiles(remoteDirectory + remoteFilePattern, localFileDirectory, false, transferOptions); transferResult.Check(); //THrows the first error if not successful foreach (WinSCP.TransferEventArgs transfer in transferResult.Transfers) { string downfileName = transfer.FileName; DateTime remoteWriteTime = session.GetFileInfo(downfileName).LastWriteTime; //get the DateTime of the file. if (remoteWriteTime >= DateTime.Now.AddHours(numHoursGoback * -1)) // ignore if older that the num Hours Goback spec by user { string localFilename = localFileDirWithDateTime + downfileName; //try //{ result += downfileName + "\r\n"; LogObj.WriteExcelrow("Success", enMsgType.enMsgType_Info, filePrefix, pharmacyName, downfileName, remoteWriteTime, "", ref tblExcel); // } //catch (Exception ex) //{ // LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix, // pharmacyName, downfileName, remoteWriteTime, ex.Message, ref tblExcel); // return "Failure occurred trying to Download SecureFtpWinSCP file " + downfileName + " for HostIp " + hostIP + " directory " + remoteDirectory + " files " + remoteFilePattern + " error:" + ex.Message + "\r\n"; //} } else { result += "Should be Ignored" + downfileName + " but still nowloaded." + "\r\n"; LogObj.WriteExcelrow("Success", enMsgType.enMsgType_Info, filePrefix, pharmacyName, downfileName, remoteWriteTime, " but still nowloaded.", ref tblExcel); //LogObj.WriteExcelrow("Ignored", enMsgType.enMsgType_Info, filePrefix, // pharmacyName, downfileName, file.Attributes.LastWriteTime, "its too old", ref tblExcel); } } } //------------------------------------------------------------------------------------------------------------------- return("Successfully downloaded to local dir " + localFileDirectory + " the following files: " + result); } catch (WinSCP.SessionRemoteException ex) { LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix, pharmacyName, "", DateTime.Now, "Check the remote settings. " + ex.Message, ref tblExcel); return("Failure occurred trying to connect to download SFtp for HostIp " + hostIP + " directory " + remoteDirectory + remoteFilePattern + " error:" + ex.Message + "\r\n"); } catch (System.TimeoutException ex) { LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix, pharmacyName, "", DateTime.Now, ex.Message, ref tblExcel); return("Failure occurred trying to connect to download SFtp for HostIp " + hostIP + " directory " + remoteDirectory + remoteFilePattern + " error:" + ex.Message + "\r\n"); } catch (Exception ex) { LogObj.WriteExcelrow("Failure!", enMsgType.enMsgType_Info, filePrefix, pharmacyName, "", DateTime.Now, ex.Message, ref tblExcel); return("Failure occurred trying to connect to download SFtp for HostIp " + hostIP + " directory " + remoteDirectory + remoteFilePattern + " error:" + ex.Message + "\r\n"); } }
//单线程即可 public static Tuple <int, string> m_fSendFile(m_cRecModel m_mRecModel, string m_sRemoteDirectory, bool m_bTest, LogTyper lt = LogTyper.LogLogger) { int status = 0; string msg = string.Empty; try { ///链接(S)FTP SessionOptions sessionOptions = new SessionOptions(); sessionOptions.Protocol = (Protocol)(int.Parse(m_cConfigConstants.m_sProtocol)); sessionOptions.HostName = m_cConfigConstants.m_sIP; sessionOptions.PortNumber = int.Parse(m_cConfigConstants.m_sPort); sessionOptions.UserName = m_cConfigConstants.m_sUa; sessionOptions.FtpMode = (FtpMode)(int.Parse(m_cConfigConstants.m_sMode)); if (!string.IsNullOrWhiteSpace(m_cConfigConstants.m_sPwd)) { sessionOptions.Password = m_cConfigConstants.m_sPwd; } if (!string.IsNullOrWhiteSpace(m_cConfigConstants.m_sKey)) { sessionOptions.SshHostKeyFingerprint = m_cConfigConstants.m_sKey; } ///放入测试 using (WinSCP.Session session = new WinSCP.Session()) { session.Open(sessionOptions); TransferEventArgs transferEventArgs; TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; //是否需要创建文件夹,逐级创建 if (!string.IsNullOrWhiteSpace(m_sRemoteDirectory) && !session.FileExists(RemotePath.EscapeFileMask(m_sRemoteDirectory))) { //查找出所有目录 string[] m_lDirectory = m_sRemoteDirectory.Split('/'); string m_sPrefixMulu = string.Empty; foreach (string m_sMulu in m_lDirectory) { if (!string.IsNullOrWhiteSpace(m_sMulu)) { m_sPrefixMulu += $"/{m_sMulu}"; if (!session.FileExists(RemotePath.EscapeFileMask(m_sPrefixMulu))) { session.CreateDirectory(RemotePath.EscapeFileMask(m_sPrefixMulu)); Log.Instance.Debug($"逐级创建(S)FTP目录:“{m_sPrefixMulu}”", lt); } } } } //判断文件是否已经上传 if (!session.FileExists(RemotePath.EscapeFileMask($"{m_sRemoteDirectory}/{System.IO.Path.GetFileName(m_mRecModel.mimiFile)}"))) { //如果为测试,文件不进行删除 transferEventArgs = session.PutFileToDirectory(m_mRecModel.mimiFile, RemotePath.EscapeFileMask(m_sRemoteDirectory), !m_bTest, transferOptions); string m_sErrMsg = string.Join(",", transferEventArgs?.Error?.Message); if (!string.IsNullOrWhiteSpace(m_sErrMsg)) { Log.Instance.Debug(m_sErrMsg, lt); status = 1; msg = m_sErrMsg; } else { status = 0; msg = "录音上传(S)FTP成功"; } } else { status = 0; msg = "录音已存在,略过上传(S)FTP"; if (!m_bTest) { Log.Instance.Debug($"{m_mRecModel.Id}:“{msg}”", lt); } } } } catch (Exception ex) { status = 1; msg = ex.Message; //如果有误 if (!m_bTest) { m_cSQL.m_fSetActionState(m_mRecModel.Id, "3", $"上传(S)FTP错误:{msg}", lt); } //打印一下错误,处理一下此处导致计划任务无法继续的问题 Log.Instance.Debug(ex, lt); } return(new Tuple <int, string>(status, msg)); }
public bool UploadToSFTP(string filename, string url, string username, string password, string spath, string stopath, string hostkey, string article, string journal) { try { //get static value from App.config file. //string ftpServerIP = ConfigurationSettings.AppSettings["sftpServerIP"].ToString(); //string stringsFtpUserID = ConfigurationSettings.AppSettings["sftpUserID"].ToString(); //string stringsFtpPassword = ConfigurationSettings.AppSettings["sftpPassword"].ToString(); string stringStrDate = System.DateTime.Now.ToString("dd_MM_yyyy-hh_mm_ss"); string stringFileName = filename; //string stringFromPath = ConfigurationSettings.AppSettings["sFromPath"].ToString(); //string stringToPath = ConfigurationSettings.AppSettings["sToPath"].ToString(); //string stringHostKey = ConfigurationSettings.AppSettings["sHostKey"].ToString(); string ftpServerIP = url; string stringsFtpUserID = username; string stringsFtpPassword = password; string stringFromPath = spath; string stringToPath = stopath; //string stringsBackUpFolder = "Processed"; //create folder for back up data if (!Directory.Exists(stringFromPath)) { // Directory.CreateDirectory(stringFromPath + stringsBackUpFolder); } //check whether file exist or not in local machine. if (!System.IO.File.Exists(stringFromPath)) { // using (FileStream fileStreamLocalFile = File.Create(stringFromPath + stringFileName)) //{ //byte[] byteLocalFile = new UTF8Encoding(true).GetBytes(filename); //fileStreamLocalFile.Write(byteLocalFile, 0, byteLocalFile.Length); // } } SessionOptions sessionOptionsSFTP = new SessionOptions { Protocol = Protocol.Sftp, HostName = ftpServerIP, UserName = stringsFtpUserID, Password = stringsFtpPassword, PortNumber = 22, SshHostKeyFingerprint = hostkey }; WinSCP.Session sessionSFTP = new WinSCP.Session(); sessionSFTP.Open(sessionOptionsSFTP); TransferOptions transferOptionsSFTP = new TransferOptions(); transferOptionsSFTP.TransferMode = TransferMode.Binary; transferOptionsSFTP.FilePermissions = null; transferOptionsSFTP.PreserveTimestamp = false; transferOptionsSFTP.ResumeSupport.State = TransferResumeSupportState.Off; TransferOperationResult transferOperationResultSFTP; transferOperationResultSFTP = sessionSFTP.PutFiles(stringFromPath + filename, filename, false, transferOptionsSFTP); if (System.IO.File.Exists(stringFromPath + stringFileName)) { // File.Move(stringFromPath + stringFileName, stringFromPath + "\\" + stringsBackUpFolder + "\\" + stringFileName); } transferOperationResultSFTP.Check(); if (transferOperationResultSFTP.IsSuccess == true) { Console.Write("File upload successfully"); Notifymail(filename, journal, article, "No Error"); report("ReadyFileFTP", filename, "Uploaded TO FTP__" + stopath + ""); return(true); } else { Console.Write("File upload failed"); Notifymail(filename, journal, article, "Upload Failed " + transferOperationResultSFTP.Failures.ToString()); report("Ready_FTP_Error", filename, "File upload failed " + transferOperationResultSFTP.Failures.ToString()); return(false); } } catch (Exception exError) { Console.Write(exError.Message); Notifymail(filename, journal, article, exError.ToString()); report("Ready_FTP_Error", filename, exError.ToString()); return(false); } }
private void DoTestConnection(object sender, DoWorkEventArgs e) { try { using (Session session = new Session()) { session.Open(sessionOptions); session.Close(); } RaiseConnectionOK(); } catch (Exception ex) { RaiseConnectionFAILED(); } }
public void DeleteOld(Database db) { if (MySQLBackUpFTP_ADOPSE.Properties.Settings.Default.deleteOld && MySQLBackUpFTP_ADOPSE.Properties.Settings.Default.keepOnFTP > 0 && MySQLBackUpFTP_ADOPSE.Properties.Settings.Default.sendBackup) { deleteAttempts++; try { using (Session session = new Session()) { session.Open(sessionOptions); ArrayList files = new ArrayList(); RemoteDirectoryInfo directory = session.ListDirectory(session.HomePath); Regex regex = new Regex("^DB_"+db.GetAlias()+@"_bu............\.sql$"); for (int i = 0; i < directory.Files.Count; i++) { Match match = regex.Match(directory.Files[i].Name); if (match.Success) files.Add(directory.Files[i].Name); } files.Sort(); for (int i = 0; i < files.Count - MySQLBackUpFTP_ADOPSE.Properties.Settings.Default.keepOnFTP; i++) session.RemoveFiles((string)files[i]); } } catch (Exception) { if (deleteAttempts < 4) DeleteOld(db); else new Log("Error trying to delete backup file(s) from the FTP server."); } } }
private void DoTransmission(Database db,EmailNotifications emailSettings) { sendAttempts++; new Log("FTP transmission for \"" + db.GetAlias() + "\" started."); try { using (Session session = new Session()) { session.Open(sessionOptions); TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; transferResult = session.PutFiles(db.GetFile(), "DB_" + db.GetAlias() + "_bu" + DateTime.Now.ToString("yyyyMMddHHmm") + ".sql", false, transferOptions); transferResult.Check(); new Log("FTP transmission for \"" + db.GetAlias() + "\" completed successfully."); session.Close(); emailSettings.NotifyCheck(db.GetAlias(),EmailNotifications.FTP_OPERATION_OK); } } catch (Exception ex) { if (sendAttempts < 6) DoTransmission(db,emailSettings); else { new Log("ERROR: FTP transmission for \"" + db.GetAlias() + "\" failed."); emailSettings.NotifyCheck(db.GetAlias(), EmailNotifications.FTP_OPERATION_FAIL); } } }
public void DownloadCSV(string winSCPPath, string csvDirectory, string serverType, string version, string csvFile, string report, string portfolio, string windowsOutput) { using (Session session = new Session()) { try { // Connect session.ExecutablePath = winSCPPath; session.Open(winSCPSessionOptions); } catch (Exception e) { throw new Exception("Could not open a WinSCP session!\n\n" + e.Message); } String rslReport = Path.GetFileNameWithoutExtension(report); String windowsOutputPath = windowsOutput + @"GFT_DiffTool_Output\" + DateTime.Today.ToString("yyyy-MM-dd") + "-" + version + @"\" + serverType + @"\"; try { DirectoryInfo dir = new DirectoryInfo(windowsOutputPath); if (!dir.Exists) { dir.Create(); } } catch (Exception e) { throw new Exception(String.Format("Could not create the following directory: {0}\n\n{1}", windowsOutputPath, e.Message)); } portfolio = portfolio.Replace(' ', '_'); String newCsvFileName = serverType + "." + portfolio + "." + rslReport + "." + version + ".csv"; #region Clean Directory if (File.Exists(windowsOutputPath + newCsvFileName)) { try { File.Delete(windowsOutputPath + newCsvFileName); } catch (Exception e) { throw new Exception(String.Format("Could not delete the following file: {0}\n\n{1}", windowsOutputPath + newCsvFileName, e.Message)); } } if (File.Exists(windowsOutputPath + "temp_" + newCsvFileName)) { try { File.Delete(windowsOutputPath + "temp_" + newCsvFileName); } catch (Exception e) { throw new Exception(String.Format("Could not delete the following file: {0}\n\n{21}", windowsOutputPath + "temp_" + newCsvFileName, e.Message)); } } if (File.Exists(windowsOutputPath + "backup_" + newCsvFileName)) { try { File.Delete(windowsOutputPath + "backup_" + newCsvFileName); } catch (Exception e) { throw new Exception(String.Format("Could not delete the following file: {0}\n\n{1}", windowsOutputPath + "backup_" + newCsvFileName, e.Message)); } } if (File.Exists(windowsOutputPath + "ERRORS_" + newCsvFileName)) { try { File.Delete(windowsOutputPath + "ERRORS_" + newCsvFileName); } catch (Exception e) { throw new Exception(String.Format("Could not delete the following file: {0}\n\n{21}", windowsOutputPath + "ERRORS_" + newCsvFileName, e.Message)); } } #endregion #region Transfer File TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; try { transferResult = session.GetFiles(csvDirectory + csvFile, windowsOutputPath + newCsvFileName, false, transferOptions); transferResult.Check(); } catch (Exception e) { throw new Exception(String.Format("Could not transfer the file \"{0}\" in Unix server to the Windows output as {1}\n\n{2}", csvDirectory + csvFile, windowsOutputPath + newCsvFileName, e.Message)); } try { session.ExecuteCommand("rm -f " + csvDirectory + csvFile); } catch (Exception e) { throw new Exception(String.Format("Could not execute de command: rm {0}\n\n{1}", csvDirectory + csvFile, e.Message)); } #endregion if (File.Exists(windowsOutputPath + newCsvFileName)) { string header; string line = ""; int errorCount = 0; try { using (var reader = File.OpenText(windowsOutputPath + newCsvFileName)) using (var writer = File.CreateText(windowsOutputPath + "temp_" + newCsvFileName)) using (var errorWriter = File.CreateText(windowsOutputPath + "ERRORS_" + newCsvFileName)) { header = reader.ReadLine(); writer.WriteLine(header); errorWriter.WriteLine("\"Error #\",\"Description\""); while (line != null && (line = reader.ReadLine()) != null) { if (line.Contains("\"Error #\"")) { errorCount++; while ((line = reader.ReadLine()) != null && !header.Equals(line)) { errorWriter.WriteLine(line); } } else { if (!header.Equals(line) && !line.Trim().Equals("") && line.StartsWith("\"")) { writer.WriteLine(line); } } } } File.Replace(windowsOutputPath + "temp_" + newCsvFileName, windowsOutputPath + newCsvFileName, windowsOutputPath + "backup_" + newCsvFileName); if (File.Exists(windowsOutputPath + "backup_" + newCsvFileName)) { File.Delete(windowsOutputPath + "backup_" + newCsvFileName); } if (File.Exists(windowsOutputPath + "ERRORS_" + newCsvFileName) && errorCount == 0) { File.Delete(windowsOutputPath + "ERRORS_" + newCsvFileName); } } catch (Exception e) { throw new Exception(String.Format("Could not open the file: {0}\n\n{1}", newCsvFileName, e.Message)); } } } }
public static void SyncFile() { SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = Param.SqlCeConfig["sshServer"].ToString(), UserName = Param.SqlCeConfig["sshUsername"].ToString(), SshPrivateKeyPath = Param.SqlCeConfig["sshKeyPath"].ToString(), PortNumber = int.Parse(Param.SqlCeConfig["sshPort"].ToString()), SshHostKeyFingerprint = Param.SqlCeConfig["sshHostKey"].ToString() }; if (CanConnectInternet()) { using (Session session = new Session()) { session.Open(sessionOptions); RemoteFileInfo fileInfo = session.GetFileInfo(Param.ScpSoftwarePath + "/Updater.exe"); FileInfo fi = new FileInfo("Updater.exe"); if (DateTimeToUnixTimestamp(fi.LastWriteTime) != DateTimeToUnixTimestamp(fileInfo.LastWriteTime)) { try { TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Automatic; TransferOperationResult transferResult; transferResult = session.GetFiles(Param.ScpSoftwarePath + "/Updater.exe", "Updater.exe", false, transferOptions); transferResult.Check(); foreach (TransferEventArgs transfer in transferResult.Transfers) { WriteLog(string.Format("Download of {0} : {1} succeeded", transfer.FileName, transfer.Destination)); } } catch (Exception ex) { WriteErrorLog(string.Format("SCP Download Error : {0}", ex.Message)); } } //session.FileTransferred += FileTransferred; if (Directory.Exists(Param.ApplicationDataPath + @"\log")) { try { TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Automatic; SynchronizationResult synchronizationResult; synchronizationResult = session.SynchronizeDirectories(SynchronizationMode.Remote, Param.ApplicationDataPath + @"\log", Param.ScpLogPath, false, false, SynchronizationCriteria.Time, transferOptions); synchronizationResult.Check(); } catch (Exception ex) { WriteErrorLog(string.Format("SCP SynchronizeDirectories Error : {0}", ex.Message)); } } session.Close(); } } }