コード例 #1
0
ファイル: SshCopyTask.cs プロジェクト: jenzy-forks/flubu.core
        protected override int DoExecute(ITaskContextInternal context)
        {
            DoLogInfo($"Connecting to {_userName}@{_host}");
            string password = _password.GetPassword();

            using (ScpClient cl = new ScpClient(_host, _userName, password))
            {
                cl.Connect();
                foreach (SourceDestinationPair item in _items)
                {
                    DoLogInfo($"copy {item.Source}->{item.Destination}");

                    if (item.IsFile)
                    {
                        cl.Upload(new FileInfo(item.Source), item.Destination);
                    }
                    else
                    {
                        cl.Upload(new DirectoryInfo(item.Source), item.Destination);
                    }
                }

                cl.Disconnect();
                return(0);
            }
        }
コード例 #2
0
        protected override async Task <Message> HandleFile(MessageContext context, ScpClient client)
        {
            string sfLocalFile = File != null ? await File.SelectStringAsync(context) : null;

            string sfRemote = Remote != null ? await Remote.SelectStringAsync(context) : null;

            StreamMessage smsg = context.msg as StreamMessage;

            if (smsg != null)
            {
                client.Upload(await smsg.GetStream(), sfRemote);
            }
            else
            {
                if (!System.IO.File.Exists(sfLocalFile))
                {
                    logger.Warn("{0} does not exist and cannot be uploaded to {1}", sfLocalFile, ConnectionName(client.ConnectionInfo));
                    return(null);
                }

                client.Upload(new FileInfo(sfLocalFile), sfRemote);
            }

            return(context.msg);
        }
コード例 #3
0
        public StatusCode Upload(Models.FileTransportInfo transportInformation)
        {
            StatusCode retVal = StatusCode.SUCCEED_STATUS;

            if (client == null || client.IsConnected == false)
            {
                retVal = Open();
                if (retVal.IsSucceeded == false)
                {
                    return(retVal);
                }
            }
            try
            {
                if (transportInformation.SourceIsDirectory)
                {
                    client.Upload(new System.IO.DirectoryInfo(transportInformation.SourceFullName), transportInformation.DestinationFolderName);
                }
                else
                {
                    client.Upload(new System.IO.FileInfo(transportInformation.SourceFullName), transportInformation.DestinationFolderName);
                }
            }
            catch (Exception ex)
            {
                return(new Common.CommonStatusCode(Common.CommonStatusCode.SCP_UPLOAD_ERROR, new object[] { connectionInformation.Host, connectionInformation.Username, transportInformation.SourceFullName, transportInformation.DestinationFolderName }, ex, Config, ApplicationID));
            }
            return(retVal);
        }
コード例 #4
0
        /// <summary>
        /// Upload files to remote target path
        /// </summary>
        /// <param name="filePath">file path</param>
        /// <param name="targetPath">target path</param>
        /// <returns>success or not</returns>
        public bool UploadFile(string filePath, string targetPath)
        {
            bool ret = false;

            if (IsSCPClientActive())
            {
                scpClient.Upload(new FileInfo(filePath), targetPath);
                ret = true;
            }
            return(ret);
        }
コード例 #5
0
        /// <summary>
        /// Upload a file to the connected server.
        /// </summary>
        /// <param name="fileinfo">Local file</param>
        /// <param name="newfile">Server upload full-qualified filename</param>
        public bool UploadFile(FileInfo fileinfo, string newfile)
        {
            bool retVal = false;

            if (!disposed && base.IsConnected)
            {
                using (ScpClient transfer = new ScpClient(base.ConnectionInfo))
                {
                    try
                    {
                        transfer.Connect();
                        transfer.OperationTimeout = new TimeSpan(0, 1, 0);
                        transfer.Upload(fileinfo, newfile);
                        retVal = true;
                    }
                    catch
                    {
                        retVal = false;
                    }
                    finally
                    {
                        transfer.Disconnect();
                    }
                }
            }
            return(retVal);
        }
