Esempio n. 1
0
        private void GetSubDirectories(DirectoryInfo info, SftpClient client)
        {
            foreach (var subInfo in Directory.GetDirectories(info.FullName)
                     .Where(x => x != Directory.GetCurrentDirectory() && !x.EndsWith(".vs") && !x.EndsWith(".git"))
                     .Select(x => new DirectoryInfo(x)))
            {
                if (!client.Exists(subInfo.Name))
                {
                    client.CreateDirectory(subInfo.Name);
                }
                var prevDirectory = client.WorkingDirectory;
                client.ChangeDirectory(subInfo.Name);

                GetSubDirectories(subInfo, client);
                foreach (var file in subInfo.GetFiles())
                {
                    try
                    {
                        using (var fileStream = File.OpenRead(file.FullName))
                        {
                            client.UploadFile(fileStream, file.Name, true);
                        }
                    }
                    catch (IOException e)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(e.Message);
                        Console.ResetColor();
                    }
                }
                client.ChangeDirectory(prevDirectory);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Create a test folder on a server
        /// </summary>
        /// <param name="serverName">The server to connect to</param>
        /// <param name="userName">The user to log into</param>
        /// <param name="password">The password of the user</param>
        public static string CreateFiles(string serverName, string userName, string password)
        {
            using (SftpClient client = new SftpClient(serverName, userName, password))
            {
                client.Connect();

                // cd TestDir
                if (!client.Exists("TestDir"))
                {
                    client.CreateDirectory("TestDir");
                }
                client.ChangeDirectory("TestDir");

                // Make new dir based on timestamp + random guid and cd to it
                string dirName = $"{DateTime.Now.ToString("ddMMyyyy-HHmmss")}_{Guid.NewGuid()}";
                client.CreateDirectory(dirName);
                client.ChangeDirectory(dirName);

                // xfer files from SampleData
                Parallel.ForEach(Directory.GetFiles(@"SampleData"), k =>
                {
                    client.UploadFile(File.OpenRead(k), k);
                });

                client.Disconnect();

                return(dirName);
            }
        }
Esempio n. 3
0
 public void UploadDirectory()
 {
     using (var client = new SftpClient(host, username, password))
     {
         client.Connect();
         client.ChangeDirectory(".local");
         if (!client.WorkingDirectory.EndsWith("root"))
         {
             client.ChangeDirectory("/root");
         }
         DirectoryInfo info = new DirectoryInfo(Directory.GetCurrentDirectory()).Parent;
         if (!client.Exists(info.Name))
         {
             client.CreateDirectory(info.Name);
         }
         client.ChangeDirectory(info.Name);
         foreach (var file in info.GetFiles())
         {
             using (var fileStream = File.OpenRead(file.FullName))
             {
                 client.UploadFile(fileStream, file.Name, true);
             }
         }
         GetSubDirectories(info, client);
     }
 }
Esempio n. 4
0
        /// <summary>
        /// 取得文件列表
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public List <string> ListFiles(string path)
        {
            if (!Connect())
            {
                return(null);
            }

            List <string> files = new List <string>();

            try
            {
                sftp.ChangeDirectory("/");
                sftp.ListDirectory(path).ToList().ForEach(f =>
                {
                    files.Add(f.FullName);
                });

                return(files);
            }
            catch (Exception ex)
            {
                // logger.Error("[{0}] 取得文件列表发生错误。", Path, ex);
                return(null);
            }
        }
Esempio n. 5
0
        public bool InitializeSFTP()
        {
            try
            {
                if (!client.IsConnected)
                {
                    client.Connect();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            if (client.IsConnected)
            {
                client.ChangeDirectory(workingdirectory);
                var listDirectory = client.ListDirectory(workingdirectory);
                foreach (var file in listDirectory)
                {
                    if (file.Name == uploadfile)
                    {
                        return(true);
                    }
                }
            }
            else
            {
                return(false);
            }

            return(false);
        }
        private void TransferPrereqs(SshClient sshClient, ServerDistro distro)
        {
            string prereqsPath = (distro == ServerDistro.RPM) ? rpmPackages : debianPackages;

            using (var sftpClient = new SftpClient(sshClient.ConnectionInfo))
            {
                sftpClient.Connect();

                List <string> files = ListPrereqsFiles(prereqsPath);
                foreach (string file in files)
                {
                    using (var fileStream = new FileStream(file, FileMode.Open))
                    {
                        Console.WriteLine("Uploading {0} ({1:N0} bytes)", file, fileStream.Length);
                        sftpClient.BufferSize = 4 * 1024; // bypass Payload error large files
                        string   path     = file.Remove(file.IndexOf(Path.GetFileName(file))).Replace(@"\", "/");
                        string   filename = Path.GetFileName(file);
                        string[] dirs     = path.TrimEnd('/').Split('/');
                        foreach (var dir in dirs)
                        {
                            try
                            {
                                if (!sftpClient.Exists(dir))
                                {
                                    sftpClient.CreateDirectory(dir);
                                }
                                sftpClient.ChangeDirectory(dir);
                            }
                            catch
                            {
                                //Log: Directory already exists
                            }
                        }
                        if (sftpClient.Exists(filename))
                        {
                            sftpClient.UploadFile(fileStream, filename);
                        }
                        sftpClient.ChangePermissions(filename, 755);
                        sftpClient.ChangeDirectory("/home/" + sshClient.ConnectionInfo.Username);
                    }
                }
            }

            ////chmod +x for the file to be executable
            //var cmd = sshClient.CreateCommand("chmod +x ./" + Path.GetFileName(agentPath));
            //var result = cmd.BeginExecute();
            //using (var reader = new StreamReader(cmd.OutputStream, Encoding.UTF8, true, 1024, true))
            //{
            //    while (!result.IsCompleted || !reader.EndOfStream)
            //    {
            //        string line = reader.ReadLine();
            //        if (line != null)
            //        {
            //            //Log: result
            //        }
            //    }
            //}
            //cmd.EndExecute(result);
        }
        void UploadData(PatientEntity model, ObservableCollection <PatientReport> reports)
        {
            //try
            //{
            APIResult result = new APIResult();

            if (model.PatientId == 0)
            {
                result = SyncPatientDetails(model, reports, false);
            }
            else
            {
                result = SyncPatientDetails(model, reports, true);
            }

            if (result.status == "ok")
            {
                foreach (var item in reports)
                {
                    item.Sync = true;
                    new Patient().UpdateSyncStatus(item.Id);
                }
            }

            string localPath   = Path.Combine(Program.BaseDir(), "Uploads", model.UniqueID.ToString());
            string ftpHost     = ConfigurationManager.AppSettings["ftpHost"].ToString();
            string ftpUserName = ConfigurationManager.AppSettings["ftpUserName"].ToString();
            string ftpPassword = ConfigurationManager.AppSettings["ftpPassword"].ToString();

            using (var client = new SftpClient(ftpHost, ftpUserName, ftpPassword))
            {
                client.Connect();
                client.ChangeDirectory("/home/ftpuser11/ftp/files");
                string rootDir = client.WorkingDirectory + "/" + model.UniqueID.ToString();

                if (!client.Exists(rootDir))
                {
                    client.CreateDirectory(rootDir);
                }
                foreach (var item in PatientReports)
                {
                    string rootDataDir = rootDir + "/" + item.UniqueID.ToString();
                    if (!client.Exists(rootDataDir))
                    {
                        client.CreateDirectory(rootDataDir);
                        client.ChangeDirectory(rootDataDir);
                        UploadDirectory(client, localPath, rootDir);
                    }
                }
                client.Disconnect();
            }
            //}
            //catch (Exception ex)
            //{
            //    ModernDialog.ShowMessage("An error has occurred on the server", "Alert", MessageBoxButton.OK);
            //    throw ex;
            //}
        }
Esempio n. 8
0
 public void ChangeToFolder(string changeTo)
 {
     if (changeTo.StartsWith("/"))
     {
         changeTo = changeTo.Substring(1);
     }
     _sftpClient.ChangeDirectory(changeTo);
     _logger($"Changed directory to {changeTo}", NLog.LogLevel.Info);
 }
Esempio n. 9
0
    public string GetDirectoryContent()
    {
        if (password == null || password.Length < 1)
        {
            if (debug)
            {
                Debug.LogError("sftpaccess >> No Password specified!");
            }
            return(null);
        }
        using (var client = new SftpClient(host, username, password))
        {
            client.Connect();
            if (debug)
            {
                Debug.Log("Is connected? " + client.IsConnected);
            }

            string baseReadWriteDir = "/surveylog/";
            string playerName       = PlayerPrefs.GetString("name");

            //check if /$name exists, if not create it, then switch the workdir
            client.ChangeDirectory(baseReadWriteDir);
            if (!client.Exists(playerName))
            {
                client.CreateDirectory(playerName);
            }
            client.ChangeDirectory(playerName);
            //check if /$name/$type exists, if not create it, then switch the workdir
            if (!client.Exists(gameTypeString))
            {
                client.CreateDirectory(gameTypeString);
            }
            client.ChangeDirectory(gameTypeString);

            Console.WriteLine("Changed directory to {0}", baseReadWriteDir);
            // no. of files currently
            List <SftpFile> files = client.ListDirectory(client.WorkingDirectory).ToList();
            client.Disconnect();
            String ret = "";
            foreach (var item in files)
            {
                if (debug)
                {
                    Debug.Log(">>" + item);
                }
                if (!item.Name.StartsWith("."))
                {
                    ret += "> " + item.Name + "\r\n";
                }
            }
            return(ret);
        }
    }
Esempio n. 10
0
 public void ChangeDirectory(string Path)
 {
     try
     {
         client.ChangeDirectory(Path);
     }
     catch (SftpPathNotFoundException)
     {
         CreateDirectory(Path);
         ChangeDirectory(Path);
     }
 }
        /// <summary>
        /// Upload array of files to SFTP server.
        /// specifiying sftp folder location to upload too
        /// </summary>
        /// <param name="sftpFolderLocatn"></param>
        /// <param name="filesToUpload"></param>
        /// <returns></returns>
        public bool UploadFilesToSftpSrver(string sftpFolderLocatn, string[] filesToUpload)
        {
            try
            {
                if (objSftpClient == null)
                {
                    return(false);
                }
                objSftpClient.Connect();
                if (objSftpClient.IsConnected)
                {
                    objSftpClient.ChangeDirectory(sftpFolderLocatn);
                    if (filesToUpload == null)
                    {
                        return(false);
                    }

                    foreach (var file in filesToUpload)
                    {
                        using (var fileStream = File.OpenRead(file))
                        {
                            // Upload files to SFTP server
                            objSftpClient.BufferSize = 4 * 1024;
                            objSftpClient.UploadFile(fileStream, Path.GetFileName(file));
                        }
                    }
                }
                else
                {
                    throw new Exception("Error: UploadFilesToSftpSrver() - Could not connect to sftp server");
                }
            }
            catch (Exception ex)
            {
                Log.Error(String.Format("Exception - {0} Ex: {1}", MethodBase.GetCurrentMethod().Name, ex.Message));
                throw new Exception(String.Format("Error uploading files to sftp server. Ex: {0}", ex.Message));
            }
            finally
            {
                if (objSftpClient != null)
                {
                    if (objSftpClient.IsConnected)
                    {
                        objSftpClient.Disconnect();
                    }
                }
            }

            return(true);
        }
Esempio n. 12
0
 public void ChangeDirectory(string path)
 {
     if (Connect())
     {
         try
         {
             client.ChangeDirectory(path);
         }
         catch (SftpPathNotFoundException)
         {
             CreateDirectory(path);
             ChangeDirectory(path);
         }
     }
 }
Esempio n. 13
0
        public static async void UploadFiles(StringCollection collection)
        {
            int longRunningTask = await LongRunningOperationAsync();

            using (SftpClient client = new SftpClient(host, port, username, password)) {
                UploadUtils.UploadType type = UploadUtils.UploadType.FILE;
                client.Connect();
                client.ChangeDirectory(type.getDestination());
                client.BufferSize = 2 * 1024;

                string name = NameUtils.RandomString(8) + ".zip";
                while (UploadUtils.Instance.checkFileExists(client, name, type))
                {
                    name = NameUtils.RandomString(8) + ".zip";
                }

                using (var tempPath = new TempFile(@System.IO.Path.GetTempPath() + name)) {
                    using (var ms = new MemoryStream()) {
                        using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true)) {
                            for (int i = 0; i < collection.Count; i++)
                            {
                                archive.CreateEntryFromFile(collection[i], Path.GetFileName(collection[i]));
                            }
                        }

                        using (var fileStream = new FileStream(tempPath.Path, FileMode.Create)) {
                            ms.Seek(0, SeekOrigin.Begin);
                            ms.CopyTo(fileStream);
                        }

                        UploadUtils.Instance.UploadFile(client, tempPath.Path, name, type);
                    }
                }
            }
        }
Esempio n. 14
0
 //https://sshnet.codeplex.com/discussions/403235
 public void DownloadFile(string sftpWorkingDirectory, string sftpFileName, string localDestinationFilePath)
 {
     if (File.Exists(localDestinationFilePath))
     {
         File.Delete(localDestinationFilePath);
     }
     using (SftpClient client = new SftpClient(_host, _port, _userName, _password))
     {
         Console.WriteLine("Connecting to {0}:{1}", _host, _port);
         client.Connect();
         Console.WriteLine("Changing directory to {0} ...", sftpWorkingDirectory);
         client.ChangeDirectory(sftpWorkingDirectory);
         if (client.Exists(sftpFileName))
         {
             using (FileStream fileStream = File.OpenWrite(localDestinationFilePath))
             {
                 Console.WriteLine("Downloading {0} ...", sftpFileName);
                 client.DownloadFile(sftpFileName, fileStream);
                 fileStream.Close();
             }
         }
         else
         {
             throw new FileNotFoundException(string.Format("Could not find SFTP file {0}{1} on host {2}:{3}.", sftpWorkingDirectory, sftpFileName, _host, _port));
         }
         Console.WriteLine("Disconnecting from {0} ...", _host, _port);
         client.Disconnect();
     }
 }
Esempio n. 15
0
        public void RunFTPSync()
        {
            var now     = DateTime.UtcNow.ToLocalTime();
            var lastRun = ReadLastRun();

            using (SftpClient ftp = new SftpClient(ConfigurationManager.AppSettings["FTP_URL"],
                                                   ConfigurationManager.AppSettings["FTP_Username"],
                                                   ConfigurationManager.AppSettings["FTP_Password"]))
            {
                var ftp_directory = ConfigurationManager.AppSettings["FTP_Directory"];
                ftp.Connect();
                ftp_directory.Split('/').ToList().ForEach(f => ftp.ChangeDirectory(f));
                var files = ftp.ListDirectory(".");

                files = files.Where(f => !f.Name.Equals(".") && !f.Name.Equals("..")).Where(f => f.LastWriteTime > lastRun && f.LastWriteTime < now).Where(f =>
                {
                    var actualTime = f.ActualLastWriteTime(ftp, ftp_directory);
                    return
                    (actualTime > lastRun &&
                     actualTime < now);
                }).ToList();
                DownloadFiles(files, ftp, ftp_directory);
                WriteLastRan(now.ToString()); //uncommentn after done testing
                //Run shell script to update theia library
            }
        }
Esempio n. 16
0
        internal bool UploadFile(string remoteDir, string remoteFileName, string localFile)
        {
            try
            {
                using (var client = new SftpClient(Host, 22, User, Pass))
                {
                    client.Connect();
                    client.ChangeDirectory(remoteDir);

                    using (var fileStream = new FileStream(localFile, FileMode.Open))
                    {
                        Console.WriteLine("Uploading {0} ({1:N0} bytes)", localFile, fileStream.Length);
                        client.BufferSize = 4 * 1024; // bypass Payload error large files
                        client.UploadFile(fileStream, remoteFileName);
                    }

                    client.Disconnect();
                }
                MiniLogger.LogQueue.Enqueue("File successfully uploaded: " + Path.GetFileName(localFile));
                return(true);
            }
            catch (Exception ex)
            {
                MiniLogger.LogQueue.Enqueue("Failed to upload file. " + ex.Message);
                return(false);
            }
        }
 public static int Send(string fileName)
 {
     try
     {
         //var connectionInfo = new ConnectionInfo(host, "erjan", new PasswordAuthenticationMethod(username, password));
         // Upload File
         using (var sftp = new SftpClient(host, port, username, password))
         {
             sftp.Connect();
             sftp.ChangeDirectory(Config.directoryToSave);
             using (var uplfileStream = System.IO.File.OpenRead(fileName))
             {
                 sftp.UploadFile(uplfileStream, fileName, true);
             }
             sftp.Disconnect();
             Console.WriteLine("\n\n" + fileName + " uploaded successfully.\n");
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
         Console.WriteLine("\n\n" + fileName + " was not uploaded.\n\n");
     }
     return(0);
 }
Esempio n. 18
0
        //Функция отправляет файл с путем tmp_filePath на сервер

        public void SendFileSFTP(string tmp_filePath)
        {
            this.filePath = tmp_filePath;
            if (!CheckData())
            {
                throw new Exception("Введены некорректные данные.");
            }
            FileInfo fileInfo = new FileInfo(filePath);
            string   fileName = fileInfo.Name;

            using (SftpClient sftpClient = new SftpClient(host, port, login, password))
            {
                sftpClient.Connect();
                if (sftpClient.IsConnected)
                {
                    if (File.Exists(filePath))
                    {
                        sftpClient.ChangeDirectory(directory);
                        using (var fileStream = System.IO.File.OpenRead(filePath))
                            sftpClient.UploadFile(fileStream, fileName, true);
                    }
                    else
                    {
                        throw new Exception("Файла не существует.");
                    }
                }
                else
                {
                    throw new Exception("Нет подключения к серверу.");
                }
            }
            MessageBox.Show("Файл успешно отправлен на сервер.", "Успех!", MessageBoxButtons.OK);
        }
Esempio n. 19
0
        public static void SftpFileUpload(FTPConfig config)
        {
            ConnectionInfo connectionInfo = new ConnectionInfo(config.IP, config.Port, config.User, new PasswordAuthenticationMethod(config.User, config.Password));

            using (SftpClient sftp = new SftpClient(connectionInfo))
            {
                sftp.Connect();
                sftp.ChangeDirectory(config.Directory);
                FileInfo fi = new FileInfo(config.FilePath);

                using (var uplfileStream = File.OpenRead(config.FilePath))
                {
                    if (config.DeleteIfExists)
                    {
                        try
                        {
                            Renci.SshNet.Sftp.SftpFile file = sftp.Get(fi.Name);

                            if (file.HasValue())
                            {
                                sftp.DeleteFile(file.FullName);
                            }
                        }
                        catch
                        {
                        }
                    }

                    sftp.UploadFile(uplfileStream, fi.Name, true);
                }

                sftp.Disconnect();
            }
        }
        public string List_File(string dir)
        {
            string[] strSplit = dir.Split('/');
            string   path     = "";

            for (var i = 0; i < strSplit.Length - 1; i++)
            {
                path += strSplit[i] + "/";
            }
            dir = strSplit[strSplit.Length - 1];

            ArrayList pList = new ArrayList();

            SftpClt.ChangeDirectory(path);// "/");

            string strReturn = "";

            foreach (var entry in SftpClt.ListDirectory(dir))
            {
                if (entry.IsDirectory)
                {
                    //ListDirectory(client, entry.FullName, ref files);
                }
                else
                {
                    strReturn += entry.FullName + "|";
                    //pList.Add(entry.FullName);
                }
            }
            if (strReturn.EndsWith("|"))
            {
                strReturn = strReturn.Substring(0, strReturn.Length - 1);
            }
            return(strReturn);
        }
Esempio n. 21
0
 public string UploadFile(string file_local)
 {
     try
     {
         System.IO.FileInfo file = new System.IO.FileInfo(file_local);
         if (file.Exists)
         {
             string remote_path    = path_root + file.Name;
             var    connectionInfo = new ConnectionInfo(adresse, Convert.ToInt16(port), users, new PasswordAuthenticationMethod(users, password));
             using (var sftp = new SftpClient(connectionInfo))
             {
                 sftp.Connect();
                 sftp.ChangeDirectory("files");
                 using (var uplfileStream = System.IO.File.OpenRead(file.FullName))
                 {
                     sftp.UploadFile(uplfileStream, file.Name, true);
                 }
                 sftp.Disconnect();
             }
             return(remote_path);
         }
     }
     catch (Exception ex)
     {
         var _ex_ = ex;
         Messages.Exception(ex);
     }
     return(null);
 }
Esempio n. 22
0
        /// <summary>
        /// Delete a test folder on a server
        /// </summary>
        /// <param name="serverName">The server to connect to</param>
        /// <param name="userName">The user to log into</param>
        /// <param name="password">The password of the user</param>
        /// <param name="folderName">The name of the test folder to delete</param>
        public static void DeleteFiles(string serverName, string userName, string password, string folderName)
        {
            using (SftpClient client = new SftpClient("serverName", userName, password))
            {
                client.Connect();

                // cd TestDir
                if (!client.Exists("TestDir"))
                {
                    return;
                }
                client.ChangeDirectory("TestDir");

                // Delete folder
                if (!string.IsNullOrWhiteSpace(folderName) && client.Exists(folderName))
                {
                    // client.DeleteDirectory is not recursive, so have to go in and delete every file first
                    Parallel.ForEach(client.ListDirectory(folderName), k =>
                    {
                        try
                        {
                            client.DeleteFile(k.FullName);
                        }
                        // Catch delete failures coming from trying to delete './' or '../'
                        catch (SshException) { }
                    });

                    client.DeleteDirectory(folderName);
                }

                client.Disconnect();
            }
        }
Esempio n. 23
0
 public void CreateChallengeFile(string filename, string contents)
 {
     if (string.IsNullOrEmpty(filename))
     {
         throw new ArgumentException("Must not be null or empty!", nameof(filename));
     }
     if (string.IsNullOrEmpty(contents))
     {
         throw new ArgumentException("Must not be null or empty!", nameof(contents));
     }
     using (SftpClient client = _sftpClientFactory.CreateClient())
     {
         if (!client.Exists(".well-known/acme-challenge"))
         {
             if (!client.Exists(".well-known"))
             {
                 client.CreateDirectory(".well-known");
             }
             client.CreateDirectory(".well-known/acme-challenge");
         }
         client.ChangeDirectory(".well-known/acme-challenge");
         client.WriteAllText(string.Concat(client.WorkingDirectory, "/", filename), contents);
     }
     _logger.LogInformation("Challenge presented.");
 }
        public override bool Receive(string workingPath, SshClient sshClient, SftpClient sftpClient)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                try
                {
                    try
                    {
                        //HACK
                        sftpClient.ChangeDirectory(workingPath);
                    }
                    catch (Exception)
                    {
                    }

                    sftpClient.DownloadFile(this._path, stream);

                    if (this._callback != null)
                    {
                        this._callback.Invoke(stream.ToArray());
                    }

                    return(true);
                }
                finally
                {
                    stream.Close();
                }
            }
        }
Esempio n. 25
0
        public List <string> GetDirectoryListing(string sftpWorkingDirectory, string fileExtension)
        {
            List <string> result             = new List <string>();
            string        fileExtensionLower = fileExtension.ToLower();

            using (SftpClient client = new SftpClient(_host, _port, _userName, _password))
            {
                Console.WriteLine("Connecting to {0}:{1}", _host, _port);
                client.Connect();
                Console.WriteLine("Changing directory to {0} ...", sftpWorkingDirectory);
                client.ChangeDirectory(sftpWorkingDirectory);
                IEnumerable <SftpFile> files = client.ListDirectory(".");
                foreach (SftpFile f in files)
                {
                    string currentFileExtension = Path.GetExtension(f.Name).ToLower();
                    if (string.IsNullOrEmpty(fileExtension) || currentFileExtension == fileExtensionLower)
                    {
                        result.Add(f.Name);
                    }
                }
                Console.WriteLine("Disconnecting from {0} ...", _host, _port);
                client.Disconnect();
            }
            return(result);
        }
        public async Task <int> UploadVmTemplate(
            string name,
            Stream fileStream,
            long length,
            Hypervisor hypervisor,
            VmTemplate vmTemplate,
            Action <double> callback = null)
        {
            var          safeFileName = vmTemplate.Id + ".ova";
            const string baseDir      = "/root/uploads";
            var          dirName      = "VmTemplate_" + vmTemplate.Id;
            var          dirPath      = string.Join("/", baseDir, dirName);
            var          filePath     = string.Join("/", dirPath, safeFileName);
            var          node         = await ProxmoxManager.GetPrimaryHypervisorNode(hypervisor);

            var api = ProxmoxManager.GetProxmoxApi(node);
            int vmId;

            // Upload File
            using (var sftp = new SftpClient(GetConnectionInfoFromHypervisor(hypervisor)))
            {
                sftp.Connect();
                try
                {
                    sftp.CreateDirectory(dirPath);
                    sftp.ChangeDirectory(dirPath);
                    sftp.UploadFile(fileStream, filePath, true, progress =>
                    {
                        if (callback != null)
                        {
                            callback((double)progress / length * 100);
                        }
                    });
                    using (var ssh = new SshClient(GetConnectionInfoFromHypervisor(hypervisor)))
                    {
                        ssh.Connect();
                        await ExtractOva(ssh, filePath, dirPath);

                        vmId = await CreateVmAndImportDisk(name, ssh, sftp, api, dirPath);

                        var unusedDisk = await api.GetVmUnusedDisk(vmId);

                        await api.SetVmScsi0(vmId, unusedDisk);

                        await api.ConvertVmToTemplate(vmId);

                        ssh.Disconnect();
                    }
                    Cleanup(sftp, dirPath);
                }
                catch (Exception)
                {
                    Cleanup(sftp, dirPath);
                    throw;
                }
                sftp.Disconnect();
            }

            return(vmId);
        }
Esempio n. 27
0
        //Uploades a hex file to the Pi and programs it to the Teensy
        //Would be good to parse feedback from the Teensy cli loader
        //Validating the file would good too.
        //The ssh upload library is pretty unforgiving, need to parse and handle errors from it
        public static bool uploadFile(string host_ip, string username, string password, string localFile, string remoteFile)
        {
            try
            {
                using (SftpClient ssh = new SftpClient(host_ip, username, password))
                {
                    ssh.ConnectionInfo.Timeout = new TimeSpan(0, 0, 3);
                    ssh.Connect();
                    FileStream stream = new FileStream(localFile, FileMode.Open);
                    if (ssh.ListDirectory("/").FirstOrDefault(x => x.Name == "teensyTemp") == null)
                    {
                        ssh.CreateDirectory("/teensyTemp");
                    }
                    ssh.ChangeDirectory("/teensyTemp");
                    ssh.UploadFile(stream, remoteFile);
                    ssh.Disconnect();
                    stream.Close();
                }

                using (SshClient ssh = new SshClient(host_ip, username, password))
                {
                    ssh.ConnectionInfo.Timeout = new TimeSpan(0, 0, 3);
                    ssh.Connect();
                    ssh.RunCommand("prog_teensy " + "\"/teensyTemp/" + remoteFile + "\"");
                    ssh.RunCommand("rm " + "\"/teensyTemp/" + remoteFile + "\"");
                    ssh.Disconnect();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("SSH Failed: " + e.ToString());
                return(false);
            }
            return(true);
        }
Esempio n. 28
0
        /// <summary>
        /// >>>NOT USED>>>
        /// </summary>
        /// <param name="file"></param>
        /// <param name="workingdirectory"></param>

        public void FileUploadSFTP(string file, string workingdirectory)
        {
            var host     = "dungeoneer-dota2.com";
            var port     = 0;
            var username = "";
            var password = "";

            // path for file you want to upload
            var uploadFile = file;

            using (var client = new SftpClient(host, port, username, password))
            {
                client.Connect();
                if (client.IsConnected)
                {
                    client.ChangeDirectory(workingdirectory);

                    using (var fileStream = new FileStream(uploadFile, FileMode.Open))
                    {
                        client.BufferSize = 4 * 1024; // bypass Payload error large files
                        client.UploadFile(fileStream, Path.GetFileName(uploadFile));
                    }
                }
            }
        }
Esempio n. 29
0
        private void ChangeDirectory(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            string working_dir = m_con.WorkingDirectory;

            if (!working_dir.EndsWith("/"))
            {
                working_dir += "/";
            }

            if (working_dir == path)
            {
                return;
            }

            try
            {
                m_con.ChangeDirectory(path);
            }
            catch (Exception ex)
            {
                throw new Interface.FolderMissingException(Strings.SSHv2Backend.FolderNotFoundManagedError(path, ex.Message), ex);
            }
        }
Esempio n. 30
0
        private void SendExecutionLogs(string sessionId, string path)
        {
            //"btf-preprod-artifacts.psr.rd.hpicorp.net"
            string userName = "******";
            string password = "******";

            //get the log data
            TraceFactory.Logger.Debug($"Collecting logs for Session: {sessionId}");
            var logData = SessionClient.Instance.GetLogData(sessionId);

            //we know on STB machines the log file will be present in the location of the calling assembly read that up and return the string
            if (string.IsNullOrEmpty(logData))
            {
                logData = GetLogData(sessionId);
            }

            TraceFactory.Logger.Debug($"Uploading logs to Artifact server: {_btfArtifactsServerName}");
            var connectionInfo = new ConnectionInfo(_btfArtifactsServerName, 22, userName, new PasswordAuthenticationMethod(userName, password));

            using (var client = new SftpClient(connectionInfo))
            {
                client.Connect();
                if (!client.Exists(path))
                {
                    CreateDirectoryRecursively(client, path);
                }
                client.ChangeDirectory(path);

                client.WriteAllText($"{path}/{sessionId}.log", logData);
            }
            TraceFactory.Logger.Debug($"Log written: {path}/{sessionId}.log");
        }
 public void Test_Sftp_ChangeDirectory_Subfolder_With_Slash_Dont_Exists()
 {
     using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         sftp.Connect();
         sftp.ChangeDirectory("/asdasd/sssddds/");
     }
 }
 public void Test_Sftp_ChangeDirectory_Root_Dont_Exists()
 {
     using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         sftp.Connect();
         sftp.ChangeDirectory("/asdasd");
     }
 }
 public void Test_Sftp_ChangeDirectory_Which_Exists()
 {
     using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         sftp.Connect();
         sftp.ChangeDirectory("/usr");
         Assert.AreEqual("/usr", sftp.WorkingDirectory);
     }
 }
        public void Test_Sftp_ChangeDirectory_Null()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                sftp.ChangeDirectory(null);

                sftp.Disconnect();
            }
        }
