예제 #1
0
        public StatusCode Open()
        {
            StatusCode retVal = StatusCode.SUCCEED_STATUS;

            try
            {
                if (client != null)
                {
                    if (client.IsConnected)
                    {
                        return(StatusCode.SUCCEED_STATUS);
                    }
                    else
                    {
                        client.Disconnect();
                        client = new ScpClient(connectionInformation);
                        client.Connect();
                    }
                }
                else
                {
                    client = new ScpClient(connectionInformation);
                    client.Connect();
                }
                return(StatusCode.SUCCEED_STATUS);
            }
            catch (Exception ex)
            {
                return(new Common.CommonStatusCode(Common.CommonStatusCode.SCP_CONNECT_ERROR, new object[] { connectionInformation.Host, connectionInformation.Username }, ex, Config, ApplicationID));
            }
        }
예제 #2
0
        public void Cancel()
        {
            if (_scpClient.IsConnected)
            {
                _scpClient.Disconnect();
            }

            ErrorMessage = "Upload canceled";
            wait.Set();
        }
예제 #3
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;
            }));
        }
예제 #4
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);
            }
        }
예제 #5
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");
            }
        }
예제 #6
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) {}
    }
예제 #7
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);
            }
        }
예제 #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 bool DownloadLog(NotificationModel notification, string destinationFolder)
        {
            try
            {
                var pk = new PrivateKeyFile(ApplicationConstant.PrivateKeyFilePath);
                //var folder = DateTime.Now.ToString(ApplicationConstant.DatetimeFormat);
                var destination = new DirectoryInfo(destinationFolder);
                var logPath     = $"{ServerTrainConstant.DarknetPath}/{notification.LogPath}";
                var lossPath    = $"{ServerTrainConstant.DarknetPath}/{notification.LossFunctionPath}";
                var trainServer = CommonService.GetUrlApiTrainServer();
                using (var client = new ScpClient(trainServer, 22, ServerTrainConstant.Username, pk))
                {
                    client.Connect();

                    client.Download(logPath, destination);
                    client.Download(lossPath, destination);

                    client.Disconnect();
                }
            }
            catch (Exception e)
            {
                ExceptionLogging.SendErrorToText(e, nameof(this.DownloadWeight), nameof(DataSetService));
                return(false);
            }
            return(true);
        }
예제 #10
0
 public async Task <bool> ReconnectAsync()
 {
     return(await Task.Run(() =>
     {
         _timer.Elapsed -= KeepAlive;
         try
         {
             _scpClient.Disconnect();
             _scpClient.Connect();
             _sshClient.Disconnect();
             _sshClient.Connect();
         }
         catch (SocketException)
         {
             return false;
         }
         _shellStream = _sshClient.CreateShellStream("CONTROLLER-SHELL", 80, 24, 800, 600, 1024);
         _shellWriterStream = new StreamWriter(_shellStream)
         {
             AutoFlush = true
         };
         _timer.Elapsed += KeepAlive;
         return true;
     }));
 }
예제 #11
0
        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);
            }
        }
예제 #12
0
        /// <summary>
        /// Downloads the directory.
        /// </summary>
        /// <param name="host">The host.</param>
        /// <param name="uid">The uid.</param>
        /// <param name="pwd">The password.</param>
        /// <param name="remotePath">The remote path.</param>
        /// <param name="localPath">The local path.</param>
        /// <param name="errOut">The error out.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        /// <example>
        /// SSHFileTransfer ssh = new SSHFileTransfer();<br/>
        /// ssh.CurrentFile += (sender, e) =><br/>
        ///    {<br/>
        /// Debug.Print(e);<br/>
        /// };<br/>
        /// ssh.UploadStatus += (sender, e) =><br/>
        /// {<br/>
        /// Debug.Print(e.ToString());<br/>
        /// };<br/>
        /// bool value = ssh.DownloadDirectory("testmachine", "root", "toor", "/root/Downloads/", "C:\Test\",out errOut);
        /// </example>
        public bool DownloadDirectory(string host, string uid, string pwd, string remotePath, string localPath, out string errOut)
        {
            bool bAns = false;
            errOut = @"";
            try
            {
                DirectoryInfo toPath = new DirectoryInfo(localPath);
                ConnectionInfo connectionInfo = new ConnectionInfo(host, uid, new PasswordAuthenticationMethod(uid, pwd), new PrivateKeyAuthenticationMethod(General.RsaKey));

                ScpClient client = new ScpClient(connectionInfo);

                client.Connect();

                client.Downloading += delegate (object sender, ScpDownloadEventArgs e)
                {
                    OnCurrentFile(e.Filename);
                    OnDownloadStatus(CalcPercentage(e.Downloaded, e.Size));
                };

                client.Download(remotePath, toPath);
                bAns = true;
                client.Disconnect();
            }
            catch (Exception e)
            {
                errOut = ErrorMessage("DownloadDirectory", e);
            }
            return bAns;
        }
예제 #13
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);
        }
