public ChangeDirectory ( string path ) : void | ||
path | string | New directory path. |
리턴 | void |
public bool UploadFile(string filePath) { ConnectionInfo connectionInfo = new PasswordConnectionInfo(_address, ConstFields.SFTP_PORT, _username, _password); try { using (var sftp = new SftpClient(connectionInfo)) { sftp.Connect(); using (var file = File.OpenRead(filePath)) { if (!sftp.Exists(ConstFields.TEMP_PRINT_DIRECTORY)) { sftp.CreateDirectory(ConstFields.TEMP_PRINT_DIRECTORY); } sftp.ChangeDirectory(ConstFields.TEMP_PRINT_DIRECTORY); string filename = Path.GetFileName(filePath); sftp.UploadFile(file, filename); } sftp.Disconnect(); } } catch (Renci.SshNet.Common.SshConnectionException) { Console.WriteLine("Cannot connect to the server."); return false; } catch (System.Net.Sockets.SocketException) { Console.WriteLine("Unable to establish the socket."); return false; } catch (Renci.SshNet.Common.SshAuthenticationException) { Console.WriteLine("Authentication of SSH session failed."); return false; } return true; }
public SFTP(Uri targetServer,string password) { _sftp = new SftpClient(targetServer.Host,targetServer.Port, targetServer.UserInfo, password); log.InfoFormat("SFTP - Connecting to {0}", targetServer); _sftp.Connect(); log.InfoFormat("SFTP - Changing dir to {0}", targetServer.LocalPath); _sftp.ChangeDirectory(targetServer.LocalPath); }
private void ChangeWorkingDirectory(string destinationDirectory) { var cmd = _sshClient.RunCommand($"mkdir -p \"{destinationDirectory}\""); if (cmd.ExitStatus != 0) { throw new Exception(cmd.Error); } if (_sftpClient != null) { _sftpClient.ChangeDirectory(destinationDirectory); _scpDestinationDirectory = ""; } else { _scpDestinationDirectory = destinationDirectory; } PrintTime($"Working directory changed to '{destinationDirectory}'"); }
RenciSftpClient InstantiateClient() { var connectionInfo = new ConnectionInfo(Options.Host, Options.UserName, new PasswordAuthenticationMethod(Options.UserName, Options.Password)); var client = new RenciSftpClient(connectionInfo); client.Connect(); if (!client.ConnectionInfo.IsAuthenticated) { throw new Exception("SFTP: Could not authenticate"); } if (!string.IsNullOrWhiteSpace(Options.RemoteWorkingDirectory)) { client.ChangeDirectory(Options.RemoteWorkingDirectory); if (client.WorkingDirectory != Options.RemoteWorkingDirectory) { throw new Exception("SFTP: Do not match"); } } return(client); }
private StdResult<NoType> PushFileSFTP(string localFilePath, string distantDirectory) { if (!distantDirectory.StartsWith("/")) distantDirectory = string.Concat("/", distantDirectory); string distantPath = string.Format("ftp://{0}{1}", Host, distantDirectory); LogDelegate(string.Format("[FTP] Distant path: {0}", distantPath)); try { //new SftpClient(Host, 22, Login, Pwd) using (var sftp = new SftpClient(new PasswordConnectionInfo(Host, 22, Login, Pwd))) { sftp.HostKeyReceived += sftp_HostKeyReceived; sftp.Connect(); sftp.ChangeDirectory(distantDirectory); FileInfo fi = new FileInfo(localFilePath); string distantFullPath = string.Format("{0}{1}", distantDirectory, fi.Name); LogDelegate(string.Format("[FTP] ConnectionInfo : sftp.ConnectionInfo.IsAuthenticated:{0}, distant directory: {1}, username:{2}, host:{3}, port:{4}, distantPath:{5}", sftp.ConnectionInfo.IsAuthenticated, distantDirectory, sftp.ConnectionInfo.Username, sftp.ConnectionInfo.Host, sftp.ConnectionInfo.Port, distantFullPath)); //var sftpFiles = sftp.ListDirectory(distantDirectory); //FileStream local = File.OpenRead(localFilePath); //sftp.UploadFile(sr.BaseStream, distantDirectory, null); using (StreamReader sr = new StreamReader(localFilePath)) { LogDelegate(string.Format("[FTP] File being sent : {0} bytes.", sr.BaseStream.Length)); sftp.UploadFile(sr.BaseStream, distantFullPath); } } LogDelegate(string.Format("[FTP] File Sent successfully.")); return StdResult<NoType>.OkResult; } catch (Exception e) { if (LogDelegate != null) { Mailer mailer = new Mailer(); mailer.LogDelegate = LogDelegate; Exception exception = e; while (exception != null) { LogDelegate("[FTP] Exception envoi : " + exception.Message + " " + exception.StackTrace); exception = e.InnerException; } string emailConf = ConfigurationManager.AppSettings["NotificationEmail"]; mailer.SendMail(emailConf, "[Canal Collecte] Erreur FTP!", exception.Message + "<br/>" + e.StackTrace, null, ConfigurationManager.AppSettings["NotificationEmail_CC"]); } return StdResult<NoType>.BadResultFormat("[FTP] Exception envoi: {0} /// {1}", e.Message); } }
private void CreateDirectory(SftpClient client, string sourceFolderName, string destination) { var arr = sourceFolderName.Split(DeployUtil.TransferFolder.ToCharArray()); var relativeFolder = arr.Last(); var destinationPath = Path.Combine(destination, relativeFolder); if (!client.Exists(destinationPath)) { client.CreateDirectory(destination); client.ChangeDirectory(destination); } }
private void btnFTP_Click(object sender, EventArgs e) { //// Get the object used to communicate with the server. //FtpWebRequest request = (FtpWebRequest)WebRequest.Create("sftp://ftp.s6.exacttarget.com"); //request.Method = WebRequestMethods.Ftp.UploadFile; //// This example assumes the FTP site uses anonymous logon. //request.Credentials = new NetworkCredential("6177443", "mD.5.d6T"); //// Copy the contents of the file to the request stream. //StreamReader sourceStream = new StreamReader(@"D:\\DataExtension1List1.txt"); //byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); //sourceStream.Close(); //request.ContentLength = fileContents.Length; //Stream requestStream = request.GetRequestStream(); //requestStream.Write(fileContents, 0, fileContents.Length); //requestStream.Close(); //FtpWebResponse response = (FtpWebResponse)request.GetResponse(); //MessageBox.Show(string.Format("Archivo Subido, Estado {0}", response.StatusDescription), "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning); //response.Close(); const int port = 22; const string host = "ftp.s6.exacttarget.com"; const string username = "******"; const string password = "******"; const string workingdirectory = "/Import//"; const string uploadfile = @"D:\\DataExtension1List1.txt"; Console.WriteLine("Creating client and connecting"); using (var client = new SftpClient(host, port, username, password)) { client.Connect(); Console.WriteLine("Connected to {0}", host); client.ChangeDirectory(workingdirectory); Console.WriteLine("Changed directory to {0}", workingdirectory); //var listDirectory = client.ListDirectory(workingdirectory); //Console.WriteLine("Listing directory:"); //foreach (var fi in listDirectory) //{ // Console.WriteLine(" - " + fi.Name); //} using (var fileStream = new FileStream(uploadfile, FileMode.Open)) { Console.WriteLine("Uploading {0} ({1:N0} bytes)", uploadfile, fileStream.Length); client.BufferSize = 4 * 1024; // bypass Payload error large files client.UploadFile(fileStream, Path.GetFileName(uploadfile)); } MessageBox.Show("Archivo " + uploadfile + " subido a " + host, "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
/// <summary> /// This function will connect to the SFTP server for Paymentus /// Once connected it will upload the 2 files. /// </summary> private static void sftpConnect() { client = new Renci.SshNet.SftpClient(sftpHost, sftpPort, sftpUsername, new PrivateKeyFile(new MemoryStream(Encoding.ASCII.GetBytes(sftpKeyFile)),"MoneyBag$")); try { client.Connect(); client.ChangeDirectory(uploadPath); using (Stream fin = File.OpenRead(outputControlFullName)) { try { client.UploadFile(fin, outputControlFileName); } catch (Exception e) { body = body + "Threw an exception: " + e.Message.ToString() + (char)13 + (char)10; Console.WriteLine(string.Format("exception...{0}", e)); } } using (Stream fin = File.OpenRead(outputFileFullName)) { try{ client.UploadFile(fin, outputFileName); } catch (Exception e) { body = body + "Threw an exception: " + e.Message.ToString() + (char)13 + (char)10; Console.WriteLine(string.Format("exception...{0}", e)); } } } catch (Exception e) { body = body + "Threw an exception: " + e.Message.ToString() + (char)13 + (char)10; Console.WriteLine(string.Format("exception...{0}", e)); } }
/// <summary> /// This function will connect to the SFTP server for Paymentus /// Once connected it will upload the 2 files. /// </summary> private static void sftpConnect() { client = new Renci.SshNet.SftpClient(sftpHost, sftpPort, sftpUsername, new PrivateKeyFile(new MemoryStream(Encoding.ASCII.GetBytes(sftpKeyFile)), "MoneyBag$")); client.Connect(); client.ChangeDirectory(uploadPath); }
/* private void combineAdd(string url,List<string> adIds, List<string> adUrls, List<string> adImages, List<string> adTitle, List<string> imgwidth, List<string> imgheight, ad_network adN) { for (int i = 0; i < adUrls.Count; i++) { //file.Write(adUrls[i] +"|" + adIds + "|" + adImages[i] + "|" + adTitle + "|" + FirstSeen[i] + "|" + LastSeen[i]); advertisement ad = new advertisement(); ad.Id = adIds[i] + "_" + adN.name + "_" + Form1.country + "_" + Form1.device; ad.ad_networkId = adN.id; ad.ad_networkName = adN.name; ad.AddId = adIds[i]; ad.title = adTitle[i];// "19 Things That Probably Only Happen in Dubai"; //ad.image = adImages[i];// "http://d3dytsf4vrjn5x.cloudfront.net/2724/300x250/6afe33ad3159d67dd9b77b210a1a4335.jpg"; //ad.imageheight = 120; //ad.imageWidth = 150; ad.firstSceen = System.DateTime.Now; ad.lastSceen = System.DateTime.Now; ad.advertiserUrl = new List<string> { url }; //url; // ad.publisherUrl[0] = adUrls[i]; ad.publisherUrl = new List<string> { adUrls[i] }; //ad.publisherUrl = new List<string> { "http://firsttoknow.com/only-in-dubai/?utm_source=contentad_backfill&utm_campaign=only-in-dubai-102596&pp=1", "http://firsttoknow.com/make-a-ring-out-of-a-quarter/?utm_source=contentad_backfill&utm_campaign=make-a-ring-out-of-a-qua-108675&pp=1" }; ad.Country = Form1.country; ad.deviceName = Form1.device; ad.Useragent = "Opera/9.80 (Android; Opera Mini/5.1.22460/23.334; U; en) Presto/2.5.25 Version/10.54";//"Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0)";//"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36"; ad.Hits = new List<ad_hits>(); ad_hits hit = new ad_hits(); hit.date = System.DateTime.Now.Date; hit.count = 1; ad.Hits.Add(hit); ad.ad_details = new List<ad_Detail>(); ad_Detail adeatail = new ad_Detail(); adeatail.advertiserUrl = url; adeatail.publisherUrl = new List<string> { adUrls[i] }; adeatail.firstSceen = System.DateTime.Now; adeatail.lastSceen = System.DateTime.Now; adeatail.Hits = new List<ad_hits> { hit }; //adeatail.Hits.Add(hit); ad_Images aImage = new ad_Images(); aImage.ImageUrl = adImages[i]; try { aImage.imageheight = imgheight[i]; aImage.imageWidth = imgwidth[i]; } catch { aImage.imageheight = "300"; aImage.imageWidth = "250"; } aImage.IsServerUploaded = false; aImage.IsAmazonUploaded = false; aImage.ServerUrl = ""; aImage.AmazonUrl = ""; adeatail.Images = new List<ad_Images> { aImage }; ad.ad_details.Add(adeatail); Form1.saveAdvertisement(ad); } adIds = new List<string>(); adUrls = new List<string>(); adImages = new List<string>(); adTitle = new List<string>(); } private void saveAdvertisement(advertisement ad) { //ad.Id = "ad1_" + item.name + "_PK_D"; //ad.ad_networkId = item.id; //ad.ad_networkName = item.name; //ad.title = "19 Things That Probably Only Happen in Dubai"; //ad.image = "http://d3dytsf4vrjn5x.cloudfront.net/2724/300x250/6afe33ad3159d67dd9b77b210a1a4335.jpg"; //ad.imageheight = 120; //ad.imageWidth = 150; //ad.firstSceen = System.DateTime.Now; //ad.lastSceen = System.DateTime.Now; //ad.advertiserUrl = "http://viralkeen.com/"; //string publisherUrl = "http://firsttoknow.com/"; //ad.Country = "PK"; //ad.deviceName = "desktop"; //ad.Useragent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36"; advertisement Old = new advertisement(); Old = ad.SearchById(ad.Id); if (Old != null) { try { ad.firstSceen = Old.firstSceen; var CurrentHit = Old.Hits.Find(a => a.date == System.DateTime.Now.Date); if (CurrentHit != null) CurrentHit.count++; else { ad_hits hit = new ad_hits(); hit.date = System.DateTime.Now.Date; hit.count = 1; Old.Hits.Add(hit); } ad.Hits = Old.Hits; var OldDetail = Old.ad_details.Find(a => a.advertiserUrl == ad.advertiserUrl[0]); if (OldDetail != null) { OldDetail.lastSceen = System.DateTime.Now; var imag = OldDetail.Images.Find(a => a.ImageUrl == ad.ad_details[0].Images[0].ImageUrl); if (imag == null) { int index = Old.ad_details.FindIndex(a => a.advertiserUrl == ad.advertiserUrl[0]); string ImagePath = Old.Id + "_" + index + "_" + OldDetail.Images.Count; if( UploadImage(ImagePath, ad.ad_details[0].Images[0].ImageUrl)) { ad.ad_details[0].Images[0].ServerUrl = ImagePath; ad.ad_details[0].Images[0].IsServerUploaded = true; } OldDetail.Images.Add(ad.ad_details[0].Images[0]); } if (!OldDetail.publisherUrl.Contains(ad.ad_details[0].publisherUrl[0])) OldDetail.publisherUrl.Add(ad.ad_details[0].publisherUrl[0]); var HitDetail = OldDetail.Hits.Find(a => a.date == System.DateTime.Now.Date); if (HitDetail != null) HitDetail.count++; else { ad_hits hit = new ad_hits(); hit.date = System.DateTime.Now.Date; hit.count = 1; OldDetail.Hits.Add(hit); } } else { //int index = Old.ad_details.FindIndex(a => a.advertiserUrl == ad.advertiserUrl[0]); string ImagePath = Old.Id + "_" + Old.ad_details.Count + "_" + 0; if (UploadImage(ImagePath, ad.ad_details[0].Images[0].ImageUrl)) { ad.ad_details[0].Images[0].ServerUrl = ImagePath; ad.ad_details[0].Images[0].IsServerUploaded = true; } Old.ad_details.Add(ad.ad_details[0]); } ad.ad_details = Old.ad_details; if (Old.publisherUrl.Contains(ad.publisherUrl[0])) ad.publisherUrl = Old.publisherUrl; else { Old.publisherUrl.Add(ad.publisherUrl[0]); ad.publisherUrl = Old.publisherUrl; } if (Old.advertiserUrl.Contains(ad.advertiserUrl[0])) ad.advertiserUrl = Old.advertiserUrl; else { Old.advertiserUrl.Add(ad.advertiserUrl[0]); ad.advertiserUrl = Old.advertiserUrl; } ad.Update(ad); } catch { } } else { // ad.publisherUrl = new List<string> { publisherUrl }; try { //int index = Old.ad_details.FindIndex(a => a.advertiserUrl == ad.advertiserUrl[0]); string ImagePath = ad.Id + "_" + 0 + "_" + 0+".jpg"; if (UploadImage(ImagePath, ad.ad_details[0].Images[0].ImageUrl)) { ad.ad_details[0].Images[0].ServerUrl = ImagePath; ad.ad_details[0].Images[0].IsServerUploaded = true; } ad.Insert(ad); } catch { } } } */ internal static bool UploadImage(string FileName, string ImageUrl) { try { using (WebClient webClient = new WebClient()) { webClient.DownloadFile(new Uri(ImageUrl), FileName); } const int port = 22; const string host = "66.85.92.2"; const string username = "******"; const string password = "******"; const string workingdirectory = "/var/www/ad_images/"; // const string uploadfile = path; Console.WriteLine("Creating client and connecting"); if (System.IO.File.Exists(FileName)) { using (var client = new SftpClient(host, port, username, password)) { client.Connect(); client.ChangeDirectory(workingdirectory); //var listDirectory = client.ListDirectory(workingdirectory); //foreach (var fi in listDirectory) //{ // Console.WriteLine(" - " + fi.Name); //} using (var fileStream = new FileStream(FileName, FileMode.Open)) { Console.WriteLine("Uploading {0} ({1:N0} bytes)", FileName, fileStream.Length); client.BufferSize = 4 * 1024; // bypass Payload error large files client.UploadFile(fileStream, Path.GetFileName(FileName)); } try { System.IO.File.Delete(FileName); } catch (Exception ex) { } return true; } } return false; } catch { return false; } }
//& IM-3927 private void SendSingleFtp(FtpPending fp) { bool succeeded = false; if (fp == null) return; string destinationFilename = ""; try { if (fp.Retry > 1) _Log.Debug("Retry ftp attachmentFiles: " + fp.AttachmentFiles); string destinationPath = ""; if (fp.DestinationPath != null) { // Ensure destination path is in Windows format i.e. "\" between folders string validWindowsPath = fp.DestinationPath; validWindowsPath = validWindowsPath.Replace("/","\\"); destinationPath = Path.GetDirectoryName(validWindowsPath); if (destinationPath != "" && !destinationPath.StartsWith("C:") && !destinationPath.StartsWith("\\")) //& IM-4227 destinationPath = "\\" + destinationPath; //& IM-4227 destinationFilename = Path.GetFileName(validWindowsPath); } if (destinationFilename.Contains("YYMMDD_HHMMSS")) { string tmp = destinationFilename.Replace("YYMMDD_HHMMSS", DateTime.UtcNow.ToString("yyyyMMdd_HHmmss")); //# IM-4227 destinationFilename = tmp.Replace(":", ""); } if (destinationFilename.EndsWith("YYYYMMDD")) //PP-206 { string tmp = destinationFilename.Replace("YYYYMMDD", DateTime.UtcNow.ToString("yyyyMMdd")); //PP-206 destinationFilename = tmp.Replace(":", ""); } if (destinationFilename != "") { // User has a custom filename they want to use - so just add the appropriate extension from the source report name destinationFilename += Path.GetExtension(fp.AttachmentFiles); // use extension from report file generated e.g. CSV //# IM-4227 } else { // use the default report name that the report writer assigned when creating the report destinationFilename = Path.GetFileName(fp.AttachmentFiles); } // Unencrypt username and password // TODO var sftp = new SftpClient(fp.IPAddress, fp.Port, fp.Username, fp.Password); //# PP-223 ---Added Port Number sftp.Connect(); using (var file = File.OpenRead(fp.AttachmentFiles)) { if (destinationPath != "") { destinationPath = FormatPathForOSTalkingTo(destinationPath, sftp.WorkingDirectory); sftp.ChangeDirectory(destinationPath); } sftp.UploadFile(file, destinationFilename); } sftp.Disconnect(); succeeded = true; } catch (Exception ex) { var msg = string.Format("Ftp ID={0} file=[{1}] server=[{2}]: error {3} : Stack {4} destination :{5}", fp.ID, Path.GetFileName(fp.AttachmentFiles).Truncate(30), fp.IPAddress, ex.Message, ex.StackTrace, destinationFilename); AttentionUtils.Attention(new Guid("63dd8220-d6a8-badd-8158-bed1aa10d130"), msg); _Log.Warn(msg); succeeded = false; } //if ftp'ed successfully, save to FtpSent and delete from FtpPending if (succeeded) { DeleteFtpPending(new IDRequest(fp.ID)); var req = new SaveRequest<FtpSent>(); var fs = new FtpSent(fp); fs.LastRetryAt = fp.DateModified; fs.Retry = fp.Retry + 1; fs.TimeToSend = DateTime.MaxValue;//never to send again req.Item = fs; SaveFtpSent(req); } //if failed, save to FtpFailed and delete from FtpPending else { DeleteFtpPending(new IDRequest(fp.ID)); var request = new SaveRequest<FtpFailed>(); var fs = new FtpFailed(fp); fs.LastRetryAt = fp.DateModified; if (!string.IsNullOrEmpty(fs.DestinationPath) && fs.Retry < _Retries.Length) //TODO check for path valid syntax { fs.TimeToSend = DateTime.UtcNow.AddMinutes(_Retries[fs.Retry]); fs.Retry++; } else { fs.TimeToSend = DateTime.MaxValue; // don't send again fs.Deleted = true; } request.Item = fs; SaveFtpFailed(request); } }
public bool UploadFile(string localFileName, Action<ulong> uploadCallback, string remotePath = "") { string remoteFileName = remotePath+System.IO.Path.GetFileName(localFileName); using (var sftp = new SftpClient(GenerateConnectionInfo())) { sftp.Connect(); //TODO: check if the directory exists! sftp.ChangeDirectory(Workingdirectory); sftp.ErrorOccurred += ssh_ErrorOccurred; using (var file = File.OpenRead(localFileName)) { try { sftp.UploadFile(file, remoteFileName, uploadCallback); } catch (Exception e) { return false; } } sftp.Disconnect(); } return true; }
public static void SSHTest() { string[] list; ConnectionInfo ConnNfo = new ConnectionInfo("10.26.2.136", 22, "root", new AuthenticationMethod[]{ // Pasword based Authentication new PasswordAuthenticationMethod("root","adminadmin_2") // Key Based Authentication (using keys in OpenSSH Format) //new PrivateKeyAuthenticationMethod("username",new PrivateKeyFile[]{ // new PrivateKeyFile(@"..\openssh.key","passphrase") //} }); using (var sshclient = new SshClient(ConnNfo)) { sshclient.Connect(); // quick way to use ist, but not best practice - SshCommand is not Disposed, ExitStatus not checked... Console.WriteLine(sshclient.CreateCommand("cd /tmp && ls -lah").Execute()); Console.WriteLine(sshclient.CreateCommand("pwd").Execute()); string output = sshclient.CreateCommand("cd /data1/strongmail/log && find strongmail-monitor* -maxdepth 1 -mtime -1").Execute(); list = output.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (string file in list) { Console.WriteLine("File: " + file); } sshclient.Disconnect(); } Console.Write("Attempt to download file."); // Upload A File using (var sftp = new SftpClient(ConnNfo)) { sftp.Connect(); sftp.ChangeDirectory("/data1/strongmail/log"); foreach (string file in list) { string fullPath = @"D:\Temp\StrongView\" + file; var x = sftp.Get(file); byte[] fileBytes = new byte[x.Length]; using (var dwnldfileStream = new System.IO.MemoryStream(fileBytes)) { sftp.DownloadFile(file, dwnldfileStream); //System.IO.File.WriteAllBytes(@"d:\temp\strongview\bytes\" + file, fileBytes); //var xmlr = System.Xml.XmlReader.Create(dwnldfileStream); //while (xmlr.Read()) { // if (xmlr.NodeType.Equals(System.Xml.XmlNodeType.Element) && xmlr.Name.Equals("QueueInfo")) { // string processid = xmlr.GetAttribute("PID"); // while(!xmlr.) // } //} string text = ConnNfo.Encoding.GetString(fileBytes); XDocument doc = XDocument.Parse("<root>" + text + "</root>"); var smtpQueue = doc.Descendants("QueueInfo").Where(xx => xx.Element("Protocol").Value.Equals("SMTP")); var serverInfo = doc.Descendants("ServerInfo"); var wrtr = doc.CreateWriter(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); using (System.Xml.XmlWriter wr = System.Xml.XmlWriter.Create(sb, new System.Xml.XmlWriterSettings() { ConformanceLevel = System.Xml.ConformanceLevel.Fragment })) { wr.WriteStartElement("root"); serverInfo.First().WriteTo(wr); foreach (XElement xl in smtpQueue) { xl.WriteTo(wr); } wr.WriteEndElement(); } string PID = smtpQueue.Attributes().First().Value.ToString(); System.IO.File.WriteAllText(@"d:\temp\strongview\docs\" + PID + ".xml", sb.ToString()); } } sftp.Disconnect(); } Console.WriteLine("Done!"); //Console.ReadKey(); }
void doUpload(object sender, Renci.SshNet.Common.ShellDataEventArgs e) { var line = Encoding.UTF8.GetString(e.Data); var arr = line.Split(Environment.NewLine.ToCharArray()).Where(x => !string.IsNullOrEmpty(x)).ToList(); //拿到路径之后开始上传 var remoteBasePath = arr[1]; using (var sftp = new SftpClient(server,port, user, pwd)) { sftp.Connect(); foreach (var file in fileList) { string uploadfn = file; var fileName = Path.GetFileName(file); sftp.ChangeDirectory(remoteBasePath); using (var uplfileStream = System.IO.File.OpenRead(uploadfn)) { sftp.UploadFile(uplfileStream, fileName, true); } showLine(string.Format(" file===>{0} uploaed", file)); } sftp.Disconnect(); } shellStream.DataReceived -= doUpload; shellStream.DataReceived += ShellStream_DataReceived; }
/// <summary> /// Upload Files. /// </summary> /// <returns></returns> public Boolean Put() { Boolean ok = false; // Choose Authentication Method AuthenticationMethod authenticationMethod; if (PrivateKeyPath != null && PrivateKeyPath.Trim().Length > 0) { authenticationMethod = new PrivateKeyAuthenticationMethod(UserName, new PrivateKeyFile(PrivateKeyPath, PassPhrase)); } else { authenticationMethod = new PasswordAuthenticationMethod(UserName, Password); } // Get Connection Info ConnectionInfo connectionInfo; if (Port > 0) { if (Proxy != null && Proxy.Host != null && Proxy.Host.Length > 0) { connectionInfo = new ConnectionInfo(Host, Port, UserName, (ProxyTypes)Enum.Parse(typeof(ProxyTypes), Proxy.Type.ToString()), Proxy.Host, Proxy.Port, Proxy.UserName, Proxy.Password, authenticationMethod); } else { connectionInfo = new ConnectionInfo(Host, Port, UserName, authenticationMethod); } } else { connectionInfo = new ConnectionInfo(Host, UserName, authenticationMethod); } // Uploads Boolean fail = false; using (SftpClient sftp = new SftpClient(connectionInfo)) { // Connect try { sftp.Connect(); } catch (Exception xcp) { Logger.Log($"SftpClient.Connect failed:{Environment.NewLine}{ToString()}", xcp, EventLogEntryType.Error); fail = true; } // Check Connection if (!fail && sftp.IsConnected) { // Change Directory if (Directory.Length > 0) { sftp.ChangeDirectory(Directory); } foreach (var filePath in FilePaths) { // Upload File using (FileStream file = File.OpenRead(filePath)) { try { String path = Directory.Length > 0 ? string.Format("{0}/{1}", Directory, Path.GetFileName(filePath)) : ""; Action<UInt64> del = uploadFileCallback; sftp.UploadFile(file, path, del); //uploadFileResult ok = true; } catch (System.ArgumentException xcp) { Logger.Log($"SftpClient.UploadFile failed:{Environment.NewLine}{ToString()}", xcp, EventLogEntryType.Error); throw; } catch (Exception xcp) { Logger.Log($"SftpClient.UploadFile failed:{Environment.NewLine}{ToString()}", xcp, EventLogEntryType.Error); throw; } } } // Disconnect try { sftp.Disconnect(); } catch (Exception xcp) { Logger.Log($"SftpClient.Disconnect failed:{Environment.NewLine}{ToString()}", xcp, EventLogEntryType.FailureAudit); } } } return ok && !fail; }
public Response UploadSFTP(DataExtensionImport dataExtensionImport) { var response = new Response { Success = true, Warning = false }; try { const int port = 22; const string host = "ftp.s6.exacttarget.com"; const string username = "******"; const string password = "******"; const string workingdirectory = "/Import//"; using (var client = new SftpClient(host, port, username, password)) { client.Connect(); client.ChangeDirectory(workingdirectory); string extension = Path.GetExtension(dataExtensionImport.Ruta); string nombreArchivo = string.Format("{0}{1}", dataExtensionImport.Nombre, extension); using (var fileStream = new FileStream(dataExtensionImport.Ruta, FileMode.Open)) { client.BufferSize = 4 * 1024; // bypass Payload error large files client.UploadFile(fileStream, nombreArchivo); } } } catch (Exception ex) { response.Success = false; response.Message = ex.Message; } return response; }
/// <summary> /// This function will connect to the SFTP server for Wells Fargo /// </summary> private static void sftpConnect() { client = new Renci.SshNet.SftpClient(sftpHost, sftpPort, sftpUsername, new PrivateKeyFile(new MemoryStream(Encoding.ASCII.GetBytes(sftpKeyFile)))); try { client.Connect(); client.ChangeDirectory(downloadPath); } catch (Exception e) { appendToBody(String.Format("Download client threw an exception: {0}", e.Message.ToString())); Console.WriteLine(string.Format("exception...{0}", e)); } }
private bool Sftp(string server, int port, bool passive, string username, string password, string filename, int counter, byte[] contents, out string error, bool rename) { bool failed = false; error = ""; try { int i = 0; filename = filename.Replace("{C}", counter.ToString(CultureInfo.InvariantCulture)); if (rename) filename += ".tmp"; while (filename.IndexOf("{", StringComparison.Ordinal) != -1 && i < 20) { filename = String.Format(CultureInfo.InvariantCulture, filename, Helper.Now); i++; } var methods = new List<AuthenticationMethod> { new PasswordAuthenticationMethod(username, password) }; var con = new ConnectionInfo(server, port, username, methods.ToArray()); using (var client = new SftpClient(con)) { client.Connect(); var filepath = filename.Trim('/').Split('/'); var path = ""; for (var iDir = 0; iDir < filepath.Length - 1; iDir++) { path += filepath[iDir] + "/"; try { client.CreateDirectory(path); } catch { //directory exists } } if (path != "") { client.ChangeDirectory(path); } filename = filepath[filepath.Length - 1]; using (Stream stream = new MemoryStream(contents)) { client.UploadFile(stream, filename); if (rename) { try { //delete target file? client.DeleteFile(filename.Substring(0, filename.Length - 4)); } catch (Exception) { } client.RenameFile(filename, filename.Substring(0, filename.Length - 4)); } } client.Disconnect(); } MainForm.LogMessageToFile("SFTP'd " + filename + " to " + server + " port " + port, "SFTP"); } catch (Exception ex) { error = ex.Message; failed = true; } return !failed; }