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 static void CopyFileFromRemoteToLocal(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); var file = File.OpenWrite(localPath); client.DownloadFile(remotePath, file); file.Close(); client.Disconnect(); } }
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 static IEnumerable<SftpFile> GetList(string host, string folder, string userName, string password) { using (var sftp = new SftpClient(host, userName, password)) { sftp.ErrorOccurred += Sftp_ErrorOccurred; sftp.Connect(); var toReturn = sftp.ListDirectory(folder).ToList(); sftp.Disconnect(); return toReturn; } }
private async Task DownloadFilesWithSftpAsync(Endpoint endpoint, string decodedPass) { var client = new SftpClient(endpoint.Url, endpoint.Username, decodedPass); client.Connect(); SftpFile[] filesOnServer = (await this.ListRemoteDirectoriesAsync(client, endpoint.RemoteDirectory)).Where( x => !this.excludedListOfFiles.Any(y => x.Name.Equals(y))).ToArray(); var primaryLocalDirectory = endpoint.Destinations.FirstOrDefault(x => x.Type == DestinationType.Primary); var archiveLocalDirectory = endpoint.Destinations.FirstOrDefault(x => x.Type == DestinationType.Archive); var primaryAndArchiveAreNotExisting = primaryLocalDirectory == null || archiveLocalDirectory == null; if (primaryAndArchiveAreNotExisting) { progress.ReportLine("You haven't provided the primary or archive folder"); return; } var filteredLocalFiles = FilterLocalFiles(filesOnServer, GetFilesListInFolder(primaryLocalDirectory.Name)); await this.GetFilesAsync(filteredLocalFiles, endpoint.RemoteDirectory, primaryLocalDirectory.Name, client).ContinueWith(x => client.Disconnect()); this.ArchiveFiles(GetFilesListInFolder(primaryLocalDirectory.Name), primaryLocalDirectory, archiveLocalDirectory); }
private void checkFingerpint(ConnectionInfo con, string knownHostsPath) { _knownHosts = new KnownHostStore(knownHostsPath); using (Renci.SshNet.SftpClient client1 = new Renci.SshNet.SftpClient(con)) { client1.HostKeyReceived += (sender, eventArgs) => { eventArgs.CanTrust = CanTrustHost(client1.ConnectionInfo.Host, eventArgs); }; try { client1.Connect(); this.fingerprint = true; } catch (Exception) { this.error.setError("SF012", "unknown host"); this.channel = null; this.fingerprint = false; } finally { client1.Disconnect(); } } }
public override async ValueTask DisconnectAsync(CancellationToken ctk = default) { if (!_client.IsConnected) { return; } await Task.Run(() => _client.Disconnect(), ctk); }
public static void UploadFile(string localFileToUpload, string host, string targetFile, string userName, string password) { using (var sftp = new SftpClient(host, userName, password)) { sftp.OperationTimeout = new TimeSpan(0, 0, seconds: 40); sftp.Connect(); UploadFileWithOpenConnection(localFileToUpload, targetFile, sftp); sftp.Disconnect(); } }
public static void DeleteRemoteDirectory(string host, string directory, string username, string password) { using (var sftp = new SftpClient(host, username, password)) { sftp.Connect(); sftp.DeleteDirectory(directory); sftp.Disconnect(); } }
public void Disconnect() { if (_sftpClient != null) { _sftpClient.Disconnect(); } if (_scp != null) { _scp.Close(); } }
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(); } }
/// <summary> /// Defines a SFTP Client transaction /// </summary> /// <param name="_cred">The SSH transaction credentials</param> /// <param name="task">The Transaction task</param> public static void SFTPTransactionVoid(SiteCredentials _cred, Action <Renci.SshNet.SftpClient> task) { using (var client = new Renci.SshNet.SftpClient(_cred.Host, _cred.Port, _cred.User, _cred.Password)) { try { client.Connect(); task(client); client.Disconnect(); } catch (System.Exception exc) { Console.WriteLine(exc.Message); } } }
/// <summary> /// Defines a SFTP Client transaction /// </summary> /// <param name="_cred">The SSH transaction credentials</param> /// <param name="task">The Transaction task</param> /// <returns>The transaction result</returns> public static Object SFTPTransaction(SiteCredentials _cred, Func <Renci.SshNet.SftpClient, Object> task) { Object result = null; using (var client = new Renci.SshNet.SftpClient(_cred.Host, _cred.Port, _cred.User, _cred.Password)) { try { client.Connect(); result = task(client); client.Disconnect(); } catch (System.Exception exc) { Console.WriteLine(exc.Message); } } return(result); }
/// <summary> /// Test the credentials connection /// </summary> /// <param name="_cred">The credential connections</param> /// <param name="errMsg">The error message</param> /// <returns>True if the credentials are valid to connect to the host</returns> public static Boolean TestConnection(SiteCredentials _cred, out string errMsg) { Boolean result = true; errMsg = String.Empty; using (var client = new Renci.SshNet.SftpClient(_cred.Host, _cred.Port, _cred.User, _cred.Password)) { try { client.Connect(); client.Disconnect(); } catch (System.Exception exc) { errMsg = Message.MSG_ERR_NO_CONN + ".\n" + exc.Message; result = false; } } return(result); }
public override async Task Disconnect() { var caughtException = default(Exception); await Task.Run(() => { try { _sftpc.Disconnect(); } catch (Exception ex) { ex.LogException(); caughtException = ex; } }); if (caughtException != default(Exception)) { throw caughtException; } }
public static bool DoexRemoteFolderExist(string host, string user, string password, 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 r = client.Exists(remotePath); client.Disconnect(); return r; } }
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(); }
/// <inheritdoc /> public void CheckConnection() { _sftpClient.Connect(); _sftpClient.Disconnect(); }
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(); } }
private async Task<FtpMessage> GetFromSftp(FtpConfiguration config, string path) { var host = config.FtpHost.Host; var username = config.Username; var password = config.Password; var port = config.FtpPort; using (var sftpClient = new SftpClient(host, port, username, password)) { sftpClient.Connect(); var data = sftpClient.ReadAllBytes(path); sftpClient.Disconnect(); return new FtpMessage { Configuration = config, Data = data, Filename = path }; } }
public override void Send(string overrideValue) { overrideValue = overrideValue.Replace("\r", "").Replace("\n", ""); try { int port = 22; var hostname = Settings.SFTPHostname; if (hostname.StartsWith("sftp://")) { hostname = hostname.Replace("sftp://", ""); } if (hostname.Contains(":")) { var parts = hostname.Split(':'); hostname = parts[0]; port = int.Parse(parts[1]); } ConnectionInfo conn = new ConnectionInfo(hostname, port, Settings.SFTPUsername, new AuthenticationMethod[1] { new PasswordAuthenticationMethod(Settings.SFTPUsername, Settings.SFTPPassword) }); using (var client = new SftpClient(conn)) { client.Connect(); var file = client.CreateText(currentDespatch.SalesOrderNumber + ".csv"); try { file.WriteLine(overrideValue); } finally { file.Close(); } var path = Path.Combine(Path.GetDirectoryName(Settings.LabelDirectory), "MHI.csv"); File.AppendAllText(path, string.Format("\"{0}\",{1}\n", DateTime.Now.ToLongTimeString(), overrideValue)); client.Disconnect(); } WriteLog(string.Format("Sent request to {0} tracking number {1} service type {2}...", PluginName, Settings.MHIPrefix + currentDespatch.SalesOrderNumber, currentDespatch.ServiceTypeName), Color.Black); var ps = new PrinterSettings { PrinterName = Settings.PrinterName }; var maxResolution = ps.PrinterResolutions.OfType<PrinterResolution>() .OrderByDescending(r => r.X) .ThenByDescending(r => r.Y) .First(); PrintDocument pd = new PrintDocument(); pd.PrinterSettings.PrinterName = Settings.PrinterName; pd.PrintController = new StandardPrintController(); pd.DefaultPageSettings.Margins = pd.PrinterSettings.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0); pd.DefaultPageSettings.Landscape = true; pd.OriginAtMargins = true; Image label = generateLabel(maxResolution.X, maxResolution.Y); label.Save(Path.Combine(Settings.LabelDirectory, currentDespatch.SalesOrderNumber + "-" + currentDespatch.DespatchNumber + ".png"), ImageFormat.Png); pd.PrintPage += (sndr, args) => { args.Graphics.DrawImage(label, args.MarginBounds); }; pd.Print(); WriteLog(string.Format("Print request sent to {0}...", Settings.PrinterName), Color.Black); label.Dispose(); if (this.NeedsCN22(currentDespatch.ShippingAddressCountry)) { PrintDocument pd22 = new PrintDocument(); pd22.PrinterSettings.PrinterName = Settings.PrinterName; pd22.PrintController = new StandardPrintController(); pd22.DefaultPageSettings.Margins = pd.PrinterSettings.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0); pd22.DefaultPageSettings.Landscape = false; pd22.OriginAtMargins = true; var cn22label = this.GenerateCN22(currentDespatch.SalesOrderNumber, currentDespatch.Items); pd22.PrintPage += (sndr, args) => { args.Graphics.DrawImage(cn22label, args.MarginBounds); }; pd22.Print(); cn22label.Dispose(); } trackingNumber = Settings.MHIPrefix + currentDespatch.SalesOrderNumber; Result = Settings.MHIPrefix + currentDespatch.SalesOrderNumber; } catch (Exception e) { WriteLog(string.Format("Exception on SEND:\n{0}", e.ToString()), Color.Red); } }
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 CreateRemoteFolder(string host, string user, string password, 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(); if (!DoexRemoteFolderExist(host, user, password, remotePath)) { RunCommand(host, user, password, "sudo mkdir -p '" + remotePath + "'"); RunCommand(host, user, password, "sudo chmod -R 777 '" + remotePath + "'"); } client.Disconnect(); } }
// 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); }
public void ftpDisconnect() { ftp.Disconnect(); }
//& 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 void DisconnectClient() { _sftpClient.Disconnect(); }
/// <summary> /// Non-asynchronous file transfer from remote-uri to local-uri. /// </summary> public void DownloadFile() { string host = m_remoteUri.Authority; string localFilePath = m_localUri.AbsolutePath; string remoteFileName = m_remoteUri.AbsolutePath; using (SftpClient sftp = new SftpClient(host, username, password)) { //sftp.ListDirectory(Path.GetDirectoryName(m_remoteUri)) //.First<SftpFile>((f) => {f.FullName.Equals(remoteFileName)}); sftp.Connect(); using (FileStream file = File.OpenWrite(localFilePath)) { sftp.DownloadFile(remoteFileName, file, makePercentCompleteCallback); } sftp.Disconnect(); } }
private bool tryInitConnection() { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name); var ip = ConfigurationManager.AppSettings["HostIP"]; var userName = ConfigurationManager.AppSettings["HostPass"]; var pass = ConfigurationManager.AppSettings["UserName"]; try { sshConn = new SshClient(ip, userName, pass); sshConn.Connect(); sshConn.Disconnect(); } catch { return false; } try { scpClient = new ScpClient(ip, userName, pass); scpClient.Connect(); scpClient.Disconnect(); } catch { return false; } try { sftpConn = new SftpClient(ip, userName, pass); sftpConn.Connect(); sftpConn.Disconnect(); return true; } catch { return false; } }
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 (); } } } }
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> /// 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(); } }
public static void DeleteRemoteFile(string host, string file, string username, string password) { using (var sftp = new SftpClient(host, username, password)) { sftp.Connect(); sftp.Delete(file); sftp.Disconnect(); } }
private void UploadFilesFromFilemanager() { string destpathroot = txtRemoteFolderPath.Text; if (!destpathroot.EndsWith("/")) { destpathroot += "/"; } var filelist = new Dictionary<string, string>(); foreach (var item in lvLocalBrowser.SelectedItems.Cast<EXImageListViewItem>().Where(item => (string) item.Tag != "[..]")) { if ((string)item.Tag == "File") { filelist.Add(item.MyValue, destpathroot + Path.GetFileName(item.MyValue)); } if ((string)item.Tag == "Folder") { string folder = Path.GetDirectoryName(item.MyValue); folder = folder.EndsWith("\\") ? folder : folder + "\\"; string[] files = Directory.GetFiles(item.MyValue, "*.*", SearchOption.AllDirectories); // Display all the files. foreach (string file in files) { filelist.Add(Path.GetFullPath(file), destpathroot + Path.GetFullPath(file).Replace(folder,"").Replace("\\","/")); } } } long fulllength = filelist.Sum(file => new FileInfo(file.Key).Length); MessageBox.Show(Tools.Misc.LengthToHumanReadable(fulllength)); var ssh = new SftpClient(txtHost.Text, int.Parse(this.txtPort.Text), txtUser.Text, txtPassword.Text); ssh.Connect(); ThreadPool.QueueUserWorkItem(state => { long totaluploaded = 0; foreach (var file in filelist) { CreatSSHDir(ssh, file.Value); var s = new FileStream(file.Key, FileMode.Open); var i = ssh.BeginUploadFile(s, file.Value) as SftpUploadAsyncResult; while (!i.IsCompleted) { SetProgressStatus(totaluploaded + (long)i.UploadedBytes, fulllength); } ssh.EndUploadFile(i); totaluploaded += s.Length; } MessageBox.Show(Language.SSHTransfer_StartTransfer_Upload_completed_); EnableButtons(); ssh.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; }
//turn this into some kind of interface public GatherResults DownloadQtyFiles(IVendorDirectory dir) { var files = new List<File>(); using (var sftp = new SftpClient(_config.QtyFileHost, _config.QtyFilePort, _config.QtyFileUsername, _config.QtyFilePassword)) { sftp.Connect(); dir.EnsureExists(); var localFile = dir.GetNewRawFile(FileTypes.Qty); using (var stream = new FileStream(localFile.Name.GetPath(), FileMode.Create)) { sftp.DownloadFile(_config.QtyFileName, stream); } files.Add(localFile); sftp.Disconnect(); } return new GatherResults { VendorHandle = dir.VendorHandle, Files = files }; }
public void go(string filename) { if (string.IsNullOrWhiteSpace(filename) || connInfo == null || config.sftpEnabled == false) { Log.Debug("Not doing SFTP because it wasn't configured properly or at all"); return; } FileInfo fi = new FileInfo(filename); if(!fi.Exists) { Log.Error("Can't open file for SFTPing: " + filename); return; } if(!fi.DirectoryName.StartsWith(config.localBaseFolder)) { Log.Error("Can't figure out where the file " + filename + " is relative to the base dir"); return; } string rel = fi.DirectoryName.Replace(config.localBaseFolder, ""); if (rel.StartsWith(Path.DirectorySeparatorChar.ToString())) rel = rel.Substring(1); SftpClient client = new SftpClient(connInfo); string accum = ""; try { client.Connect(); string thedir = null; foreach (string str in rel.Split(Path.DirectorySeparatorChar)) { accum = accum + "/" + str; thedir = config.sftpRemoteFolder + "/" + accum; thedir = thedir.Replace("//", "/"); Log.Debug("Trying to create directory " + thedir); try { client.CreateDirectory(thedir); } catch (SshException) { } } FileStream fis = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); client.BeginUploadFile(fis, thedir + "/" + fi.Name, true, (fini) => { FileStream ffini = fini.AsyncState as FileStream; if (ffini != null) ffini.Close(); if (client != null && client.IsConnected) { client.Disconnect(); } Log.Debug("Upload finished!"); if(Program.frm != null) Program.frm.SetStatus("Upload finished! / Ready"); }, fis, (pct) => { if(Program.frm != null) { Program.frm.SetStatus("Uploaded " + pct.ToString() + " bytes"); } }); } catch(Exception aiee) { Log.Error("Error: " + aiee.Message); Log.Debug(aiee.StackTrace); } }
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 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; }
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(); } } }