public UploadFile ( Stream input, string path, Action |
||
input | Stream | Data input stream. |
path | string | Remote file path. |
uploadCallback | Action |
The upload callback. |
Результат | 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; }
private void Execute() { var keyPath = textBoxFile.Text; var host = textBoxHost.Text; var user = textBoxUser.Text; var pass = textBoxPass.Text; Action _execute = () => { try { //Read Key Status("opening key"); FileStream file = File.OpenRead(keyPath); //Connect to SFTP Status("sftp connecting"); SftpClient sftp = new SftpClient(host, user, pass); sftp.Connect(); //users home directory string homepath = "/home/" + user + "/"; if (user == "root") { homepath = "/root/"; } //Find authorized keys string authKeys = homepath + ".ssh/authorized_keys"; if (!sftp.Exists(authKeys)) { Status("creating"); if (!sftp.Exists(homepath + ".ssh")) sftp.CreateDirectory(homepath + ".ssh"); sftp.Create(authKeys); } //Download Status("downloading"); Stream stream = new MemoryStream(); sftp.DownloadFile(authKeys, stream); Status("downloaded"); //Read byte[] buffer = new byte[10240]; //No key should be this large int length = file.Read(buffer, 0, buffer.Length); //Validate String strKey; if (length < 20) { Status("Invalid Key (Length)"); return; } if (buffer[0] == (byte) 's' && buffer[1] == (byte) 's' && buffer[2] == (byte) 'h' && buffer[3] == (byte) '-' && buffer[4] == (byte) 'r' && buffer[5] == (byte) 's' && buffer[6] == (byte) 'a') { strKey = Encoding.ASCII.GetString(buffer, 0, length).Trim(); } else { Status("Invalid Key (Format)"); return; } stream.Seek(0, SeekOrigin.Begin); StreamReader reader = new StreamReader(stream); //Check for key that might already exist while (!reader.EndOfStream) { var line = reader.ReadLine().Trim(); if (line == strKey) { Status("key already exists"); return; } } //Check new line if (stream.Length != 0) { stream.Seek(0, SeekOrigin.End); stream.WriteByte((byte) '\n'); } else { stream.Seek(0, SeekOrigin.End); } //Append Status("appending"); stream.Write(buffer, 0, length); //Upload Status("uploading"); stream.Seek(0, SeekOrigin.Begin); sftp.UploadFile(stream, authKeys); Status("done"); //Save key path Settings.Default.KeyPath = textBoxFile.Text; Settings.Default.Save(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }; Thread thread = new Thread(new ThreadStart(_execute)); thread.Start(); }
private void sendSFTP(string filePath, string fileName) { SftpClient sftp = new SftpClient("194.2.93.194", "userece", "AdminPOCNUC01"); sftp.Connect(); using (FileStream filestream = File.OpenRead(filePath)) { sftp.UploadFile(filestream, "/"+fileName, null); sftp.Disconnect(); } }
public void uploadFile(string localpath, Action <ulong> uploadProgress = null) { System.IO.FileStream filestream = new System.IO.FileStream(localpath, System.IO.FileMode.Open); fileName = Path.GetFileName(localpath); ftp.UploadFile(filestream, "/tmp/" + fileName, uploadProgress); filestream.Close(); ftp.Disconnect(); }
public void beginCracking() { log("beginning cracking process.."); var connectionInfo = new PasswordConnectionInfo (xml.Config.host, xml.Config.port, "root", xml.Config.Password); using (var sftp = new SftpClient(connectionInfo)) { using (var ssh = new SshClient(connectionInfo)) { PercentStatus("Establishing SSH connection", 5); ssh.Connect(); PercentStatus("Establishing SFTP connection", 10); sftp.Connect(); log("Cracking " + ipaInfo.AppName); PercentStatus("Preparing IPA", 25); String ipalocation = AppHelper.extractIPA(ipaInfo); using (var file = File.OpenRead(ipalocation)) { log("Uploading IPA to device.."); PercentStatus("Uploading IPA", 40); sftp.UploadFile(file, "Upload.ipa"); } log("Cracking! (This might take a while)"); PercentStatus("Cracking", 50); String binaryLocation = ipaInfo.BinaryLocation.Replace("Payload/", ""); String TempDownloadBinary = Path.Combine(AppHelper.GetTemporaryDirectory(), "crackedBinary"); var crack = ssh.RunCommand("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary"); log("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary"); log("cracking output: " + crack.Result); using (var file = File.OpenWrite(TempDownloadBinary)) { log("Downloading cracked binary.."); PercentStatus("Downloading cracked binary", 80); try { sftp.DownloadFile("/tmp/crackedBinary", file); } catch (SftpPathNotFoundException e) { log("Could not find file, help!!!!!"); return; } } PercentStatus("Repacking IPA", 90); String repack = AppHelper.repack(ipaInfo, TempDownloadBinary); PercentStatus("Done!", 100); log("Cracking completed, file at " + repack); } } }
private void UploadFile(Stream input, string path) { if (_sftpClient != null) { _sftpClient.UploadFile(input, path); } else { _scpClient.Upload(input, _scpDestinationDirectory + "/" + path); } }
public static void UploadFileWithOpenConnection(string localFileToUpload, string targetFile, SftpClient sftp) { var directory = FlatRedBall.IO.FileManager.GetDirectory(targetFile, FlatRedBall.IO.RelativeType.Relative); CreateDirectoriesRecursively(directory, sftp); using (var file = File.OpenRead(localFileToUpload)) { sftp.UploadFile(file, targetFile, canOverride: true); } }
public static void CopyFileFromLocalToRemote(string host, string user, string password, string localPath, string remotePath) { using (SftpClient client = new SftpClient(host, user, password)) { client.KeepAliveInterval = TimeSpan.FromSeconds(60); client.ConnectionInfo.Timeout = TimeSpan.FromMinutes(180); client.OperationTimeout = TimeSpan.FromMinutes(180); client.Connect(); bool connected = client.IsConnected; // RunCommand(host, user, password, "sudo chmod 777 -R " + remotePath); FileInfo fi = new FileInfo(localPath); client.UploadFile(fi.OpenRead(), remotePath + fi.Name, true); client.Disconnect(); } }
public void UploadFile(ResourceNode node, string remotePath, string localPath) { if (_sftpClient != null) { using (var stream = File.OpenRead(localPath)) { _sftpClient.UploadFile(stream, remotePath); } } else if (_scp != null) { _scp.Put(localPath, remotePath); } else { throw new Exception("No connection established to node for copy"); } //scp.Upload(new FileInfo(localPath), remotePath); //scp.ConnectionInfo.ChannelRequests. //scp.Upload(new FileInfo(localPath), "tmp/" + Path.GetFileName(remotePath)); }
public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction) { try { using (var sftp = new SftpClient(Host, Port, Username, Password)) { sftp.Connect(); using (var file = File.OpenRead(SourcePath)) { sftp.UploadFile(file, TargetPath); } return DTSExecResult.Success; } } catch (Exception ex) { log.Write(string.Format("{0}.Execute", GetType().FullName), ex.ToString()); return DTSExecResult.Failure; } }
// Use this for initialization public void Send() { string address = "10.211.55.4"; string user = "******"; string pass = "******"; //string cmd = "r2 '/home/parallels/Desktop/Bomb.ex_' -c 'aa;s section..text;afn main;e asm.lines=False;e asm.comments=False;e asm.calls=false;e asm.cmtflgrefs=false;e asm.cmtright=false;e asm.flags=false;e asm.function=false;e asm.functions=false;e asm.vars=false;e asm.xrefs=false;e asm.linesout=false;e asm.fcnlines=false;e asm.fcncalls=false;e asm.demangle=false;aa;s section..text;pdf>main.txt;exit' -q"; string cmd = "r2 '/home/parallels/Desktop/Bomb.ex_' -c 'aa; s section..text; afn main; pdf @ main > main.txt' -q"; string uploadfile = @"/Users/JonathanWatts/Desktop/Bomb.ex_"; string uploadDirectory = "/home/parallels/Desktop/"; //Upload a file to a linux VM using (var sftp = new SftpClient(address, user, pass)) { try { sftp.Connect(); using (var fileStream = new FileStream(uploadfile, FileMode.Open)) { Console.WriteLine("Uploading {0} ({1:N0} bytes)", uploadfile, fileStream.Length); sftp.BufferSize = 4 * 1024; // bypass Payload error large files sftp.UploadFile(fileStream, uploadDirectory + Path.GetFileName(uploadfile)); } sftp.Disconnect(); sftp.Dispose(); } catch(Exception ex) { Console.WriteLine(ex.Message); } } //This block of code will send linux terminal commands from windows machine to linux virtual machine using(SshClient client = new SshClient(address,user, pass)) { try { Debug.Log ("Sending Command..."); client.Connect(); Debug.Log ("Sending Command..."); var result = client.RunCommand(cmd); Debug.Log (result); client.Disconnect(); Debug.Log ("Sending Command..."); client.Dispose(); } catch(Exception ex) { Debug.Log (ex.Message); Console.WriteLine(ex.Message); } } //This block of code will download the file from linux VM to the windows host machine try { Debug.Log ("Uploading file..."); using (var sftp = new SftpClient(address, user, pass)) { sftp.Connect(); if(File.Exists("/Users/JonathanWatts/main333.txt")) { File.Delete("/Users/JonathanWatts/main333.txt"); } using (Stream file1 = File.OpenWrite("/Users/JonathanWatts/main333.txt")) { try { sftp.DownloadFile("main.txt", file1); } catch (Exception ex) { Console.WriteLine(ex.Message); } file1.Close(); } sftp.Disconnect(); sftp.Dispose(); } } catch(Exception ex) { Debug.Log (ex.Message); Console.WriteLine(ex.Message); } //SshShell shell = new SshShell(address, user, pass); }
private void UploadFile(SftpClient client, string filePath, string destination) { using (var fileStream = new FileStream(filePath, FileMode.Open)) { Console.WriteLine("Uploading {0} ({1:N0} bytes)", filePath, fileStream.Length); client.BufferSize = 4 * 1024; // bypass Payload error large files client.UploadFile(fileStream, Path.GetFileName(filePath)); } }
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; }
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; }
/// <summary> /// Publishes the application to the server /// </summary> /// <param name="app"></param> /// <param name="localPath">The path to the local .exe file of the application</param> public void PublishApplication(Application app, string localPath, List<string> bugFixes, List<string> newStuff, List<string> deletedFiles, string ftpServer, string ftpUser, string privateKeyFile, string privateKeyPassPhrase, string pathToAppsFolder) { try { #region PRECONDITIONS if (!File.Exists(localPath)) throw new FileNotFoundException(string.Format("Could not find a part of the file '{0}'", localPath)); #endregion app.UpdateProgress = 0; app.PublishingStatus = "Connecting to SFTP server"; // Open SFTP connection to server using (var ftpClient = new SftpClient(ftpServer, ftpUser, new PrivateKeyFile(privateKeyFile, privateKeyPassPhrase))) { ftpClient.Connect(); var newVersion = AssemblyName.GetAssemblyName(localPath).Version; if (newVersion <= app.ApplicationVersion) throw new InvalidOperationException("You are trying to publish an older version than the one that is on the server! You have to increase the assembly version and republish!"); app.PublishingStatus = "Updating changelog"; // Create changelog entry app.AddVersionToChangelog(newVersion, bugFixes, newStuff, deletedFiles); ftpClient.UploadFile(this.GenerateStreamFromString(app.ChangeLog.ToString()), string.Format("{1}/{0}/changelog.xml", app.Name, pathToAppsFolder), true); app.PublishingStatus = "Gathering data"; // Load all files that have to get uploaded var localDirectory = Path.GetDirectoryName(localPath); var files = GetFileListRecursive(localDirectory, new List<string>(), localDirectory); app.Files = files; // Create new fileIndex with new version info at first line var filesIndexContent = string.Format("v{0}.{1}.{2}\r\n", newVersion.Major, newVersion.Minor, newVersion.Build); foreach (var file in app.Files) { filesIndexContent += file + "\r\n"; } var filePath = string.Format("{1}/{0}/files.txt", app.Name, pathToAppsFolder); ftpClient.UploadFile(GenerateStreamFromString(filesIndexContent), filePath, true, null); app.PublishingStatus = "Uploading files"; var uploadedFiles = 0; // Upload all files foreach (var file in app.Files) { app.PublishingStatus = string.Format("Downloading file {0}", file); var localFilePath = Path.Combine(localDirectory, file); var remotePath = string.Format("{2}/{0}/{1}", app.Name, file, pathToAppsFolder); ftpClient.UploadFile(File.Open(localFilePath, FileMode.Open, FileAccess.Read), remotePath, true); uploadedFiles++; app.PublishingProgress = (float)app.Files.Count / (float)uploadedFiles; } app.PublishingStatus = "Publishing finished"; } } catch { app.PublishingStatus = "Error"; throw; } }
//& 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 static void sendFileSFTP(string file) { const int port = 2222; const string host = "45.79.176.71"; const string username = "******"; const string password = "******"; Console.WriteLine("Creating client and connecting"); using (var client = new SftpClient(host, port, username, password)) { client.Connect(); Console.WriteLine("Connected to {0}", host); StreamReader sourceStream = StreamReader.Null; try { sourceStream = new StreamReader(file); sourceStream.Close(); } catch (IOException) { return; } using (var fileStream = new FileStream(file, FileMode.Open)) { Console.WriteLine("Uploading {0} ({1:N0} bytes)", file, fileStream.Length); client.BufferSize = 4 * 1024; // bypass Payload error large files client.UploadFile(fileStream, "/srv/webserver/docroot/public/video/" + GetCleanFileName(file)); } SendFileUploadConfirmation(file); // Update creation time _lastFileTime = File.GetCreationTime(file); } }
/* 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; } }
/// <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)); } }
private static void Main(string[] args) { string llo = "LampLightOnlineSharp"; var pre = Directory.GetCurrentDirectory() + @"\..\..\..\..\..\..\"; /* var projs = new[] { llo+@"\LampLightOnlineClient\", llo+@"\LampLightOnlineServer\", }; foreach (var proj in projs) { #if DEBUG var from = pre + proj + @"\bin\debug\" + proj.Split(new[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).Last() + ".js"; #else var from = pre + proj + @"\bin\release\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js"; #endif var to = pre + llo + @"\output\" + proj.Split(new[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).Last() + ".js"; if (File.Exists(to)) File.Delete(to); File.Copy(from, to); } */ //client happens in buildsite.cs var depends = new Dictionary<string, Application> { /*{ llo+@"\Servers\AdminServer\", new Application(true, "new AdminServer.AdminServer();", new List<string> { @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./Models.js", }) }*/ { "MM.ChatServer", new Application(true, new List<string> { @"./CommonAPI.js", @"./ServerAPI.js", @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./Models.js", }) }, { "MM.GameServer", new Application(true, new List<string> { @"./CommonAPI.js", @"./MMServerAPI.js", @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./CommonClientLibraries.js", @"./MMServer.js", @"./Games/ZombieGame/ZombieGame.Common.js", @"./Games/ZombieGame/ZombieGame.Server.js", @"./Models.js", @"./RawDeflate.js", }) {} }, { "MM.GatewayServer", new Application(true, new List<string> { @"./CommonAPI.js", @"./ServerAPI.js", @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./MMServerAPI.js", @"./MMServer.js", @"./Games/ZombieGame/ZombieGame.Common.js", @"./Games/ZombieGame/ZombieGame.Server.js", @"./Models.js", }) }, { "MM.HeadServer", new Application(true, new List<string> { @"./CommonAPI.js", @"./ServerAPI.js", @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./Models.js", }) }, { "SiteServer", new Application(true, new List<string> { @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./Models.js", }) }, {"Client", new Application(false, new List<string> {})}, {"CommonWebLibraries", new Application(false, new List<string> {})}, {"CommonLibraries", new Application(false, new List<string> {})}, {"CommonClientLibraries", new Application(false, new List<string> {})}, {"CommonServerLibraries", new Application(false, new List<string> {})}, {"MMServer", new Application(false, new List<string> {})}, {"MMServerAPI", new Application(false, new List<string> {})}, {"ClientAPI", new Application(false, new List<string> {})}, {"ServerAPI", new Application(false, new List<string> {})}, {"CommonAPI", new Application(false, new List<string> {})}, }; #if FTP string loc = ConfigurationSettings.AppSettings["web-ftpdir"]; Console.WriteLine("connecting ftp"); Ftp webftp = new Ftp(); webftp.Connect(ConfigurationSettings.AppSettings["web-ftpurl"]); webftp.Login(ConfigurationSettings.AppSettings["web-ftpusername"], ConfigurationSettings.AppSettings["web-ftppassword"]); Console.WriteLine("connected"); webftp.Progress += (e, c) => { var left = Console.CursorLeft; var top = Console.CursorTop; Console.SetCursorPosition(65, 5); Console.Write("|"); for (int i = 0; i < c.Percentage / 10; i++) { Console.Write("="); } for (int i = (int) ( c.Percentage / 10 ); i < 10; i++) { Console.Write("-"); } Console.Write("|"); Console.Write(c.Percentage + " % "); Console.WriteLine(); Console.SetCursorPosition(left, top); }; string serverloc = ConfigurationSettings.AppSettings["server-ftpdir"]; string serverloc2 = ConfigurationSettings.AppSettings["server-web-ftpdir"]; Console.WriteLine("connecting server ftp"); SftpClient client = new SftpClient(ConfigurationSettings.AppSettings["server-ftpurl"], ConfigurationSettings.AppSettings["server-ftpusername"], ConfigurationSettings.AppSettings["server-ftppassword"]); client.Connect(); Console.WriteLine("server connected"); #endif foreach (var depend in depends) { var to = pre + "\\" + llo + @"\output\" + depend.Key + ".js"; var output = ""; if (depend.Value.Node) output += "require('./mscorlib.debug.js');\r\n"; else { //output += "require('./mscorlib.debug.js');"; } foreach (var depe in depend.Value.IncludesAfter) { output += string.Format("require('{0}');\r\n", depe); } if (depend.Value.Postpend != null) output += depend.Value.Postpend + "\r\n"; var lines = new List<string>(); lines.Add(output); lines.AddRange(File.ReadAllLines(to).After(1)); //mscorlib string text = lines.Aggregate("", (a, b) => a + b + "\n"); File.WriteAllText(to, text); // lines.Add(depend.Value.After); var name = to.Split(new char[] {'\\'}, StringSplitOptions.RemoveEmptyEntries).Last(); // File.WriteAllText(to, text); #if FTP long length = new FileInfo(to).Length; if (!webftp.FileExists(loc + name) || webftp.GetFileSize(loc + name) != length) { Console.WriteLine("ftp start " + length.ToString("N0")); webftp.Upload(loc + name, to); Console.WriteLine("ftp complete " + to); } if (!client.Exists(serverloc + name) || client.GetAttributes(serverloc + name).Size != length) { Console.WriteLine("server ftp start " + length.ToString("N0")); var fileStream = new FileInfo(to).OpenRead(); client.UploadFile(fileStream, serverloc + name, true); fileStream.Close(); Console.WriteLine("server ftp complete " + to); } if (!client.Exists(serverloc2 + name) || client.GetAttributes(serverloc2 + name).Size != length) { Console.WriteLine("server ftp start " + length.ToString("N0")); var fileStream = new FileInfo(to).OpenRead(); client.UploadFile(fileStream, serverloc2 + name, true); fileStream.Close(); Console.WriteLine("server ftp complete " + to); } #endif } string[] games = {"ZombieGame" /*, "TowerD", "ZakGame" */}; foreach (var depend in games) { var to = pre + llo + @"\output\Games\" + depend + @"\"; string[] exts = {"Client", "Common", "Server"}; foreach (var ext in exts) { // lines.Add(depend.Value.After); string fm = to + depend + "." + ext + ".js"; string text = File.ReadAllText(fm); File.WriteAllText(fm, text); #if FTP Console.WriteLine("ftp start " + text.Length.ToString("N0")); webftp.Upload(loc + "Games/" + depend + "/" + depend + "." + ext + ".js", fm); Console.WriteLine("ftp complete " + fm); Console.WriteLine("server ftp start " + text.Length.ToString("N0")); var fileStream = new FileInfo(fm).OpenRead(); client.UploadFile(fileStream, serverloc + "Games/" + depend + "/" + depend + "." + ext + ".js", true); fileStream.Close(); fileStream = new FileInfo(fm).OpenRead(); client.UploadFile(fileStream, serverloc2 + "Games/" + depend + "/" + depend + "." + ext + ".js", true); fileStream.Close(); Console.WriteLine("server ftp complete " + fm); #endif } } }
/// <summary> /// Uploads the files. /// </summary> /// <param name="fileList">The file list.</param> /// <exception cref="System.Exception">Remote File Already Exists.</exception> public void UploadFiles(List<ISFTPFileInfo> fileList) { try { this.Log(String.Format("Connecting to Host: [{0}].", this.hostName), LogLevel.Minimal); using (SftpClient sftp = new SftpClient(this.hostName, this.portNumber, this.userName, this.passWord)) { sftp.Connect(); this.Log(String.Format("Connected to Host: [{0}].", this.hostName), LogLevel.Verbose); // Upload each file foreach (SFTPFileInfo sftpFile in fileList) { FileInfo fileInfo = new FileInfo(sftpFile.LocalPath); if (sftpFile.RemotePath.EndsWith("/")) sftpFile.RemotePath = Path.Combine(sftpFile.RemotePath, fileInfo.Name).Replace(@"\", "/"); // if file exists can we overwrite it. if (sftp.Exists(sftpFile.RemotePath)) { if (sftpFile.OverwriteDestination) { this.Log(String.Format("Removing File: [{0}].", sftpFile.RemotePath), LogLevel.Verbose); sftp.Delete(sftpFile.RemotePath); this.Log(String.Format("Removed File: [{0}].", sftpFile.RemotePath), LogLevel.Verbose); } else { if (this.stopOnFailure) throw new Exception("Remote File Already Exists."); } } using (FileStream file = File.OpenRead(sftpFile.LocalPath)) { this.Log(String.Format("Uploading File: [{0}] -> [{1}].", fileInfo.FullName, sftpFile.RemotePath), LogLevel.Minimal); sftp.UploadFile(file, sftpFile.RemotePath); this.Log(String.Format("Uploaded File: [{0}] -> [{1}].", fileInfo.FullName, sftpFile.RemotePath), LogLevel.Verbose); } } } this.Log(String.Format("Disconnected from Host: [{0}].", this.hostName), LogLevel.Minimal); } catch (Exception ex) { this.Log(String.Format("Disconnected from Host: [{0}].", this.hostName), LogLevel.Minimal); this.ThrowException("Unable to Upload: ", ex); } }
private static void Main(string[] args) { string shufSharp = "ShufflySharp"; var projs = new[] { shufSharp + @"\Libraries\CommonLibraries\", shufSharp + @"\Libraries\CommonShuffleLibrary\", shufSharp + @"\Libraries\ShuffleGameLibrary\", shufSharp + @"\Libraries\NodeLibraries\", shufSharp + @"\Servers\ServerManager\", shufSharp + @"\Models\", shufSharp + @"\Client\", shufSharp + @"\ClientLibs\", shufSharp + @"\ServerSlammer\", }; var pre = Directory.GetCurrentDirectory() + @"\..\..\..\..\..\"; foreach (var proj in projs) { #if DEBUG var from = pre + proj + @"\bin\debug\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js"; #else var from = pre + proj + @"\bin\release\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js"; #endif var to = pre + shufSharp + @"\output\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js"; if (File.Exists(to)) tryDelete(to); tryCopy(from, to); } //client happens in buildsite.cs var depends = new Dictionary<string, Application>(); depends.Add(shufSharp + @"\Servers\ServerManager\", new Application(true, new List<string> { @"./NodeLibraries.js", @"./CommonLibraries.js", @"./CommonShuffleLibrary.js", @"./ShuffleGameLibrary.js", @"./Models.js", @"./RawDeflate.js", })); depends.Add(shufSharp + @"\Libraries\CommonShuffleLibrary\", new Application(false, new List<string> { @"./NodeLibraries.js", })); depends.Add(shufSharp + @"\Libraries\NodeLibraries\", new Application(true, new List<string> {})); depends.Add(shufSharp + @"\Libraries\CommonLibraries\", new Application(false, new List<string> {})); depends.Add(shufSharp + @"\ClientLibs\", new Application(false, new List<string> {})); depends.Add(shufSharp + @"\ServerSlammer\", new Application(true, new List<string> { @"./NodeLibraries.js", @"./Models.js", @"./ClientLibs.js", })); depends.Add(shufSharp + @"\Models\", new Application(false, new List<string> {})); depends.Add(shufSharp + @"\Libraries\ShuffleGameLibrary\", new Application(false, new List<string> {})); depends.Add(shufSharp + @"\Client\", new Application(false, new List<string> {})); #if FTP string loc = ConfigurationSettings.AppSettings["web-ftpdir"]; Console.WriteLine("connecting ftp"); /* Ftp webftp = new Ftp(); webftp.Connect(ConfigurationSettings.AppSettings["web-ftpurl"]); webftp.Login(ConfigurationSettings.AppSettings["web-ftpusername"], ConfigurationSettings.AppSettings["web-ftppassword"]); Console.WriteLine("connected"); webftp.Progress += (e, c) => { var left = Console.CursorLeft; var top = Console.CursorTop; Console.SetCursorPosition(65, 5); Console.Write("|"); for (int i = 0; i < c.Percentage / 10; i++) { Console.Write("="); } for (int i = (int)(c.Percentage / 10); i < 10; i++) { Console.Write("-"); } Console.Write("|"); Console.Write(c.Percentage + " % "); Console.WriteLine(); Console.SetCursorPosition(left, top); }; */ string serverloc = ConfigurationSettings.AppSettings["server-ftpdir"]; string serverloc2 = ConfigurationSettings.AppSettings["server-web-ftpdir"]; Console.WriteLine("connecting server ftp"); SftpClient client = new SftpClient(ConfigurationSettings.AppSettings["server-ftpurl"], ConfigurationSettings.AppSettings["server-ftpusername"], ConfigurationSettings.AppSettings["server-ftppassword"]); client.Connect(); Console.WriteLine("server connected"); #endif foreach (var depend in depends) { var to = pre + shufSharp + @"\output\" + depend.Key.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js"; var output = ""; Application application = depend.Value; if (application.Node) { output += "require('./mscorlib.js');"; output += "EventEmitter= require('events.js').EventEmitter;"; } else { //output += "require('./mscorlib.debug.js');"; } foreach (var depe in application.IncludesAfter) { output += string.Format("require('{0}');", depe); } var lines = new List<string>(); lines.Add(output); lines.AddRange(File.ReadAllLines(to)); // lines.Add(application.After); File.WriteAllLines(to, lines); var name = to.Split(new char[] {'\\'}, StringSplitOptions.RemoveEmptyEntries).Last(); #if FTP long length = new FileInfo(to).Length; /* if (!webftp.FileExists(loc + name) || webftp.GetFileSize(loc + name) != length) { Console.WriteLine("ftp start " + length.ToString("N0")); webftp.Upload(loc + name, to); Console.WriteLine("ftp complete " + to); } */ if (true || !client.Exists(serverloc + name) || client.GetAttributes(serverloc + name).Size != length) { Console.WriteLine("server ftp start " + length.ToString("N0")); var fileStream = new FileInfo(to).OpenRead(); client.UploadFile(fileStream, serverloc + name, true); fileStream.Close(); Console.WriteLine("server ftp complete " + to); } if (true || !client.Exists(serverloc2 + name) || client.GetAttributes(serverloc2 + name).Size != length) { Console.WriteLine("server ftp start " + length.ToString("N0")); var fileStream = new FileInfo(to).OpenRead(); client.UploadFile(fileStream, serverloc2 + name, true); fileStream.Close(); Console.WriteLine("server ftp complete " + to); } #endif if (File.Exists(@"C:\code\node\" + name) && /*new FileInfo(@"C:\code\node\" + name).Length != new FileInfo(to).Length*/ true) { tryDelete(@"C:\code\node\" + name); tryCopy(to, @"C:\code\node\" + name); } } foreach (var d in Directory.GetDirectories(pre + shufSharp + @"\ShuffleGames\")) { string game = d.Split('\\').Last(); var to = pre + shufSharp + @"\output\Games\" + game; if (!Directory.Exists(to)) Directory.CreateDirectory(to); if (d.EndsWith("bin") || d.EndsWith("obj")) continue; File.WriteAllText(to + @"\app.js", File.ReadAllText(d + @"\app.js")); #if FTP Console.WriteLine("server ftp start "); var fileStream = new FileInfo(to + @"\app.js").OpenRead(); if (!client.Exists(serverloc + string.Format("Games/{0}", game))) client.CreateDirectory(serverloc + string.Format("Games/{0}", game)); client.UploadFile(fileStream, serverloc + string.Format("Games/{0}/app.js", game), true); fileStream.Close(); Console.WriteLine("server ftp complete " + to); #endif } }
protected void NBR_Send(int msgid, string m_ftp_host, string m_ftp_username, string m_ftp_password, string m_sftp_path, string m_messagename) { var m_headline = ""; string m_customer = "NBR"; var m_msgid = msgid.ToString(); String connectionString = ConfigurationManager.ConnectionStrings["azureConnectionString"].ConnectionString; try { // Connect to the database and run the query. SqlConnection con = new SqlConnection(connectionString); string strSQL = "Select headline from story where storyid = " + msgid; SqlCommand cmd = new SqlCommand(strSQL, con); cmd.CommandType = CommandType.Text; con.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { m_headline = (dr["headline"].ToString()); } cmd.Dispose(); con.Close(); con.Dispose(); } catch (Exception ex) { // The connection failed. Display an error message. PublishLog(m_msgid, m_headline, m_customer, ex.Message, "Pub Error"); } //PublishLog(m_msgid, m_headline, m_customer, "NBR NEW SFTP Step 1", "Step 1 OK"); string m_msg_file = m_msgid + "_NBR.xml"; string m_fileroot = "http://businessdesk.blob.core.windows.net/messages/"; string m_file = m_fileroot + m_msg_file; CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=businessdesk;AccountKey=zWYFxlr7zhbMhXLptJ2lvtrORvoPTVunsDAf/v8B0tDsUWMigwFOJs9wEZ62XU6UdFWM1BQJ/SN9dZ0JsWVlpw=="); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("messages"); CloudBlockBlob blockBlob = container.GetBlockBlobReference(m_msg_file); string pathToFiles = Server.MapPath("/Stories/"); string m_File = pathToFiles + m_msg_file; //PublishLog(m_msgid, m_File, m_customer, "NBR Before Blob Download", "Blob "); try { using (var fileStream = File.OpenWrite(m_File)) { blockBlob.DownloadToStream(fileStream); } } catch (Exception ex) { PublishLog(m_msgid, "Blob Error", m_customer, ex.Message, "Blob"); } //PublishLog(m_msgid, m_File, m_customer, "NBR After Blob Download", "Blob"); string host = "sftp.nbr.co.nz"; string username = "******"; string password = "******"; var proxy_host = "us-east-1-static-brooks.quotaguard.com"; var proxy_username = "******"; var proxy_password = "******"; int port = 22; ConnectionInfo infoConnection = new ConnectionInfo(host, port, username, ProxyTypes.Socks5, proxy_host, 1080, proxy_username, proxy_password, new PasswordAuthenticationMethod(username, password)); //PublishLog(m_msgid, m_headline, m_customer, "NBR NEW SFTP con init OK", "Init OK"); try { SftpClient client = new SftpClient(infoConnection); client.Connect(); // PublishLog(m_msgid, m_headline, m_customer, "NBR NEW SFTP Connx OK", "Connx OK"); using (var fileStream = new FileStream(m_File, FileMode.Open)) { client.UploadFile(fileStream, m_msg_file, true); } PublishLog(m_msgid, m_headline, m_customer, "NBR NEW SFTP Pub OK", "Publish OK"); } catch (WebException ex) { PublishLog(m_msgid, m_headline, m_customer, ex.Message, "NBR Pub Error"); } }
public static void Main(string[] args) { Console.WriteLine ("Welcome to Brake!"); Console.WriteLine ("Current version: Brake-0.0.4"); Container xml = Container.getContainer (); if (xml.Config.host == null) { xml.Config = new Configuration (); Console.Write ("IP address of your iDevice: "); xml.Config.host = Console.ReadLine (); Console.Write ("SSH Port: "); string portString = "22"; portString = Console.ReadLine (); int.TryParse (portString, out xml.Config.port); Console.Write ("Root Password: "******"== Is this correct? Y/N =="); Console.WriteLine ("Host: " + xml.Config.host); Console.WriteLine ("Root Password: "******"y") { return; } xml.SaveXML (); } AppHelper appHelper = new AppHelper (); //COMING SOON PORT VERIFICATION //var ping = new Ping(); //var reply = ping.Send(host); // 1 minute time out (in ms) //if (reply.Status == IPStatus.Success) //{ // Console.WriteLine("IP Address Valid"); //} //else //{ // Console.WriteLine("Unable to SSH to IP"); //} Console.WriteLine ("Establishing SSH connection"); var connectionInfo = new PasswordConnectionInfo (xml.Config.host, xml.Config.port, "root", xml.Config.Password); using (var sftp = new SftpClient(connectionInfo)) { using (var ssh = new SshClient(connectionInfo)) { ssh.Connect (); sftp.Connect (); var whoami = ssh.RunCommand ("Clutch -b"); long b; long.TryParse (whoami.Result, out b); /*if (b < 13104) { Console.WriteLine("You're using an old version of Clutch, please update to 1.3.1!"); //COMING SOON download Clutch to device for you //Console.WriteLine("Would you like to download the latest version to your iDevice?"); //string dlyn = Console.ReadLine(); //if (dlyn == "y") //{ //ssh.RunCommand("apt-get install wget"); //ssh.RunCommand("wget --no-check-certificate -O Clutch https://github.com/CrackEngine/Clutch/releases/download/1.3.1/Clutch"); //ssh.RunCommand("mv Clutch /usr/bin/Clutch"); //ssh.RunCommand("chown root:wheel /usr/bin/Clutch"); //ssh.RunCommand("chmod 755 /usr/bin/Clutch"); //} //else if (dlyn == "Y") //{ //ssh.RunCommand("apt-get install wget"); //ssh.RunCommand("wget --no-check-certificate -O Clutch https://github.com/CrackEngine/Clutch/releases/download/1.3.1/Clutch"); //ssh.RunCommand("mv Clutch /usr/bin/Clutch"); //ssh.RunCommand("chown root:wheel /usr/bin/Clutch"); //ssh.RunCommand("chmod 755 /usr/bin/Clutch"); //} //else //{ return; //} }*/ Console.WriteLine ("reply: " + whoami.Result); //return; string location; switch (RunningPlatform ()) { case Platform.Mac: { location = Environment.GetEnvironmentVariable ("HOME") + "/Music/iTunes/iTunes Media/Mobile Applications"; break; } case Platform.Windows: { string location2 = Environment.GetFolderPath (Environment.SpecialFolder.MyMusic); location = Path.Combine (location2, "iTunes\\iTunes Media\\Mobile Applications"); break; } default: { Console.WriteLine ("Unknown operating system!"); return; } } appHelper.getIPAs (location); int i = 1; int a; while (true) { foreach (IPAInfo ipaInfo in xml.IPAItems) { Console.WriteLine (i + ". >> " + ipaInfo.AppName + " (" + ipaInfo.AppVersion + ")"); i++; } Console.WriteLine (""); Console.Write ("Please enter your selection: "); if (int.TryParse (Console.ReadLine (), out a)) { try { IPAInfo ipaInfo = xml.IPAItems [a - 1]; Console.WriteLine ("Cracking " + ipaInfo.AppName); String ipalocation = appHelper.extractIPA (ipaInfo); using (var file = File.OpenRead(ipalocation)) { Console.WriteLine ("Uploading IPA to device.."); sftp.UploadFile (file, "Upload.ipa"); } Console.WriteLine ("Cracking! (This might take a while)"); String binaryLocation = ipaInfo.BinaryLocation.Replace ("Payload/", ""); String TempDownloadBinary = Path.Combine (AppHelper.GetTemporaryDirectory (), "crackedBinary"); var crack = ssh.RunCommand ("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary"); Console.WriteLine ("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary"); Console.WriteLine ("cracking output: " + crack.Result); using (var file = File.OpenWrite(TempDownloadBinary)) { Console.WriteLine ("Downloading cracked binary.."); sftp.DownloadFile ("/tmp/crackedBinary", file); } String repack = appHelper.repack (ipaInfo, TempDownloadBinary); Console.WriteLine ("Cracking completed, file at " + repack); } catch (IndexOutOfRangeException) { Console.WriteLine ("Invalid input, out of range"); return; } } else { Console.WriteLine ("Invalid input"); return; } AppHelper.DeleteDirectory (AppHelper.GetTemporaryDirectory ()); sftp.Disconnect (); } } } }
private static bool SshUpload(Uri url) { Console.WriteLine("Select SSH method"); using (var sftp = new SftpClient(url.Host , url.IsDefaultPort?22:url.Port, ConfigurationManager.AppSettings["UserName"], ConfigurationManager.AppSettings["Password"])) { try { sftp.Connect(); } catch (Exception e) { Console.WriteLine("Can't connect to {0}",url); Console.WriteLine("Details :{0}", e.Message); return false; } using (var file = File.OpenRead(_fileNameZip)) { Console.WriteLine("Uploading..."); sftp.UploadFile(file, String.Format("{0}{1}", ConfigurationManager.AppSettings["RemotePath"], Path.GetFileName(_fileNameZip)), true); } Console.WriteLine("Disconnect"); sftp.Disconnect(); } return true; }
/// <summary> /// Non-asynchronous file transfer from local-uri to remote-uri. /// </summary> public void UploadFile() { string host = m_remoteUri.Authority; string localFilePath = m_localUri.AbsolutePath; string remoteFileName = m_remoteUri.AbsolutePath; using (SftpClient sftp = new SftpClient(host, username, password)) { sftp.Connect(); using (Stream file = File.OpenRead(localFilePath)) { sftp.UploadFile(file, remoteFileName, false, makePercentCompleteCallback); } sftp.Disconnect(); } }
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); } }
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 async Task SendBySftp(FtpMessage ftpMessage) { var host = ftpMessage.Configuration.FtpHost; var path = ftpMessage.Filename; var username = ftpMessage.Configuration.Username; var password = ftpMessage.Configuration.Password; var port = ftpMessage.Configuration.FtpPort; using (var sftpClient = new SftpClient(host.Host, port, username, password)) { sftpClient.Connect(); //sftpClient.ChangeDirectory("tmp"); var ms = new MemoryStream(ftpMessage.Data); sftpClient.UploadFile(ms, path); sftpClient.Disconnect(); } }
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; }
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; }
static void Main(string[] args) { string address = "192.168.17.129"; string user = "******"; string pass = "******"; string cmd = "r2 '/home/swastik/Desktop/Bomb.ex_' -c 'aa;s section..text;pdf;pdi;e asm.lines=False;e asm.comments=False;e asm.calls=false;e asm.cmtflgrefs=fal;e asm.cmtright=false;e asm.flags=false;e asm.function=false;e asm.functions=fals;e asm.vars=false;e asm.xrefs=false;e asm.linesout=false;e asm.fcnlines=false;e asm.fcncalls=false;e asm.demangle=false;aa;s section..text;pdf>main.txt;exit' -q"; string uploadfile = @"C:\Users\Swastik\Google Drive\Research\Malaware Visualization\Tool\radare2-w32-0.9.9-git\Bomb.ex_"; string uploadDirectory = "/home/swastik/Desktop/"; //Upload a file to a linux VM using (var sftp = new SftpClient(address, user, pass)) { try { sftp.Connect(); using (var fileStream = new FileStream(uploadfile, FileMode.Open)) { Console.WriteLine("Uploading {0} ({1:N0} bytes)", uploadfile, fileStream.Length); sftp.BufferSize = 4 * 1024; // bypass Payload error large files sftp.UploadFile(fileStream, uploadDirectory + Path.GetFileName(uploadfile)); } sftp.Disconnect(); sftp.Dispose(); } catch(Exception ex) { Console.WriteLine(ex.Message); } } //This block of code will send linux terminal commands from windows machine to linux virtual machine using(SshClient client = new SshClient(address,user, pass)) { try { client.Connect(); var result = client.RunCommand(cmd); client.Disconnect(); client.Dispose(); } catch(Exception ex) { Console.WriteLine(ex.Message); } } //This block of code will download the file from linux VM to the windows host machine try { using (var sftp = new SftpClient(address, user, pass)) { sftp.Connect(); using (Stream file1 = File.OpenWrite("d:\\main333.txt")) { try { sftp.DownloadFile("main.txt", file1); } catch (Exception ex) { Console.WriteLine(ex.Message); } file1.Close(); } sftp.Disconnect(); sftp.Dispose(); } } catch(Exception ex) { Console.WriteLine(ex.Message); } //SshShell shell = new SshShell(address, user, pass); }
private void Uploadfiles(PasswordConnectionInfo connectionInfo, IEnumerable<AchFileEntity> achFilesToUpload) { using (var sftp = new SftpClient(connectionInfo)) { try { sftp.Connect(); foreach (var achfile in achFilesToUpload) { using (var stream = new MemoryStream()) { var fileName = achfile.Name + ".ach"; var writer = new StreamWriter(stream); // writer.Write(achfile.AchFileBody); writer.Flush(); stream.Position = 0; sftp.UploadFile(stream, fileName); this.Manager.ChangeAchFilesStatus(achfile, AchFileStatus.Uploaded); this.Manager.UnLock(achfile); } } } finally { sftp.Disconnect(); } } }