コード例 #6
0
        /// <summary>
        /// Commit the changes and upload them to the server
        /// </summary>
        public String Commit()
        {
            if (_config.Settings.Enabled)
            {
                ConnectionInfo connInfo = new ConnectionInfo(
                    _config.Settings.Server,
                    _config.Settings.ScpUsername,
                    AuthMethod);

                try
                {
                    using (var client = new ScpClient(connInfo))
                    {
                        client.Connect();
                        if (client.IsConnected)
                        {
                            var originalFileMS = new MemoryStream();
                            try
                            {
                                client.Download(_config.Settings.FilePath, originalFileMS);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine($"{_config.Settings.FilePath}: File Check Failed ({e.Message})");
                            }

                            MemoryStream newDataStream = new MemoryStream();
                            UTF8Encoding encoding      = new UTF8Encoding();
                            newDataStream.Write(encoding.GetBytes(_output.ToString()), 0, _output.Length);

                            var NewVsExisting = Tools.CompareMemoryStreams(originalFileMS, newDataStream);
                            if (NewVsExisting)
                            {
                                Console.WriteLine($"Skipping - Not Changed: {_config.Settings.FilePath}");
                            }
                            else
                            {
                                newDataStream.Position = 0;
                                client.Upload(newDataStream, _config.Settings.FilePath);
                                Console.WriteLine($"Uploaded: {_config.Settings.FilePath}");

                                ReloadOxidizedAsync();
                            }
                            client.Disconnect();
                        }
                    }
                }
                catch (Exception e)
                {
                    return($"Oxidized: Error with SSH Upload ({e.Message}");
                }

                // We made it past the try block so upload was successful;
                return($"Oxidized: Commit Complete");
            }
            else
            {
                return("Plugin is disabled");
            }
        }
コード例 #7
0
        /// <summary>
        /// ListenPort
        /// </summary>
        /// <returns></returns>
        public string ListenPort()
        {
            Constants.log.Info("Entering ScpListener ListenPort Method!");
            string response = string.Empty;

            if (_scpClient == null && _connInfo == null)
            {
                Constants.log.Info("Calling ScpListener InitializeListener Method!");
                InitializeListener();
            }

            try
            {
                _scpClient = new ScpClient(_connInfo);
                _scpClient.Connect();
                _scpClient.Upload(new DirectoryInfo(this.Path), "/home/" + this.Path);
                response = "Uploaded successfully!";
            }
            catch (Exception ex)
            {
                Constants.log.Error(ex.Message);
                response = ex.Message;
            }

            Constants.log.Info("Exiting ScpListener ListenPort Method!");
            return(response);
        }
コード例 #8
0
        public void Test_Scp_File_20_Parallel_Upload_Download()
        {
            using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                scp.Connect();

                var uploadFilenames = new string[20];
                for (int i = 0; i < uploadFilenames.Length; i++)
                {
                    uploadFilenames[i] = Path.GetTempFileName();
                    this.CreateTestFile(uploadFilenames[i], 1);
                }

                Parallel.ForEach(uploadFilenames,
                    (filename) =>
                    {
                        scp.Upload(new FileInfo(filename), Path.GetFileName(filename));
                    });

                Parallel.ForEach(uploadFilenames,
                    (filename) =>
                    {
                        scp.Download(Path.GetFileName(filename), new FileInfo(string.Format("{0}.down", filename)));
                    });

                var result = from file in uploadFilenames
                             where
                                 CalculateMD5(file) == CalculateMD5(string.Format("{0}.down", file))
                             select file;

                scp.Disconnect();

                Assert.IsTrue(result.Count() == uploadFilenames.Length);
            }
        }
コード例 #9
0
        public void Test_Scp_Stream_Upload_Download()
        {
            using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                scp.Connect();

                string uploadedFileName   = Path.GetTempFileName();
                string downloadedFileName = Path.GetTempFileName();

                this.CreateTestFile(uploadedFileName, 1);

                //  Calculate has value
                using (var stream = File.OpenRead(uploadedFileName))
                {
                    scp.Upload(stream, Path.GetFileName(uploadedFileName));
                }

                using (var stream = File.OpenWrite(downloadedFileName))
                {
                    scp.Download(Path.GetFileName(uploadedFileName), stream);
                }

                //  Calculate MD5 value
                var uploadedHash   = CalculateMD5(uploadedFileName);
                var downloadedHash = CalculateMD5(downloadedFileName);

                File.Delete(uploadedFileName);
                File.Delete(downloadedFileName);

                scp.Disconnect();

                Assert.AreEqual(uploadedHash, downloadedHash);
            }
        }
コード例 #10
0
        public void Test_Scp_10MB_File_Upload_Download()
        {
            RemoveAllFiles();

            using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                scp.Connect();

                string uploadedFileName   = Path.GetTempFileName();
                string downloadedFileName = Path.GetTempFileName();

                this.CreateTestFile(uploadedFileName, 10);

                scp.Upload(new FileInfo(uploadedFileName), Path.GetFileName(uploadedFileName));

                scp.Download(Path.GetFileName(uploadedFileName), new FileInfo(downloadedFileName));

                //  Calculate MD5 value
                var uploadedHash   = CalculateMD5(uploadedFileName);
                var downloadedHash = CalculateMD5(downloadedFileName);

                File.Delete(uploadedFileName);
                File.Delete(downloadedFileName);

                scp.Disconnect();

                Assert.AreEqual(uploadedHash, downloadedHash);
            }
        }
