示例#1
0
        private bool UploadStream(Stream stream, string remotePath)
        {
            if (Connect())
            {
                try
                {
                    using (SftpFileStream sftpStream = client.Create(remotePath))
                    {
                        return(TransferData(stream, sftpStream));
                    }
                }
                catch (SftpPathNotFoundException)
                {
                    // Happens when directory not exist, create directory and retry uploading

                    CreateDirectory(URLHelpers.GetDirectoryPath(remotePath));

                    using (SftpFileStream sftpStream = client.Create(remotePath))
                    {
                        return(TransferData(stream, sftpStream));
                    }
                }
                catch (NullReferenceException)
                {
                    // Happens when disconnected while uploading
                }
            }

            return(false);
        }
示例#2
0
 public Task CreateFile(string filePath, byte[] bytes)
 {
     return(HandleCommonExceptions(() => {
         _logger?.LogDebug($"CreateFile('{filePath}')");
         using (var stream = _client.Create(filePath)) {
             stream.Write(bytes);
         }
         _logger?.LogDebug($"CreateFile('{filePath}'): done");
     }));
 }
示例#3
0
        public IFile CreateFile(IFile file)
        {
            var filePath = _path + '/' + file.Name;
            var stream   = _client.Create(_path);

            byte[] fileBytes = file.GetBytes();
            stream.Write(fileBytes, 0, fileBytes.Length);

            return(new File(filePath, _client, file.Name));
        }
 static void Main(string[] args)
 {
     using (SftpClient sftpClient = new SftpClient(host, username, password))
     {
         try
         {
             sftpClient.Connect();
             sftpClient.DeleteFile("./variables.txt");
             sftpClient.Create("./variables.txt");
             sftpClient.WriteAllText("./variables.txt", "testwrite");
             sftpClient.ReadAllText("./variables.txt");
             sftpClient.Disconnect();
         }
         catch (Exception e)
         {
             Console.WriteLine("An exception has been caught " + e.ToString());
         }
     }
 }
        private void ButtonSaveFile_Click(object sender, EventArgs e)                     // сохранение файла на сервер
        {
            using (var sftp = new SftpClient(ServerIP, ServerPort, "root", PasswordRoot)) //переменная для подключения
            {
                try
                {
                    sftp.Connect();                                          // попытка подключения
                    if (sftp.IsConnected)                                    // если подключились
                    {
                        if (comboBoxPath.SelectedItem == null)               // проверяем поле ввода на нулевое значение
                        {
                            MessageBox.Show("Выберите существующий объект"); // если поле нулевое, то вывод сообщения
                        }
                        else
                        {
                            string FilePath = comboBoxPath.SelectedItem.ToString(); // преобразуем выбранный пункт в стринг

                            if (sftp.Exists(FilePath + ".old"))                     // если файл old существует
                            {
                                sftp.Delete(FilePath + ".old");                     //то удаляем его
                            }
                            if (!sftp.Exists(FilePath))                             // если файл на пути не существует,
                            {
                                sftp.Create(FilePath);                              //то создаем его
                            }
                            else                                                    // если файл существует
                            {
                                sftp.RenameFile(FilePath, FilePath + ".old");       // то переименовываем  файл в .old
                            }
                            sftp.WriteAllText(FilePath, TextBoxEditor.Text);        // запись нового файла
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);    // вывод описания ошибки подключения
                }
                finally
                {
                    sftp.Disconnect();              // отключаемся от сервера
                }
            }
        }
示例#6
0
        public SFTPStream(Uri uri, ConnectionInfo connectionInfo, StreamMode streamMode)
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            if (connectionInfo == null)
            {
                throw new ArgumentNullException(nameof(connectionInfo));
            }

            _uri    = uri;
            _client = new SftpClient(connectionInfo);

            _client.Connect();

            String adjustedLocalPath = uri.LocalPath.Substring(1);

            _stream = streamMode == StreamMode.Read ? _client.OpenRead(adjustedLocalPath) : _client.Create(adjustedLocalPath);
        }
        public void Upload(string source, string target, Func <string, string> renameCallback, bool deleteSourceFile = false)
        {
            if (string.IsNullOrWhiteSpace(source))
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (string.IsNullOrWhiteSpace(target))
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (!File.Exists(source))
            {
                throw new SftpProviderException($"{source} does not exist.");
            }

            if (!IsConnected)
            {
                throw new SftpProviderException("Connect to server before upload.");
            }

            var targetPath = target;

            try
            {
                CreateDirectory(targetPath);

                var completed = new ManualResetEvent(false);

                using (var fileStream = File.Open(source, FileMode.Open))
                {
                    _log.Debug(m => m("Uploading {0} to {1}", source, _host));

                    var totalBytes = (ulong)fileStream.Length;

                    if (totalBytes == 0)
                    {
                        if (!_client.Exists(target))
                        {
                            _client.Create(target).Close();
                        }
                        Uploading?.Invoke(target, 0, 0);

                        _log.Info(m => m("Upload {0} to {1} completed.", source, _host));
                    }
                    else
                    {
                        _client.UploadFile(fileStream, target, bytes =>
                        {
                            Uploading?.Invoke(target, bytes, totalBytes);

                            if (bytes == totalBytes)
                            {
                                _log.Info(m => m("Upload {0} to {1} completed.", source, _host));
                                completed.Set();
                            }
                            else
                            {
                                _log.Debug(m => m("Uploading {0} to {1} {2}/{3}", source, _host, bytes, totalBytes));
                            }
                        });

                        completed.WaitOne();
                    }

                    fileStream.Close();

                    if (renameCallback != null)
                    {
                        var renamedFile = renameCallback(targetPath);
                        if (string.CompareOrdinal(targetPath, renamedFile) != 0)
                        {
                            _client.RenameFile(targetPath, renamedFile);
                        }
                    }

                    if (!deleteSourceFile)
                    {
                        return;
                    }

                    File.Delete(source);
                    _log.Debug($"{source} deleted.");
                }
            }
            catch (Exception e)
            {
                throw new SftpProviderException(e.Message, e);
            }
        }
        private void ShellBuilder()
        {
            bool          isExist  = false;
            string        userPath = (m_Username == "root") ? "/root" : $"/home/{m_Username}";
            List <string> path     = new List <string>();
            List <string> file     = new List <string>();

            foreach (var item in m_SftpClient.ListDirectory(userPath))
            {
                if (item.IsDirectory)
                {
                    path.Add(item.Name);
                }
            }
            if (!path.Contains("steamcmd"))
            {
                m_SftpClient.CreateDirectory(userPath + "/steamcmd");
            }

            foreach (var item in m_SftpClient.ListDirectory(userPath + "/steamcmd"))
            {
                if (!item.IsDirectory)
                {
                    file.Add(item.Name);
                }
            }
            if (file.Contains("steamcmd_linux.tar.gz"))
            {
                isExist = true;
            }

            m_SftpClient.Create(userPath + "/steamcmd" + "/getsteamcmd.sh");

            StringBuilder command = new StringBuilder(512);

            command.Append($" +force_install_dir {textBox_Path.Text.Replace(@"\", @"\\")}");
            command.Append($" +login anonymous");
            command.Append($" +app_update 343050");
            if ((bool)radioButton_Alpha.IsChecked)
            {
                command.Append($" -beta {textBox_Name.Text}");
            }
            command.Append($" validate");
            command.Append($" +quit");

            MemoryStream commandStream = new MemoryStream();
            StreamWriter commandWriter = new StreamWriter(commandStream, Encoding.UTF8);

            commandWriter.Write($"#!/bin/bash\n\n");
            commandWriter.Write($"cd steamcmd\n");
            if (!isExist)
            {
                commandWriter.Write($"wget https://steamcdn-a.akamaihd.net/client/installer/steamcmd_linux.tar.gz\n");
            }
            if (!isExist)
            {
                commandWriter.Write($"tar -xvzf steamcmd_linux.tar.gz\n");
            }
            //commandWriter.Write($"rm -f steamcmd_linux.tar.gz\n");
            commandWriter.Write($"chmod 777 ./steamcmd.sh\n");
            commandWriter.Write($"./steamcmd.sh {command.ToString()}\n");

            commandWriter.Flush();

            m_SftpClient.WriteAllBytes(userPath + "/steamcmd" + "/getsteamcmd.sh", commandStream.ToArray());
            commandStream.Close();

            SendCommand($"chmod 777 {userPath}/steamcmd/getsteamcmd.sh");
            SendCommand($"dos2unix {userPath}/steamcmd/getsteamcmd.sh");

            m_SftpClient.Dispose();
        }
示例#9
0
 public void CreateTest1()
 {
     ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
     SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
     string path = string.Empty; // TODO: Initialize to an appropriate value
     SftpFileStream expected = null; // TODO: Initialize to an appropriate value
     SftpFileStream actual;
     actual = target.Create(path);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
示例#10
0
        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();
        }