예제 #14
0
        public bool DownloadLogAndLoss(WeightVersionModel weight, string destinationFolder)
        {
            try
            {
                if (string.IsNullOrEmpty(weight.LogPath) || string.IsNullOrEmpty(weight.LossFunctionPath))
                {
                    return(false);
                }
                var pk = new PrivateKeyFile(ApplicationConstant.PrivateKeyFilePath);
                //var folder = DateTime.Now.ToString(ApplicationConstant.DatetimeFormat);
                var destination   = new DirectoryInfo(destinationFolder);
                var logPath       = $"{ServerDetectConstant.ApiPath}/{weight.LogPath}";
                var lossPath      = $"{ServerDetectConstant.ApiPath}/{weight.LossFunctionPath}";
                var detectSertver = CommonService.GetUrlDetectServer();
                using (var client = new ScpClient(detectSertver, 22, ServerTrainConstant.Username, pk))
                {
                    client.Connect();

                    client.Download(logPath, destination);
                    client.Download(lossPath, destination);

                    client.Disconnect();
                }
            }
            catch
            {
                return(false);
            }
            return(true);
        }
        public void Disconnect(bool cleanup = true)
        {
            if (cleanup)
            {
                SshClient.RunCommand(Prepend + "cd ..; rm -r " + DirName).Execute();
            }
            else
            {
                string dest = "FunctionalTest-" + Info.Host;
                var    res  = SshClient.RunCommand(Prepend + "cd ..; mv " + DirName + " " + dest).Execute();
            }

            if (m_ssh != null)
            {
                m_ssh.Disconnect();
                m_ssh.Dispose();
                m_ssh = null;
            }

            if (m_scp != null)
            {
                m_scp.Disconnect();
                m_scp.Dispose();
                m_scp = null;
            }
        }
예제 #16
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);
            }
        }
예제 #17
0
        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);
            }
        }
예제 #18
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();
        }
예제 #19
0
        public void Dispose()
        {
            sshClient?.Disconnect();
            sshClient?.Dispose();

            scpClient?.Disconnect();
            scpClient?.Dispose();
        }
 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();
     }
 }
예제 #21
0
 public void Disconnect()
 {
     if (sshClient != null && sshClient.IsConnected)
     {
         sshClient.Disconnect();
     }
     if (scpClient != null && scpClient.IsConnected)
     {
         scpClient.Disconnect();
     }
 }
예제 #22
0
 public void Disconnect()
 {
     try {
         if (scp != null && Connected)
         {
             scp.Disconnect();
         }
     }
     catch (Exception ex) {
         throw new Exception(string.Format("Disconnect SCP failure,cause:{0}", ex.Message));
     }
 }
예제 #23
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);
            }
        }
        public void Disconnect()
        {
            if (Protocol == SSHTransferProtocol.SCP)
            {
                ScpClt.Disconnect();
            }

            if (Protocol == SSHTransferProtocol.SFTP)
            {
                SftpClt.Disconnect();
            }
        }
예제 #25
0
        /// <summary>
        /// Helper to test the connection
        /// </summary>
        public void TestConnection()
        {
            try
            {
                Error       = "";
                Information = "";

                if (Protocol == FileServerProtocol.FTP)
                {
                    FtpClient client = new FtpClient(HostName, UserName, ClearPassword);

                    if (PortNumber == 0)
                    {
                        client.AutoConnect();
                    }
                    else
                    {
                        client.Port = PortNumber;
                        client.Connect();
                    }
                    client.Disconnect();
                }
                else if (Protocol == FileServerProtocol.SFTP)
                {
                    using (var sftp = new SftpClient(HostName, UserName, ClearPassword))
                    {
                        sftp.Connect();
                        sftp.Disconnect();
                    }
                }
                else if (Protocol == FileServerProtocol.SCP)
                {
                    using (var scp = new ScpClient(HostName, UserName, ClearPassword))
                    {
                        scp.Connect();
                        scp.Disconnect();
                    }
                }
                Information = string.Format("The connection to '{0}:{1}' is successfull", HostName, PortNumber);
            }
            catch (Exception ex)
            {
                Error = ex.Message;
                if (ex.InnerException != null)
                {
                    Error += " " + ex.InnerException.Message.Trim();
                }
                Information = "Error got testing the connection.";
            }
        }