コード例 #11
0
        public string SPC_UploadFile(string strfile, string path)
        {
            string text = "Done";

            try
            {
                ScpClient scpClient = new ScpClient("127.0.0.1", "root", "alpine");
                try
                {
                    ((Thread)(object)scpClient).Start();
                    scpClient.Upload(new FileInfo(strfile), path);
                    ((Thread)(object)scpClient).Start();
                }
                finally
                {
                    ((Thread)(object)scpClient)?.Start();
                }
            }
            catch (Exception ex)
            {
                text = "ERROR: " + ((TextReader)(object)ex).ReadToEnd();
            }
            ERROR = text;
            return(text);
        }
コード例 #12
0
    public static void SCPFileSender(UserProgram userProgram)
    {
        try
        {
            //choofdlog.Multiselect = true

            using (SshClient client = new SshClient("127.0.0.1", 10022, "lvuser", ""))
            {
                client.Connect();
                client.RunCommand("rm FRCUserProgram FRCUserProgram.jar"); // Delete existing files so the frc program chooser knows which to run
                client.Disconnect();
            }

            using (ScpClient client = new ScpClient("127.0.0.1", 10022, "lvuser", ""))
            {
                client.Connect();
                using (Stream localFile = File.OpenRead(userProgram.fullFileName))
                {
                    client.Upload(localFile, @"/home/lvuser/" + userProgram.targetFileName);
                }
                client.Disconnect();
            }
        }
        catch (Exception) {}
    }
コード例 #13
0
        /// <summary>
        /// Copy from source to target
        /// </summary>
        /// <returns></returns>
        public override bool Execute(SshClient client)
        {
            Debug.WriteLine("CopyCommand");

            var scp = new ScpClient(client.ConnectionInfo)
            {
                BufferSize = 8 * 1024
            };

            Debug.WriteLine("Connect");

            // Need this or we get Dropbear exceptions...
            scp.Connect();

            Debug.WriteLine("Upload");

            bool status = false;

            try
            {
                scp.Upload(new FileInfo(Source), Target);
                status = true;
            } catch (Exception e)
            {
                Logger.Warn("Exception in SCP transfer: " + e.Message);
            }

            Debug.WriteLine("Done");

            return(status);
        }
コード例 #14
0
        public void Upload()
        {
            if (Protocol == SSHTransferProtocol.SCP)
            {
                if (!ScpClt.IsConnected)
                {
                    //Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg,
                    //    Language.strSSHTransferFailed + Environment.NewLine +
                    //    "SCP Not Connected!");
                    return;
                }
                ScpClt.Upload(new FileInfo(SrcFile), $"{DstFile}");
            }

            if (Protocol == SSHTransferProtocol.SFTP)
            {
                if (!SftpClt.IsConnected)
                {
                    //Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg,
                    //    Language.strSSHTransferFailed + Environment.NewLine +
                    //    "SFTP Not Connected!");
                    return;
                }
                stream_upload       = new FileStream(SrcFile, Open);
                async_upload_result =
                    (SftpUploadAsyncResult)SftpClt.BeginUploadFile(stream_upload, $"{DstFile}",
                                                                   asyncCallback);
            }
        }
コード例 #15
0
        public void Test_Scp_File_20_Parallel_Upload_Download()
        {
            using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                scp.Connect();

                var uploadFilenames = new string[20];
                for (int i = 0; i < uploadFilenames.Length; i++)
                {
                    uploadFilenames[i] = Path.GetTempFileName();
                    this.CreateTestFile(uploadFilenames[i], 1);
                }

                Parallel.ForEach(uploadFilenames,
                                 (filename) =>
                {
                    scp.Upload(new FileInfo(filename), Path.GetFileName(filename));
                });

                Parallel.ForEach(uploadFilenames,
                                 (filename) =>
                {
                    scp.Download(Path.GetFileName(filename), new FileInfo(string.Format("{0}.down", filename)));
                });

                var result = from file in uploadFilenames
                             where
                             CalculateMD5(file) == CalculateMD5(string.Format("{0}.down", file))
                             select file;

                scp.Disconnect();

                Assert.IsTrue(result.Count() == uploadFilenames.Length);
            }
        }
