当前位置: 首页>>代码示例>>C#>>正文


C# SftpClient.DownloadFile方法代码示例

本文整理汇总了C#中Renci.SshNet.SftpClient.DownloadFile方法的典型用法代码示例。如果您正苦于以下问题:C# SftpClient.DownloadFile方法的具体用法?C# SftpClient.DownloadFile怎么用?C# SftpClient.DownloadFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Renci.SshNet.SftpClient的用法示例。


在下文中一共展示了SftpClient.DownloadFile方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CopyFileFromRemoteToLocal

        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();
            }
        }
开发者ID:wangn6,项目名称:rep2,代码行数:17,代码来源:SSHWrapper.cs

示例2: PollHandler

        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);
        }
开发者ID:ojoadeolagabriel,项目名称:TqWorkflow-beta,代码行数:48,代码来源:FtpConsumer.cs

示例3: beginCracking

        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);
                }
            }
        }
开发者ID:koufengwei,项目名称:Brake,代码行数:54,代码来源:CrackProcess.cs

示例4: TryGetFileFromFtp

		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;
		}
开发者ID:csulham,项目名称:Sitecore.SharedSource.UserCsvImport,代码行数:51,代码来源:SshFileDownloader.cs

示例5: DownloadFile

        /// <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();
            }
        }
开发者ID:jimpelton,项目名称:envws,代码行数:24,代码来源:SSHAsyncTransfer.cs

示例6: Main


//.........这里部分代码省略.........
                    /*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 ();
                    }
                }
            }
        }
开发者ID:koufengwei,项目名称:Brake,代码行数:101,代码来源:Program.cs

示例7: SSHTest

        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();
//.........这里部分代码省略.........
开发者ID:shovelheadfxe,项目名称:DevLab,代码行数:101,代码来源:Code.cs

示例8: DownloadFiles

        /// <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);
            }
        }
开发者ID:ElanHasson,项目名称:SSIS-Extensions,代码行数:55,代码来源:SFTPConnection.cs

示例9: DownloadFile

 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);
     }
 }
开发者ID:dragon753,项目名称:Deployer,代码行数:8,代码来源:DeployOperation.cs

示例10: Send

    // Use this for initialization
    public void Send()
    {
        string address = "10.211.55.4";
        string user = "parallels";
        string pass = "Austinv0me6fp8";
        //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);
    }
开发者ID:dannisliang,项目名称:malwarevis,代码行数:90,代码来源:Send_Command.cs

示例11: Execute

        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");
//.........这里部分代码省略.........
开发者ID:splitice,项目名称:SSHKeyTransfer,代码行数:101,代码来源:Form1.cs

示例12: DownloadQtyFiles

        //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
            };
        }
开发者ID:InfiniteComputingSystems,项目名称:Test,代码行数:30,代码来源:MagGatherHandler.cs

示例13: Execute

        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;
            }
        }
开发者ID:rhythmagency,项目名称:rhythm.ssis,代码行数:19,代码来源:SftpDownloadTask.cs

示例14: Main

        static void Main(string[] args)
        {
            string address = "192.168.17.129";
            string user = "swastik";
            string pass = "singh";
            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);
        }
开发者ID:dannisliang,项目名称:malwarevis,代码行数:77,代码来源:Program.cs


注:本文中的Renci.SshNet.SftpClient.DownloadFile方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。