DownloadFile() public method

Downloads remote file specified by the path into the stream.
Method calls made by this method to output, may under certain conditions result in exceptions thrown by the stream.
is null. is null or contains only whitespace characters. Client is not connected. Permission to perform the operation was denied by the remote host. -or- A SSH command was denied by the server. was not found on the remote host. A SSH error where is the message from the remote host. The method was called after the client was disposed.
public DownloadFile ( string path, Stream output, Action downloadCallback = null ) : void
path string File to download.
output Stream Stream to write the file into.
downloadCallback Action The download callback.
return void
Example #1
11
        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 PollHandler()
        {
            var exchange = new Exchange(_processor.Route);
            var ipaddress = _processor.UriInformation.GetUriProperty("host");
            var username = _processor.UriInformation.GetUriProperty("username");
            var password = _processor.UriInformation.GetUriProperty("password");
            var destination = _processor.UriInformation.GetUriProperty("destination");
            var port = _processor.UriInformation.GetUriProperty<int>("port");
            var interval = _processor.UriInformation.GetUriProperty<int>("interval", 100);
            var secure = _processor.UriInformation.GetUriProperty<bool>("secure");

            do
            {
                Thread.Sleep(interval);
                try
                {
                    if (secure)
                    {
                        SftpClient sftp = null;
                        sftp = new SftpClient(ipaddress, port, username, password);
                        sftp.Connect();

                        foreach (var ftpfile in sftp.ListDirectory("."))
                        {
                            var destinationFile = Path.Combine(destination, ftpfile.Name);
                            using (var fs = new FileStream(destinationFile, FileMode.Create))
                            {
                                var data = sftp.ReadAllText(ftpfile.FullName);
                                exchange.InMessage.Body = data;

                                if (!string.IsNullOrEmpty(data))
                                {
                                    sftp.DownloadFile(ftpfile.FullName, fs);
                                }
                            }
                        }
                    }
                    else
                    {
                        ReadFtp(exchange);
                    }
                }
                catch (Exception exception)
                {
                    var msg = exception.Message;
                }
            } while (true);
        }
Example #3
2
        public void DownloadFile(ResourceNode node, string remotePath, string localPath)
        {
            if (_sftpClient != null)
            {
                using (var stream = File.OpenWrite(localPath))
                {
                    _sftpClient.DownloadFile(remotePath, stream);
                }

                //scp = _scpPool.GetSshSession(true, node);
                //scp.Recursive = recursive;
                //scp.Download(remotePath, new FileInfo(localPath));
            }
            else
            if (_scp != null)
            {
                _scp.Get(remotePath, localPath);
            }
            else
            {
                throw new Exception("No connection established to node for copy");
            }
        }
Example #4
2
        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();
        }
		public bool TryGetFileFromFtp(string fileName, DateTime lastUpdated)
		{
			if (!DirectoryUtil.VerifyDirectory(fileName))
			{
				return false;
			}

			var fileToDownload =  fileName;
			Log.Debug(string.Format("Attempting to download file " + fileToDownload));
			
			try
			{
				Log.Debug("Opening FTP Connection to " + Hostname);
				using (var client = new SftpClient(Hostname, Username, Password))
				{
					client.Connect();
					Log.Debug(string.Format("Connection to {0} opened.", Hostname));
					var fileUpdated = client.GetLastWriteTime(fileName);
					Log.Debug(string.Format("File {0} was last modified on {1}.", fileName, DateUtil.ToIsoDate(fileUpdated)));

					if (fileUpdated <= lastUpdated)
					{
						Log.Info(string.Format("Did not download file {0}, it was last modified {1} and we last processed it on {2}.",
																		fileName, DateUtil.ToIsoDate(fileUpdated), DateUtil.ToIsoDate(lastUpdated)), this);
						return false;
					}

					var outputPath = string.Format("{0}\\{1}", UserCsvImportSettings.CsvFolderPath, fileName);
					Log.Debug(string.Format("Downloading file {0} and saving to path {1}.", fileName, outputPath));
					using (var fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
					{
						client.DownloadFile(fileName, fileStream);
						Log.Debug("File successfully written to " + fileStream.Name);
					}
					Log.Debug("File Download complete.");
					Log.Debug("Updating timestamp.");
					File.SetLastWriteTime(outputPath, fileUpdated);
					Log.Debug("File timestamp set to " + fileUpdated.ToString());
				}
			}
			catch (Exception e)
			{
				Log.Error("File did not download successfully.", this);
				Log.Error(string.Format("Could not download file {0} from {1} using user {2}.", fileToDownload, Hostname, Username), e,
					this);
				return false;
				 
			}

			return true;
		}
 private void DownloadFile(string path, Stream output)
 {
     if (_sftpClient != null)
     {
         _sftpClient.DownloadFile(path, output);
     }
     else
     {
         _scpClient.Download(_scpDestinationDirectory + "/" + path, output);
     }
 }
Example #7
0
        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);
                }
            }
        }
Example #8
0
        /// <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();
            }
        }
Example #9
0
        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 ();
                    }
                }
            }
        }
Example #10
0
        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();
        }
        /// <summary>
        /// Downloads the files.
        /// </summary>
        /// <param name="fileList">The file list.</param>
        /// <param name="failRemoteNotExists">if set to <c>true</c> [fail remote not exists].</param>
        /// <exception cref="System.Exception">
        /// Local File Already Exists.
        /// </exception>
        public void DownloadFiles(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);

                    // Download each file
                    foreach (SFTPFileInfo filePath in fileList)
                    {
                        if (!sftp.Exists(filePath.RemotePath))
                        {
                            this.Log(String.Format("Remote Path Does Not Exist: [{0}].", this.hostName), LogLevel.Verbose);
                            if (this.stopOnFailure)
                                throw new Exception(String.Format("Remote Path Does Not Exist: [{0}]", filePath.RemotePath));
                            else
                                continue;
                        }

                        if (Directory.Exists(filePath.LocalPath))
                            filePath.LocalPath = Path.Combine(filePath.LocalPath, filePath.RemotePath.Substring(filePath.RemotePath.LastIndexOf("/") + 1));

                        // Can we overwrite the local file
                        if (!filePath.OverwriteDestination && File.Exists(filePath.LocalPath))
                            throw new Exception("Local File Already Exists.");

                        this.Log(String.Format("Downloading File: [{0}] -> [{1}].", filePath.RemotePath, filePath.LocalPath), LogLevel.Minimal);
                        using (FileStream fileStream = File.OpenWrite(filePath.LocalPath))
                        {
                            sftp.DownloadFile(filePath.RemotePath, fileStream);
                        }
                        this.Log(String.Format("File Downloaded: [{0}]", filePath.LocalPath), 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 Download: ", ex);
            }
        }
Example #12
0
 private void DownloadFile(SftpClient client, SftpFile file, string directory)
 {
     Console.WriteLine("Downloading {0}", file.FullName);
     using (Stream fileStream = File.OpenWrite(Path.Combine(directory, file.Name)))
     {
         client.DownloadFile(file.FullName, fileStream);
     }
 }
Example #13
0
    // 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);
    }
        //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
            };
        }
Example #15
-1
        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);
        }
        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.OpenWrite(TargetPath))
                    {
                        sftp.DownloadFile(SourcePath, file);
                    }

                    return DTSExecResult.Success;
                }   
            } catch (Exception ex) {
                log.Write(string.Format("{0}.Execute", GetType().FullName), ex.ToString());
                return DTSExecResult.Failure;
            }
        }