コード例 #16
0
ファイル: Solo.cs プロジェクト: PotatoNanana/Mission-Planner
        public static void flash_px4(string firmware_file)
        {
            if (is_solo_alive)
            {
                using (SshClient client = new SshClient(Solo.soloip, 22, Solo.username, Solo.password))
                {
                    client.KeepAliveInterval = TimeSpan.FromSeconds(5);
                    client.Connect();

                    if (!client.IsConnected)
                    {
                        throw new Exception("Failed to connect ssh");
                    }

                    var retcode = client.RunCommand("rm -rf /firmware/loaded");

                    using (ScpClient scpClient = new ScpClient(client.ConnectionInfo))
                    {
                        scpClient.Connect();

                        if (!scpClient.IsConnected)
                        {
                            throw new Exception("Failed to connect scp");
                        }

                        scpClient.Upload(new FileInfo(firmware_file), "/firmware/" + Path.GetFileName(firmware_file));
                    }

                    var st = client.CreateShellStream("bash", 80, 24, 800, 600, 1024 * 8);

                    // wait for bash prompt
                    while (!st.DataAvailable)
                    {
                        System.Threading.Thread.Sleep(200);
                    }

                    st.WriteLine("loadPixhawk.py; exit;");
                    st.Flush();

                    StringBuilder output = new StringBuilder();

                    while (client.IsConnected)
                    {
                        var line = st.Read();
                        Console.Write(line);
                        output.Append(line);
                        System.Threading.Thread.Sleep(100);

                        if (output.ToString().Contains("logout"))
                        {
                            break;
                        }
                    }
                }
            }
            else
            {
                throw new Exception("Solo is not responding to pings");
            }
        }
コード例 #17
0
        public Status CopyPatchToServer(string source, string destinationPath)
        {
            Status status = Status.Unknown;

            try
            {
                using (var client = new ScpClient(hostname, username, password))
                {
                    status = Status.Failed_Connect;
                    client.Connect();
                    using (var localFile = File.OpenRead(source))
                    {
                        status = Status.Failed_Transfer;
                        string destinationFile = Path.Combine(destinationPath, Path.GetFileName(source)).Replace("\\", "/");
                        client.Upload(localFile, destinationFile);
                        status = Status.Successful;
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
            }
            return(status);
        }
コード例 #18
0
ファイル: ScpClientTest.cs プロジェクト: REALTOBIZ/SSH.NET
        public void Test_Scp_File_Upload_Download()
        {
            RemoveAllFiles();

            using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                scp.Connect();

                string uploadedFileName = Path.GetTempFileName();
                string downloadedFileName = Path.GetTempFileName();

                this.CreateTestFile(uploadedFileName, 1);

                scp.Upload(new FileInfo(uploadedFileName), Path.GetFileName(uploadedFileName));

                scp.Download(Path.GetFileName(uploadedFileName), new FileInfo(downloadedFileName));

                //  Calculate MD5 value
                var uploadedHash = CalculateMD5(uploadedFileName);
                var downloadedHash = CalculateMD5(downloadedFileName);

                File.Delete(uploadedFileName);
                File.Delete(downloadedFileName);

                scp.Disconnect();

                Assert.AreEqual(uploadedHash, downloadedHash);
            }
        }
コード例 #19
0
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console()
                         .CreateLogger();
            var host = args[0];
            var name = args[1];
            var pwd  = args[2];

            using var scpClient = new ScpClient(host, 20002, name, pwd);
            scpClient.Connect();
            if (scpClient.IsConnected)
            {
                Log.Logger.Information("SCP服务器连接成功");
            }
            else
            {
                Log.Logger.Error("SCP服务器连接失败");
                return;
            }

            var md5s = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.md5");

            md5s.ToList().ForEach(_ => { scpClient.Upload(File.OpenRead(_), $"/var/www/html/files/{Path.GetFileName(_)}"); });
            var fs = File.OpenRead("./Minecraft-Mod-Language-Package.zip");

            scpClient.Upload(fs, "/var/www/html/files/Minecraft-Mod-Language-Modpack.zip.1");
            Log.Logger.Information("上传成功");
            scpClient.Dispose();
            using var sshClient = new SshClient(host, 20002, name, pwd);
            sshClient.Connect();
            if (sshClient.IsConnected)
            {
                Log.Logger.Information("SSH服务器连接成功");
            }
            else
            {
                Log.Logger.Error("SSH服务器连接失败");
                return;
            }
            using var cmd = sshClient.CreateCommand("mv /var/www/html/files/Minecraft-Mod-Language-Modpack.zip.1 /var/www/html/files/Minecraft-Mod-Language-Modpack.zip");
            cmd.Execute();
            var err = cmd.Error;

            Log.Logger.Error(err);
            sshClient.Dispose();
        }