예제 #26
0
        private async Task GetLog(SocketMessage message)
        {
            List <string> commandParams = message.Content.Split(" ").ToList();

            if (commandParams.Count != 2)
            {
                await message.Channel.SendMessageAsync($"Usage: !getlog servername (ex.: USA01 or GER01)");

                return;
            }
            ServerConnection serverConnection = config.ServersConnections.FirstOrDefault(s => s.ServerName == commandParams[1]);

            if (serverConnection == null)
            {
                await message.Channel.SendMessageAsync($"Unknown server: {commandParams[1]}");

                return;
            }
            await message.Channel.SendMessageAsync($"{message.Author.Username} asked for the logs for server {commandParams[1]}");

            using (ScpClient scp = new ScpClient(serverConnection.Ip, serverConnection.Login, serverConnection.Password))
            {
                scp.Connect();
                await message.Channel.SendMessageAsync($"Connection successful");

                using var rawStream = new MemoryStream();

                scp.Download("server/serverlog.txt", rawStream);
                var length = rawStream.Length;
                rawStream.Seek(0, SeekOrigin.Begin);

                using var zipStream = new MemoryStream();
                using (var gzip = new GZipStream(zipStream, CompressionMode.Compress))
                {
                    rawStream.CopyTo(gzip);
                    zipStream.Seek(0, SeekOrigin.Begin);
                    try
                    {
                        await message.Channel.SendFileAsync(zipStream, $"serverlog-{serverConnection.ServerName}.log.gz");
                    }
                    catch (HttpException)
                    {
                        await message.Channel.SendMessageAsync($"Log size might be too long: {length / 1024 / 1024}MB");
                    }
                }

                scp.Disconnect();
            }
        }
예제 #27
0
    public static void fwupdate(string host, string name, string pass)
    {
        SshClient ssh = new SshClient(host, 22, name, pass);
        ScpClient scp = new ScpClient(host, 22, name, pass);

        scp.Connect();
        FileInfo file = new FileInfo("C:\\fw\\fwupdate.bin");

        scp.Upload(file, "/tmp/fwupdate.bin");
        scp.Disconnect();
        ssh.Connect();
        ssh.RunCommand("/sbin/fwupdate -m");
        ssh.Disconnect();
        ssh.Dispose();
    }
예제 #28
0
 /// <summary>
 /// Dispose
 /// </summary>
 public void DisposeSCPClient()
 {
     try
     {
         if (scpClient != null)
         {
             scpClient.Disconnect();
             scpClient.Dispose();
         }
     }
     finally
     {
         scpClient = null;
     }
 }
예제 #29
0
        public void fixAppStore()
        {
            SshClient sshclient = new SshClient(host, user, pass);

            try
            {
                txtlog.Text += "Ejecutando comandos \r\n";
                sshclient.Connect();
                SshCommand appstore = sshclient.CreateCommand(@"mv /var/mobile/Library/Preferences/com.apple.purplebuddy.plist /var/mobile/Library/Preferences/com.apple.purplebuddy.plist.old");

                var asynch = appstore.BeginExecute();
                while (!asynch.IsCompleted)
                {
                    //  Waiting for command to complete...
                    Thread.Sleep(2000);
                }
                var result = appstore.EndExecute(asynch);
                sshclient.Disconnect();
            }
            catch (Exception e)
            {
                Analytics.TrackEvent(e.Message + " : " + uid);
                if (e.Message.Contains("SSH protocol identification"))
                {
                    MessageBox.Show("Verifique el etado de su JailBreak", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

            ScpClient scpClient = new ScpClient(host, user, pass);

            try
            {
                scpClient.Connect();
                scpClient.Upload(new FileInfo(path + "\\library\\com.apple.purplebuddy.plist"), "/var/mobile/Library/Preferences/com.apple.purplebuddy.plist");
                scpClient.Disconnect();
            }
            catch (Exception e)
            {
                Analytics.TrackEvent(e.Message + " : " + uid);
                if (e.Message.Contains("SSH protocol identification"))
                {
                    MessageBox.Show("Verifique el estado de su JailBreak", "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Process.Start("https://youtu.be/DlUuJt2Xhuw");
                }
            }
            txtlog.Text += "AppStore parcheado, Reinicie su dispositivo \r\n";
            stopProxi();
        }
예제 #30
0
        // 上传文件
        private void uploadFile(String fileName)
        {
            scp = new ScpClient(IpAddr, Username, Password);

            try
            {
                scp.Connect();
                FileStream fsSrc = new FileStream(fileName, FileMode.Open);
                scp.Upload(fsSrc, remoteWorkPath + "/" + tcExeFileName);
                scp.Disconnect();
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format("连接SFTP失败,原因:{0}", ex.Message));
            }
        }
예제 #31
0
        private static void ScpUpload(string host, int port, string username, string privateKeyPath, string privateKeyPassphrase, string filePath, string destinationFilePath)
        {
            ConnectionInfo connInfo = new ConnectionInfo(host, username, new AuthenticationMethod[] {
                new PrivateKeyAuthenticationMethod(username, new PrivateKeyFile[] {
                    new PrivateKeyFile(privateKeyPath, privateKeyPassphrase)
                })
            });

            using (var scp = new ScpClient(connInfo))
            {
                scp.Connect();
                scp.Upload(new FileInfo(filePath), destinationFilePath);
                scp.Disconnect();
                ManageClipboard(filePath);
            }
        }
예제 #32
0
        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);
            }
        }
예제 #33
0
        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);
            }
        }
예제 #34
0
        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);
            }
        }
예제 #35
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);
            }
        }