Esempio n. 35
0
 public void ChangeDirectoryTest()
 {
     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
     target.ChangeDirectory(path);
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
        public void Test_Sftp_Change_Directory()
        {
            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester");

                sftp.CreateDirectory("test1");

                sftp.ChangeDirectory("test1");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1");

                sftp.CreateDirectory("test1_1");
                sftp.CreateDirectory("test1_2");
                sftp.CreateDirectory("test1_3");

                var files = sftp.ListDirectory(".");

                Assert.IsTrue(files.First().FullName.StartsWith(string.Format("{0}", sftp.WorkingDirectory)));

                sftp.ChangeDirectory("test1_1");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1");

                sftp.ChangeDirectory("../test1_2");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_2");

                sftp.ChangeDirectory("..");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1");

                sftp.ChangeDirectory("..");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester");

                files = sftp.ListDirectory("test1/test1_1");

                Assert.IsTrue(files.First().FullName.StartsWith(string.Format("{0}/test1/test1_1", sftp.WorkingDirectory)));

                sftp.ChangeDirectory("test1/test1_1");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1");

                sftp.ChangeDirectory("/home/tester/test1/test1_1");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1");

                sftp.ChangeDirectory("/home/tester/test1/test1_1/../test1_2");

                Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_2");

                sftp.ChangeDirectory("../../");

                sftp.DeleteDirectory("test1/test1_1");
                sftp.DeleteDirectory("test1/test1_2");
                sftp.DeleteDirectory("test1/test1_3");
                sftp.DeleteDirectory("test1");

                sftp.Disconnect();
            }
        }