コード例 #20
0
ファイル: Runner.cs プロジェクト: 14lox/shopping
        private static void CopyScript(ConnectionInfo info)
        {
            var scp = new ScpClient(info);

            scp.Connect();
            scp.Upload(new FileInfo(@"./insert.sql"), "/home/ubuntu/se/shopping/script/");
            scp.Disconnect();
        }
コード例 #21
0
        public bool RecoverDb(Host FileServerHost)
        {
            string old_FileName = m_DbFile;
            string dbFile_ext   = Path.GetExtension(old_FileName);
            string new_FileName = Path.GetFileNameWithoutExtension(old_FileName) +
                                  DateTime.Now.ToString("yy-MM-dd_HH-mm-ss") + dbFile_ext;

            System.IO.File.Copy(old_FileName, new_FileName);

            using (var client = new ScpClient(FileServerHost.IP, FileServerHost.User, FileServerHost.Passwd))
            {
                client.Connect();
                client.Upload(new FileInfo(old_FileName), "/app/fileserver/www/" + Path.GetFileName(old_FileName));
                client.Upload(new FileInfo(new_FileName), "/app/fileserver/www/" + Path.GetFileName(new_FileName));
            }
            return(true);
        }
コード例 #22
0
        private static async Task UploadInputFilesAsync(long jobId, List <long?> taskIds, string sessionCode)
        {
            var client  = new RestClient(baseUrl);
            var request = new RestRequest("FileTransfer/GetFileTransferMethod", Method.Post)
            {
                RequestFormat = DataFormat.Json
            }.AddJsonBody(
                new GetFileTransferMethodModel
            {
                SubmittedJobInfoId = jobId,
                SessionCode        = sessionCode
            });
            var response = await client.ExecuteAsync(request);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception(response.Content.ToString());
            }

            FileTransferMethodExt ft = JsonConvert.DeserializeObject <FileTransferMethodExt>(response.Content.ToString());

            using (MemoryStream pKeyStream = new MemoryStream(Encoding.UTF8.GetBytes(ft.Credentials.PrivateKey)))
            {
                using (ScpClient scpClient = new ScpClient(ft.ServerHostname, ft.Credentials.Username, new PrivateKeyFile(pKeyStream)))
                {
                    scpClient.Connect();
                    DirectoryInfo di = new DirectoryInfo(@"C:\Heappe\projects\develop\tests\input\");
                    foreach (var taskId in taskIds)
                    {
                        foreach (FileInfo fi in di.GetFiles())
                        {
                            sb.AppendLine($"Uploading file: {fi.Name}");
                            scpClient.Upload(fi, ft.SharedBasepath + "/" + taskId + "/" + fi.Name);
                            sb.AppendLine($"File uploaded: {fi.Name}");
                        }
                    }
                }
            }

            client  = new RestClient(baseUrl);
            request = new RestRequest("FileTransfer/EndFileTransfer", Method.Post)
            {
                RequestFormat = DataFormat.Json
            }.AddJsonBody(
                new EndFileTransferModel
            {
                SubmittedJobInfoId = jobId,
                UsedTransferMethod = ft,
                SessionCode        = sessionCode
            });
            response = await client.ExecuteAsync(request);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception(response.Content.ToString());
            }
        }
 public static void Send(string host, string username, string password, string fileName)
 {
     using (ScpClient client = new ScpClient(host, username, password))
     {
         String Path = @".";
         client.Connect();
         client.Upload(new FileInfo(fileName), Path);
         client.Disconnect();
     }
 }
コード例 #24
0
        [Ignore] // placeholder for actual test
        public void UploadTest2()
        {
            ConnectionInfo connectionInfo = null;                          // TODO: Initialize to an appropriate value
            ScpClient      target         = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value
            Stream         source         = null;                          // TODO: Initialize to an appropriate value
            string         filename       = string.Empty;                  // TODO: Initialize to an appropriate value

            target.Upload(source, filename);
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
コード例 #25
0
ファイル: UploadToEv3.cs プロジェクト: alennartz/monoev3
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            BuildProject();

            var proj = GetStartupProject();

            if (proj == null)
            {
                ShowErrorMessage("Ev3 Extension", "Could not find startup project");
                return;
            }

            var files = GetFilesToUpload(proj);

            var dest = $"/home/root/apps/{GetEv3ProgramFolderName(proj)}";

            WriteLine($"will upload {files.Count} files to: '{dest}'");

            ThreadPool.QueueUserWorkItem(_ =>
            {
                try
                {
                    using (ScpClient client = new ScpClient(new ConnectionInfo("10.0.1.1", "root", new PasswordAuthenticationMethod("root", ""))))
                    {
                        client.Connect();
                        //make sure folder exists
                        client.Upload(new DirectoryInfo(m_emptyFolder), dest);
                        foreach (var item in files)
                        {
                            var fi = new FileInfo(item);
                            WriteLine($"uploading {fi.Name} ...");
                            client.Upload(fi, $"{dest}/{fi.Name}");
                        }
                    }
                    WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] Upload finished");
                }
                catch (Exception ex)
                {
                    ShowErrorMessage("Error Uploading", ex.ToString());
                }
            });
        }
コード例 #26
0
 public void upload_button_pressed(object sender, EventArgs e)
 {
     foreach (directory_entry entry in l_explorer.get_virtual_directory())
     {
         FileInfo info = new FileInfo(entry.GetPath());
         scp_client.Upload(info, r_explorer.get_remote_directory().GetPath() + entry.GetName());
     }
     l_explorer.get_virtual_directory().Clear();
     l_explorer.show();
     r_explorer.show();
 }
コード例 #27
0
        /// <summary>
        /// Send a user program to the active VM
        /// </summary>
        /// <param name="userProgram">The user program to upload</param>
        /// <param name="autorun">True to run the user program automatically</param>
        /// <returns>True if successful</returns>
        public static Task <bool> SCPFileSender(UserProgram userProgram, bool autorun = true)
        {
            return(Task.Run(async() =>
            {
                try
                {
                    isRobotCodeRestarting = true; // Prevent code from auto-restarting until this finishes
                    if (IsRunningRobotCodeRunner() || IsTryingToRunRobotCode())
                    {
                        await StopRobotCode();
                    }
                    isTryingToRunRobotCode = false;

                    programType = userProgram.ProgramType;
                    ClientManager.Connect();
                    ClientManager.Instance.RunCommand("rm -rf FRCUserProgram FRCUserProgram.jar").CommandTimeout = TimeSpan.FromSeconds(SSH_COMMAND_TIMEOUT);
                    frcUserProgramPresent = false;
                    using (ScpClient scpClient = new ScpClient(DEFAULT_HOST, programType == UserProgram.Type.JAVA ? DEFAULT_SSH_PORT_JAVA : DEFAULT_SSH_PORT_CPP, USER, PASSWORD))
                    {
                        try
                        {
                            scpClient.Connect();
                            using (Stream localFile = File.OpenRead(userProgram.FullFileName))
                            {
                                scpClient.ConnectionInfo.Timeout = TimeSpan.FromSeconds((double)userProgram.Size / (1024 * 1024) * 10); // File size in MB * 5 seconds
                                scpClient.Upload(localFile, "/home/lvuser/" + userProgram.TargetFileName);
                                frcUserProgramPresent = true;
                            }
                            scpClient.Disconnect();
                        }
                        catch (Exception)
                        {
                            scpClient.Disconnect();
                            throw;
                        }
                    }
                    if (autorun)
                    {
                        await RestartRobotCode();
                    }
                    else
                    {
                        isRobotCodeRestarting = false;
                    }
                }
                catch (Exception e)
                {
                    Debug.Log(e.ToString());
                    isRobotCodeRestarting = false;
                    return false;
                }
                return true;
            }));
        }
コード例 #28
0
ファイル: Uploader.cs プロジェクト: kashmervil/trik-upload
        public void Connect()
        {
            _scpClient.Connect();
            _scpClient.KeepAliveInterval = TimeSpan.FromSeconds(10.0);

            _sshClient.Connect();
            _sshClient.KeepAliveInterval = TimeSpan.FromSeconds(10.0);
            _shellStream       = _sshClient.CreateShellStream("CONTROLLER-SHELL", 80, 24, 800, 600, 1024);
            _shellWriterStream = new StreamWriter(_shellStream)
            {
                AutoFlush = true
            };

            _timer.Start();
            _timer.Elapsed += KeepAlive;
            _sshClient.RunCommand(
                "mkdir -p /home/root/trik-sharp /home/root/trik-sharp/uploads /home/root/trik/scripts/trik-sharp");
            Task.Run(() => _scpClient.Upload(new FileInfo(_libconwrapPath),
                                             "/home/root/trik-sharp/uploads/" + Path.GetFileName(_libconwrapPath)));
        }
コード例 #29
0
        public void Test_Scp_File_Upload_Download_Events()
        {
            using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                scp.Connect();

                var uploadFilenames = new string[10];

                for (int i = 0; i < uploadFilenames.Length; i++)
                {
                    uploadFilenames[i] = Path.GetTempFileName();
                    this.CreateTestFile(uploadFilenames[i], 1);
                }

                var uploadedFiles   = uploadFilenames.ToDictionary((filename) => Path.GetFileName(filename), (filename) => 0L);
                var downloadedFiles = uploadFilenames.ToDictionary((filename) => string.Format("{0}.down", Path.GetFileName(filename)), (filename) => 0L);

                scp.Uploading += delegate(object sender, ScpUploadEventArgs e)
                {
                    uploadedFiles[e.Filename] = e.Uploaded;
                };

                scp.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                {
                    downloadedFiles[string.Format("{0}.down", e.Filename)] = e.Downloaded;
                };


                Parallel.ForEach(uploadFilenames,
                                 (filename) =>
                {
                    scp.Upload(new FileInfo(filename), Path.GetFileName(filename));
                });

                Parallel.ForEach(uploadFilenames,
                                 (filename) =>
                {
                    scp.Download(Path.GetFileName(filename), new FileInfo(string.Format("{0}.down", filename)));
                });

                var result = from uf in uploadedFiles
                             from df in downloadedFiles
                             where
                             string.Format("{0}.down", uf.Key) == df.Key &&
                             uf.Value == df.Value
                             select uf;


                scp.Disconnect();

                Assert.IsTrue(result.Count() == uploadFilenames.Length && uploadFilenames.Length == uploadedFiles.Count && uploadedFiles.Count == downloadedFiles.Count);
            }
        }
コード例 #30
0
 protected override void Act()
 {
     try
     {
         _scpClient.Upload(_source, _remotePath);
         Assert.Fail();
     }
     catch (SshException ex)
     {
         _actualException = ex;
     }
 }
 protected override void Act()
 {
     try
     {
         _scpClient.Upload(_directoryInfo, _path);
         Assert.Fail();
     }
     catch (SshException ex)
     {
         _actualException = ex;
     }
 }
 protected virtual void Act()
 {
     try
     {
         _scpClient.Upload(_fileInfo, _path);
         Assert.Fail();
     }
     catch (SshException ex)
     {
         _actualException = ex;
     }
 }
コード例 #33
0
        public void Test_Scp_File_Upload_Download_Events()
        {
            using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                scp.Connect();

                var uploadFilenames = new string[10];

                for (int i = 0; i < uploadFilenames.Length; i++)
                {
                    uploadFilenames[i] = Path.GetTempFileName();
                    this.CreateTestFile(uploadFilenames[i], 1);
                }

                var uploadedFiles = uploadFilenames.ToDictionary((filename) => Path.GetFileName(filename), (filename) => 0L);
                var downloadedFiles = uploadFilenames.ToDictionary((filename) => string.Format("{0}.down", Path.GetFileName(filename)), (filename) => 0L);

                scp.Uploading += delegate(object sender, ScpUploadEventArgs e)
                {
                    uploadedFiles[e.Filename] = e.Uploaded;
                };

                scp.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                {
                    downloadedFiles[string.Format("{0}.down", e.Filename)] = e.Downloaded;
                };

                Parallel.ForEach(uploadFilenames,
                    (filename) =>
                    {
                        scp.Upload(new FileInfo(filename), Path.GetFileName(filename));
                    });

                Parallel.ForEach(uploadFilenames,
                    (filename) =>
                    {
                        scp.Download(Path.GetFileName(filename), new FileInfo(string.Format("{0}.down", filename)));
                    });

                var result = from uf in uploadedFiles
                             from df in downloadedFiles
                             where
                                 string.Format("{0}.down", uf.Key) == df.Key
                                 && uf.Value == df.Value
                             select uf;

                scp.Disconnect();

                Assert.IsTrue(result.Count() == uploadFilenames.Length && uploadFilenames.Length == uploadedFiles.Count && uploadedFiles.Count == downloadedFiles.Count);
            }
        }
コード例 #34
0
ファイル: ScpClientTest.cs プロジェクト: REALTOBIZ/SSH.NET
        public void Test_Scp_Directory_Upload_Download()
        {
            RemoveAllFiles();

            using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                scp.Connect();

                var uploadDirectory = Directory.CreateDirectory(string.Format("{0}\\{1}", Path.GetTempPath(), Path.GetRandomFileName()));
                for (int i = 0; i < 3; i++)
                {
                    var subfolder = Directory.CreateDirectory(string.Format(@"{0}\folder_{1}", uploadDirectory.FullName, i));
                    for (int j = 0; j < 5; j++)
                    {
                        this.CreateTestFile(string.Format(@"{0}\file_{1}", subfolder.FullName, j), 1);
                    }
                    this.CreateTestFile(string.Format(@"{0}\file_{1}", uploadDirectory.FullName, i), 1);
                }

                scp.Upload(uploadDirectory, "uploaded_dir");

                var downloadDirectory = Directory.CreateDirectory(string.Format("{0}\\{1}", Path.GetTempPath(), Path.GetRandomFileName()));

                scp.Download("uploaded_dir", downloadDirectory);

                var uploadedFiles = uploadDirectory.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
                var downloadFiles = downloadDirectory.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

                var result = from f1 in uploadedFiles
                             from f2 in downloadFiles
                             where
                                f1.FullName.Substring(uploadDirectory.FullName.Length) == f2.FullName.Substring(downloadDirectory.FullName.Length)
                                && CalculateMD5(f1.FullName) == CalculateMD5(f2.FullName)
                             select f1;

                var counter = result.Count();

                scp.Disconnect();

                Assert.IsTrue(counter == uploadedFiles.Length && uploadedFiles.Length == downloadFiles.Length);
            }
        }
コード例 #35
0
ファイル: ScpClientTest.cs プロジェクト: REALTOBIZ/SSH.NET
        public void Test_Scp_10MB_Stream_Upload_Download()
        {
            RemoveAllFiles();

            using (var scp = new ScpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                scp.Connect();

                string uploadedFileName = Path.GetTempFileName();
                string downloadedFileName = Path.GetTempFileName();

                this.CreateTestFile(uploadedFileName, 10);

                //  Calculate has value
                using (var stream = File.OpenRead(uploadedFileName))
                {
                    scp.Upload(stream, Path.GetFileName(uploadedFileName));
                }

                using (var stream = File.OpenWrite(downloadedFileName))
                {
                    scp.Download(Path.GetFileName(uploadedFileName), stream);
                }

                //  Calculate MD5 value
                var uploadedHash = CalculateMD5(uploadedFileName);
                var downloadedHash = CalculateMD5(downloadedFileName);

                File.Delete(uploadedFileName);
                File.Delete(downloadedFileName);

                scp.Disconnect();

                Assert.AreEqual(uploadedHash, downloadedHash);
            }
        }
コード例 #36
0
ファイル: ScpClientTest.cs プロジェクト: REALTOBIZ/SSH.NET
 [Ignore] // placeholder for actual test
 public void UploadTest2()
 {
     ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
     ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value
     Stream source = null; // TODO: Initialize to an appropriate value
     string filename = string.Empty; // TODO: Initialize to an appropriate value
     target.Upload(source, filename);
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
コード例 #37
0
                private void StartTransfer(SSHTransferProtocol Protocol)
                {
                    if (AllFieldsSet() == false)
                    {
                        Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg,
                                                            Language.strPleaseFillAllFields);
                        return;
                    }

                    if (File.Exists(this.txtLocalFile.Text) == false)
                    {
                        Runtime.MessageCollector.AddMessage(Messages.MessageClass.WarningMsg,
                                                            Language.strLocalFileDoesNotExist);
                        return;
                    }

                    try
                    {
                        if (Protocol == SSHTransferProtocol.SCP)
                        {
                            var ssh = new ScpClient(txtHost.Text, int.Parse(this.txtPort.Text), txtUser.Text, txtPassword.Text);
                            ssh.Uploading+=(sender, e) => SetProgressStatus(e.Uploaded, e.Size);
                            DisableButtons();
                            ssh.Connect();
                            ssh.Upload(new FileStream(txtLocalFile.Text,FileMode.Open), txtRemoteFile.Text);
                        }
                        else if (Protocol == SSHTransferProtocol.SFTP)
                        {
                            var ssh = new SftpClient(txtHost.Text, int.Parse(txtPort.Text),txtUser.Text, txtPassword.Text);
                            var s = new FileStream(txtLocalFile.Text, FileMode.Open);
                            ssh.Connect();
                            var i = ssh.BeginUploadFile(s, txtRemoteFile.Text) as SftpUploadAsyncResult;
                            ThreadPool.QueueUserWorkItem(state =>
                            {
                                while (!i.IsCompleted)
                                {
                                    SetProgressStatus((long)i.UploadedBytes, s.Length);
                                }
                                MessageBox.Show(Language.SSHTransfer_StartTransfer_Upload_completed_);
                                EnableButtons();
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg,
                                                            Language.strSSHTransferFailed + Constants.vbNewLine +
                                                            ex.Message);
                        EnableButtons();
                    }
                }