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); } }
protected void Arrange() { var random = new Random(); _fileName = CreateTemporaryFile(new byte[] {1}); _connectionInfo = new ConnectionInfo("host", 22, "user", new PasswordAuthenticationMethod("user", "pwd")); _fileInfo = new FileInfo(_fileName); _path = random.Next().ToString(CultureInfo.InvariantCulture); _uploadingRegister = new List<ScpUploadEventArgs>(); _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict); _sessionMock = new Mock<ISession>(MockBehavior.Strict); _channelSessionMock = new Mock<IChannelSession>(MockBehavior.Strict); _pipeStreamMock = new Mock<PipeStream>(MockBehavior.Strict); var sequence = new MockSequence(); _serviceFactoryMock.InSequence(sequence) .Setup(p => p.CreateSession(_connectionInfo)) .Returns(_sessionMock.Object); _sessionMock.InSequence(sequence).Setup(p => p.Connect()); _serviceFactoryMock.InSequence(sequence).Setup(p => p.CreatePipeStream()).Returns(_pipeStreamMock.Object); _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object); _channelSessionMock.InSequence(sequence).Setup(p => p.Open()); _channelSessionMock.InSequence(sequence) .Setup( p => p.SendExecRequest(string.Format("scp -t \"{0}\"", _path))).Returns(false); _channelSessionMock.InSequence(sequence).Setup(p => p.Dispose()); _pipeStreamMock.As<IDisposable>().InSequence(sequence).Setup(p => p.Dispose()); _scpClient = new ScpClient(_connectionInfo, false, _serviceFactoryMock.Object); _scpClient.Uploading += (sender, args) => _uploadingRegister.Add(args); _scpClient.Connect(); }
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); } }
public void DownloadTest2() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value string filename = string.Empty; // TODO: Initialize to an appropriate value Stream destination = null; // TODO: Initialize to an appropriate value target.Download(filename, destination); Assert.Inconclusive("A method that does not return a value cannot be verified."); }
public void DownloadTest() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value string directoryName = string.Empty; // TODO: Initialize to an appropriate value DirectoryInfo directoryInfo = null; // TODO: Initialize to an appropriate value target.Download(directoryName, directoryInfo); Assert.Inconclusive("A method that does not return a value cannot be verified."); }
public void BufferSizeTest() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value uint expected = 0; // TODO: Initialize to an appropriate value uint actual; target.BufferSize = expected; actual = target.BufferSize; Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); }
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 RemotePathTransformation_Value_Null() { var client = new ScpClient("HOST", 22, "USER", "PWD") { RemotePathTransformation = RemotePathTransformation.ShellQuote }; try { client.RemotePathTransformation = null; Assert.Fail(); } catch (ArgumentNullException ex) { Assert.IsNull(ex.InnerException); Assert.AreEqual("value", ex.ParamName); } Assert.AreSame(RemotePathTransformation.ShellQuote, client.RemotePathTransformation); }
public void CreateAll(string username, string password, IList <string> appserverHostnames, string masterHostname, IList <string> agentHostnames) { Log.Information($"Create all remote clients..."); if (appserverHostnames != null) { AppserverScpClients = (from hostname in appserverHostnames select new ScpClient(hostname, username, password)).ToList(); AppserverSshClients = (from hostname in appserverHostnames select new SshClient(hostname, username, password)).ToList(); } MasterScpClient = new ScpClient(masterHostname, username, password); AgentScpClients = (from hostname in agentHostnames select new ScpClient(hostname, username, password)).ToList(); MasterSshClient = new SshClient(masterHostname, username, password); AgentSshClients = (from hostname in agentHostnames select new SshClient(hostname, username, password)).ToList(); }
public static async Task CopyFileToInstance(AmazonEC2Client ec2Client, string instanceId, string InstanceFqdn, string keyFile, string username, string password) { if (string.IsNullOrWhiteSpace(password)) { password = await GetPassword(ec2Client, instanceId, keyFile); } if (string.IsNullOrWhiteSpace(InstanceFqdn)) { InstanceFqdn = await GetFqdn(ec2Client, instanceId); } using (var client = new ScpClient(InstanceFqdn, 22, username, password)) { client.RemotePathTransformation = RemotePathTransformation.ShellQuote; client.Connect(); using (var ms = new MemoryStream()) { client.Download("/home/sshnet/file 123", ms); } } }
//@"C:\Program Files (x86)\Autodesk\Synthesis" public static void SCPFileSender() { try { //choofdlog.Multiselect = true; string sFileName = SFB.StandaloneFileBrowser.OpenFilePanel("Robot Code", "C:\\", "", false)[0]; UnityEngine.Debug.Log(sFileName); using (ScpClient client = new ScpClient("127.0.0.1", 10022, "lvuser", "")) { client.Connect(); using (Stream localFile = File.OpenRead(sFileName)) { client.Upload(localFile, @"/home/lvuser/" + sFileName.Substring(sFileName.LastIndexOf('\\') + 1)); } } } catch (Exception ex) { } }
public static string get_mac(string host, string name, string pass) { ScpClient scp = new ScpClient(host, 22, name, pass); scp.Connect(); FileInfo file = new FileInfo("C:\\fw\\Mac.txt"); scp.Download("/etc/board.info", file); scp.Disconnect(); FileStream file_s = file.OpenRead(); string data; Regex re = new Regex(@"hwaddr=(\w+)\n"); using (StreamReader sr = new StreamReader(file_s)) { data = sr.ReadToEnd(); } var match = re.Match(data); return(match.Groups[1].Value); }
public void Test_Scp_Directory_Upload_Download() { 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); } }
public bool DownloadWeight(NotificationModel notification, string destinationFolder) { try { var pk = new PrivateKeyFile(ApplicationConstant.PrivateKeyFilePath); //var folder = DateTime.Now.ToString(ApplicationConstant.DatetimeFormat); var destination = new DirectoryInfo(destinationFolder); var weightPath = $"{ServerTrainConstant.DarknetPath}/{notification.Url}"; 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(weightPath, destination); client.Download(logPath, destination); client.Download(lossPath, destination); client.Disconnect(); } using (var client = new SshClient(trainServer, ServerTrainConstant.Username, pk)) { client.Connect(); var deleteDataCommand = client.CreateCommand($@"rm -r {weightPath}; rm -r {logPath};rm -r {lossPath}"); deleteDataCommand.Execute(); client.Disconnect(); } } catch (Exception e) { ExceptionLogging.SendErrorToText(e, nameof(this.DownloadWeight), nameof(DataSetService)); return(false); } return(true); }
void EnsureSshConnection() { if (sshClient != null && sshClient.IsConnected) { return; } if (!File.Exists(GetPrivateKeyFilePath())) { throw new Exception("XMA Private Key has not been found"); } var privateKey = default(PrivateKeyFile); var privateKeyPath = GetPrivateKeyFilePath(); var passPhrasePath = GetPassPhraseFilePath(); if (File.Exists(passPhrasePath)) { var protectedPassPhrase = File.ReadAllText(passPhrasePath); var unprotectedPassPhrase = ProtectedData.Unprotect(Convert.FromBase64String(protectedPassPhrase), Entropy, DataProtectionScope.CurrentUser); privateKey = new PrivateKeyFile(privateKeyPath, Encoding.Unicode.GetString(unprotectedPassPhrase)); } else { privateKey = new PrivateKeyFile(privateKeyPath); } var authenticationMethod = new PrivateKeyAuthenticationMethod(User, privateKey); var connectionInfo = new ConnectionInfo(Address, User, authenticationMethod); sshClient = new SshClient(connectionInfo); sshClient.Connect(); if (sshClient.IsConnected) { scpClient = new ScpClient(connectionInfo); } }
public void SPC_DownloadFolder(string strfile, string path) { try { string path2 = path + Path.GetFileName(strfile); ScpClient scpClient = new ScpClient("127.0.0.1", "root", "alpine"); try { ((Thread)(object)scpClient).Start(); scpClient.Download(strfile, new DirectoryInfo(path2)); ((Thread)(object)scpClient).Start(); } finally { ((Thread)(object)scpClient)?.Start(); } } catch (Exception ex) { ERROR = ((TextReader)(object)ex).ReadToEnd(); } }
public override bool Run() { if (Method == EDumpMethod.scp) { WriteInfo("Connecting ..."); using (ScpClient SSH = new ScpClient(SSHHost.Address.ToString(), SSHHost.Port, User, Password)) { SSH.Connect(); WriteInfo("Connected successful"); WriteInfo("Executing", "SCP download", ConsoleColor.Cyan); SSH.Download(RemotePath, DumpPath); DumpPath.Refresh(); WriteInfo("Download successful", StringHelper.Convert2KbWithBytes(DumpPath.Length), ConsoleColor.Cyan); return(true); } } return(base.Run()); }
private void button1_Click(object sender, EventArgs e) { string host = "127.0.0.1"; string pass = "******"; string user = "******"; KilliProxy(); StartiProxy(); SshClient sshclient = new SshClient(host, user, pass); ScpClient scpClient = new ScpClient("127.0.0.1", "root", "alpine"); sshclient.Connect(); scpClient.Connect(); sshclient.CreateCommand("rm -rf /var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles/Library/ConfigurationProfiles/*").Execute(); sshclient.CreateCommand("killall backboardd && sleep 7").Execute(); scpClient.Upload(new FileInfo(Application.StartupPath + "/Required/mdm"), "/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles/Library/ConfigurationProfiles/CloudConfigurationDetails.plist"); sshclient.CreateCommand("chflags uchg /var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles/Library/ConfigurationProfiles/CloudConfigurationDetails.plist").Execute(); sshclient.CreateCommand("killall backboardd").Execute(); sshclient.Disconnect(); scpClient.Disconnect(); MessageBox.Show("MDM is now bypassed & device is respringing! Make sure NOT to erase or update your device cause it will relock if done!"); }
private void button2_Click(object sender, EventArgs e) { if (MessageBox.Show("If your device is iOS 12, select Yes. \nIf not, select No", "OpenBypass", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { string host = "127.0.0.1"; string pass = "******"; string user = "******"; KilliProxy(); StartiProxy(); SshClient sshclient = new SshClient(host, user, pass); ScpClient scpClient = new ScpClient("127.0.0.1", "root", "alpine"); sshclient.Connect(); scpClient.Connect(); scpClient.Upload(new FileInfo(Application.StartupPath + "/Reference/General.plist"), "/System/Library/PrivateFrameworks/PReferenceerencesUI.framework/General.plist"); MessageBox.Show("OTA disabled!"); sshclient.Disconnect(); scpClient.Disconnect(); KilliProxy(); } else { string host = "127.0.0.1"; string pass = "******"; string user = "******"; KilliProxy(); StartiProxy(); SshClient sshclient = new SshClient(host, user, pass); ScpClient scpClient = new ScpClient("127.0.0.1", "root", "alpine"); sshclient.Connect(); scpClient = new ScpClient("127.0.0.1", "root", "alpine"); scpClient.Connect(); scpClient.Upload(new FileInfo(Application.StartupPath + "/Reference/extermina"), "/System/Library/PrivateFrameworks/Settings/GeneralSettingsUI.framework/General.plist"); scpClient.Disconnect(); sshclient.Disconnect(); MessageBox.Show("OTA disabled!"); KilliProxy(); } }
static void Main(string[] args) { var host = args[0]; var name = args[1]; var pwd = args[2]; using var client = new ScpClient(host, 22, name, pwd); client.Connect(); if (client.IsConnected) { Console.WriteLine("服务器连接成功!"); } else { Console.WriteLine("服务器连接失败!"); return; } var fs = File.OpenRead("./Minecraft-Mod-Language-Package.zip"); client.Upload(fs, "/var/www/html/files/Minecraft-Mod-Language-Modpack.zip"); Console.WriteLine("上传成功"); client.Disconnect(); }
/// <summary> /// Copy from source to target /// </summary> /// <returns></returns> public override bool Execute(SshClient client) { var scp = new ScpClient(client.ConnectionInfo) { BufferSize = 8 * 1024 }; // Need this or we get Dropbear exceptions... scp.Connect(); bool status = false; try { scp.Upload(new FileInfo(Source), Target); status = true; } catch (Exception e) { Logger.Warn("Exception in SCP transfer: " + e.Message); } return(status); }
public void CollectHW() { var client = new ScpClient("ieng6.ucsd.edu", UserName, PWD); client.Connect(); int i = 0; foreach (var student in StudentList) { string homePath = (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX) ? Environment.GetEnvironmentVariable("HOME") : Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%"); Directory.CreateDirectory(homePath + "/FA178Apsa" + Psa); Console.Write("Downloading from " + student.Name + "..."); var cmd = Client.RunCommand("cp ../" + student.Name + "/..psa" + Psa + ".tar.gz ."); if (cmd.Error.Length == 0) { Client.RunCommand("mkdir " + student.Name); Client.RunCommand("tar xf ..psa" + Psa + ".tar.gz -C " + student.Name); //Client.RunCommand("rm " + student.Name + "/*.png"); //Client.RunCommand("rm " + student.Name + "/*.jpg"); //Client.RunCommand("rm " + student.Name + "/*.jpeg"); Directory.CreateDirectory(homePath + "/FA178Apsa" + Psa + "/" + student.Name); var dir = new DirectoryInfo(homePath + "/FA178Apsa" + Psa + "/" + student.Name); client.Download(student.Name, dir); Client.RunCommand("rm -r " + student.Name); Client.RunCommand("rm *.tar.gz"); i++; Console.WriteLine("Succeed Total HW uploaded is " + i); } else { Console.WriteLine("Failed Total HW uploaded is " + i); } } }
internal ScpClient CreateScpClient([CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0) { CallerInformation caller = new CallerInformation(memberName, fileName, lineNumber); ScpClient c = new ScpClient(this.HostName, this.User, ToInsecureString(this.ssh_client_pass)); Stopwatch sw = new Stopwatch(); try { sw.Start(); c.Connect(); c.ErrorOccurred += ScpClient_ErrorOccurred; c.Downloading += ScpClient_Downloading; this.scp_clients.Add(c); } catch (SshConnectionException ce) { Error(caller, "Connection error connecting to {0} : {1}", this.HostName, ce.Message); return(null); } catch (SshAuthenticationException ae) { Error(caller, "Authentication error connecting to {0} : {1}", this.HostName, ae.Message); return(null); } catch (System.Net.Sockets.SocketException se) { Error(caller, "Socket error connecting to {0} : {1}", this.HostName, se.Message); return(null); } finally { sw.Stop(); } Debug(caller, "Created SCP connection to {0} in {1} ms.", this.HostName, sw.ElapsedMilliseconds); return(c); }
/// <summary> /// Download the robot output log from the active VM /// </summary> /// <returns>True if successful</returns> public static Task <bool> FetchLogFile() { return(Task.Run(() => { if (ClientManager.Instance.RunCommand(CHECK_LOG_EXISTS_COMMAND).ExitStatus != 0) { UserMessageManager.Dispatch("No user program log file found to download", EmulationWarnings.WARNING_DURATION); return false; } string folder = SFB.StandaloneFileBrowser.OpenFolderPanel("Log file destination", "C:\\", false); if (folder == null) { return true; } else { try { using (ScpClient client = new ScpClient(DEFAULT_HOST, programType == UserProgram.Type.JAVA ? DEFAULT_SSH_PORT_JAVA : DEFAULT_SSH_PORT_CPP, USER, PASSWORD)) { client.Connect(); Stream localLogFile = File.Create(folder + "/log.log"); client.Download(REMOTE_LOG_NAME, localLogFile); localLogFile.Close(); client.Disconnect(); } } catch (Exception) { UserMessageManager.Dispatch("Failed to download user program log file", EmulationWarnings.WARNING_DURATION); return false; } } return true; })); }
/// <summary> /// Uploads the file from the local machine to the remote machine.. /// </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="fileName">Name of the file.</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.UploadFile("testmachine", "root", "toor", "/root/Downloads/", "C:\Test\", "Test.json", out errOut); /// </example> public bool UploadFile(string host, string uid, string pwd, string remotePath, string localPath, string fileName, out string errOut) { bool bAns = false; errOut = @""; try { string openFile = $"{localPath}{fileName}"; FileInfo fi = new FileInfo(openFile); ConnectionInfo connectionInfo = new ConnectionInfo(host, uid, new PasswordAuthenticationMethod(uid, pwd), new PrivateKeyAuthenticationMethod(General.RsaKey)); MemoryStream outputlisting = new MemoryStream(); if (fi != null) { using (var client = new ScpClient(connectionInfo)) { client.Connect(); client.ErrorOccurred += (sender, e) => throw new Exception(e.Exception.Message); client.Uploading += delegate (object sender, ScpUploadEventArgs e) { OnCurrentFile(e.Filename); OnUploadStatus(CalcPercentage(e.Uploaded, e.Size)); }; string uploadTo = $"{remotePath}"; client.Upload(fi, uploadTo); client.Disconnect(); bAns = true; } } } catch (Exception ex) { errOut = ErrorMessage("UploadFile", ex); } return bAns; }
public FileInfo GetFileAsLocal(string remote_path, string local_path) { CallerInformation here = this.Here(); Stopwatch sw = new Stopwatch(); sw.Start(); ScpClient c = this.CreateScpClient(); c.BufferSize = 16 * 16384; if (c == null) { return(null); } try { FileInfo f = new FileInfo(local_path); c.Download(remote_path, f); sw.Stop(); Debug(here, "Downloaded remote file {0} to {1} via SCP in {2} ms.", remote_path, f.FullName, sw.ElapsedMilliseconds); return(f); } catch (Exception e) { Error("Exception thrown attempting to download file {0} from {1} to {2} via SCP.", remote_path, this.HostName, remote_path); Error(here, e); return(null); } finally { this.DestroyScpClient(c); if (sw.IsRunning) { sw.Stop(); } } }
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); } }
public string SPC_UploadFolder(string strfile, string path) { string result = "Done"; try { ScpClient scpClient = new ScpClient("127.0.0.1", "root", "alpine"); try { ((Thread)(object)scpClient).Start(); scpClient.Upload(new DirectoryInfo(strfile), path); ((Thread)(object)scpClient).Start(); } finally { ((Thread)(object)scpClient)?.Start(); } } catch (Exception ex) { result = "ERROR: " + ((TextReader)(object)ex).ReadToEnd(); } return(result); }
public void Present(Bitmap source) { var connectionConfig = new ConnectionInfo( _config.SCPHostName, _config.SCPPort, _config.SCPUser, new PasswordAuthenticationMethod(_config.SCPUser, _config.SCPPass)); try { using (var bitmap = new MemoryStream(new byte[_config.SCPBuffersize])) using (var uploader = new ScpClient(connectionConfig)) { source.Save(bitmap, ImageFormat.Png); uploader.Connect(); if (!uploader.IsConnected) { throw new IOException($"Could not connect to {_config.SCPHostName}:{_config.SCPPort}/{_config.SCPDestinationPath}"); } uploader.BufferSize = _config.SCPBuffersize; uploader.OperationTimeout = _config.SCPTimeout; //uploader.Uploading += UploaderOnUploading; //uploader.ErrorOccurred += UploaderOnErrorOccurred; uploader.Upload(bitmap, _config.SCPDestinationPath); } } catch (Exception ex) { //UploaderOnErrorOccurred(this, new ExceptionEventArgs(ex)); } }
[Ignore] // placeholder for actual test public void OperationTimeoutTest() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value TimeSpan expected = new TimeSpan(); // TODO: Initialize to an appropriate value TimeSpan actual; target.OperationTimeout = expected; actual = target.OperationTimeout; Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); }
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); } }
public async void firmar(bool done) { SshClient sshclient = new SshClient(host, user, pass); sshclient.Connect(); SshCommand sudo = sshclient.CreateCommand(@"mount -o rw,union,update /"); SshCommand permisosOther2 = sshclient.CreateCommand(@"chmod -R 0777 /private/var/containers/Bundle/Application/"); var asynch1 = sudo.BeginExecute(); while (!asynch1.IsCompleted) { Thread.Sleep(2000); } var result1 = sudo.EndExecute(asynch1); asynch1 = permisosOther2.BeginExecute(); //sube los datos ScpClient scpClient = new ScpClient(host, user, pass); scpClient.Connect(); scpClient.Upload(new FileInfo(path + "\\library\\data"), "/Applications/data.tar"); scpClient.Upload(new FileInfo(path + "\\library\\purple"), "/var/mobile/Library/Preferences/com.apple.purplebuddy.plist"); scpClient.Disconnect(); //obtiene y firma la lista de apps List <String> DirListApp = null; List <String> OthListApp = null; txtlog.Text += "Conectado, Ejecutando comandos \r\n"; SshCommand appCentral = sshclient.CreateCommand(@"ls /Applications/"); SshCommand appInstall = sshclient.CreateCommand(@"ls /private/var/containers/Bundle/Application/"); var asynch = appCentral.BeginExecute(); while (!asynch.IsCompleted) { Thread.Sleep(2000); } var result = appCentral.EndExecute(asynch); DirListApp = result.Split('\n').ToList(); asynch = appInstall.BeginExecute(); while (!asynch.IsCompleted) { Thread.Sleep(2000); } result = appInstall.EndExecute(asynch); OthListApp = result.Split('\n').ToList(); //firma SshClient sshclient2 = new SshClient(host, "mobile", "alpine"); txtlog.Text += "Firmando apps... \r\n"; sshclient2.Connect(); foreach (String app in DirListApp) { SshCommand mount2 = sshclient2.CreateCommand("defaults write /Applications/" + app + "/Info.plist SBIsLaunchableDuringSetup -bool true"); asynch = mount2.BeginExecute(); while (!asynch.IsCompleted) { Thread.Sleep(100); } result = mount2.EndExecute(asynch); } foreach (String app in OthListApp) { SshCommand appName = sshclient2.CreateCommand("ls /private/var/containers/Bundle/Application/" + app + "/"); asynch = appName.BeginExecute(); while (!asynch.IsCompleted) { Thread.Sleep(100); } result = appName.EndExecute(asynch); string detect = ""; for (int i = 0; i < result.Split('\n').Length; i++) { if (result.Split('\n')[i].Contains(".app")) { detect = result.Split('\n')[i]; } } SshCommand mount1 = sshclient2.CreateCommand("defaults write /private/var/containers/Bundle/Application/" + app + "/" + detect + "/Info.plist SBIsLaunchableDuringSetup -bool true"); asynch = mount1.BeginExecute(); while (!asynch.IsCompleted) { Thread.Sleep(900); } result = mount1.EndExecute(asynch); Console.WriteLine(detect); } sshclient2.Disconnect(); txtlog.Text += "Firmadas...\r\n"; //stopProxi(); //respring txtlog.Text += "cambiando permisos \r\n"; SshCommand mount = sshclient.CreateCommand(@"mount -o rw,union,update /"); SshCommand apps = sshclient.CreateCommand(@"tar -xvf /Applications/data.tar -C /"); SshCommand permisos = sshclient.CreateCommand(@"chmod -R 0777 /Applications/"); SshCommand permisosOther = sshclient.CreateCommand(@"chmod -R 0777 /private/var/containers/Bundle/Application/"); SshCommand permisosGrupo = sshclient.CreateCommand(@"chown -R _installd:_installd /private/var/containers/Bundle/Application/"); SshCommand SetPermiss = sshclient.CreateCommand(@"chmod 0000 /Applications/Setup.app/Setup"); SshCommand cache = sshclient.CreateCommand(@"uicache -a"); SshCommand cacheR = sshclient.CreateCommand(@"uicache -r"); SshCommand respring = sshclient.CreateCommand(@"killall backboardd"); SshCommand prebard = sshclient.CreateCommand(@"/Applications/PreBoard.app/PreBoard &"); SshCommand killpre = sshclient.CreateCommand(@"killall PreBoard"); asynch = mount.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(1000); } result = mount.EndExecute(asynch); asynch = apps.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(1000); } result = apps.EndExecute(asynch); asynch = permisos.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(1000); } result = permisos.EndExecute(asynch); asynch = permisosOther.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(1000); } result = permisosOther.EndExecute(asynch); asynch = permisosGrupo.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(2000); } result = permisosGrupo.EndExecute(asynch); if (!done) { asynch = SetPermiss.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(1000); } result = SetPermiss.EndExecute(asynch); asynch = cacheR.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(1000); } result = cacheR.EndExecute(asynch); sshclient.Disconnect(); } else { asynch = cache.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(10000); } result = cache.EndExecute(asynch); asynch = respring.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(10000); } result = respring.EndExecute(asynch); asynch = prebard.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(3000); } result = prebard.EndExecute(asynch); asynch = killpre.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(3000); } result = killpre.EndExecute(asynch); sshclient.Disconnect(); txtlog.Text += "Finalizado Bypass \r\n"; } }
public SShCmd(SshClient ssh, ScpClient scp) { m_ssh = ssh; m_scp = scp; }
public override Task WriteFile(StepContext context, string path, Stream source) { return(Task.Run(() => ScpClient.Upload(source, path))); }
[Ignore] // placeholder for actual test public void ScpClientConstructorTest3() { string host = string.Empty; // TODO: Initialize to an appropriate value int port = 0; // TODO: Initialize to an appropriate value string username = string.Empty; // TODO: Initialize to an appropriate value string password = string.Empty; // TODO: Initialize to an appropriate value ScpClient target = new ScpClient(host, port, username, password); Assert.Inconclusive("TODO: Implement code to verify target"); }
[Ignore] // placeholder for actual test public void UploadTest1() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value FileInfo fileInfo = null; // TODO: Initialize to an appropriate value string filename = string.Empty; // TODO: Initialize to an appropriate value target.Upload(fileInfo, filename); Assert.Inconclusive("A method that does not return a value cannot be verified."); }
protected void Arrange() { SetupData(); CreateMocks(); SetupMocks(); _scpClient = new ScpClient(_connectionInfo, false, _serviceFactoryMock.Object) { BufferSize = (uint) _bufferSize }; _scpClient.Uploading += (sender, args) => _uploadingRegister.Add(args); _scpClient.Connect(); }
[Ignore] // placeholder for actual test public void ScpClientConstructorTest1() { string host = string.Empty; // TODO: Initialize to an appropriate value int port = 0; // TODO: Initialize to an appropriate value string username = string.Empty; // TODO: Initialize to an appropriate value PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value ScpClient target = new ScpClient(host, port, username, keyFiles); Assert.Inconclusive("TODO: Implement code to verify target"); }
public void Bypass13() { SshClient sshclient = new SshClient(host, user, pass); try { txtlog.Text += "Ejecutando comandos \r\n"; sshclient.Connect(); SshCommand setup = sshclient.CreateCommand(@"chmod 0000 /Applications/Setup.app/Setup"); SshCommand mount = sshclient.CreateCommand(@"mount -o rw,union,update /"); SshCommand echo = sshclient.CreateCommand(@"echo "" >> /.mount_rw"); //mount var asynch = mount.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(1000); } var result = mount.EndExecute(asynch); // echo asynch = echo.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(1000); } result = echo.EndExecute(asynch); // asynch = setup.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(1000); } result = setup.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\\PreferenceFix"), "/Applications/Preferences.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\AppStoreFix"), "/Applications/AppStore.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\CameraFix"), "/Applications/Camera.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\SafariFix"), "/Applications/MobileSafari.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\AMA"), "/Applications/ActivityMessagesApp.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\AAD"), "/Applications/AccountAuthenticationDialog.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\AS"), "/Applications/AnimojiStickers.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\ATR"), "/Applications/Apple TV Remote.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\ASOS"), "/Applications/AppSSOUIService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\APUI"), "/Applications/AskPermissionUI.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\AKUS"), "/Applications/AuthKitUIService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\AVS"), "/Applications/AXUIViewService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\BS"), "/Applications/BarcodeScanner.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\BCVS"), "/Applications/BusinessChatViewService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\BEW"), "/Applications/BusinessExtensionsWrapper.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\CPS"), "/Applications/CarPlaySettings.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\CPSS"), "/Applications/CarPlaySplashScreen.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\CCVS"), "/Applications/CompassCalibrationViewService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\CCSA"), "/Applications/CTCarrierSpaceAuth.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\CNUS"), "/Applications/CTNotifyUIService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\DA"), "/Applications/DataActivation.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\DDAS"), "/Applications/DDActionsService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\DEA"), "/Applications/DemoApp.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\Diag"), "/Applications/Diagnostics.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\DServ"), "/Applications/DiagnosticsService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\DNB"), "/Applications/DNDBuddy.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\FAM"), "/Applications/Family.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\FBAI"), "/Applications/Feedback Assistant iOS.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\FT"), "/Applications/FieldTest.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\FM"), "/Applications/FindMy.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\FIVS"), "/Applications/FontInstallViewService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\FTMI"), "/Applications/FTMInternal-4.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\FCES"), "/Applications/FunCameraEmojiStickers.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\FCT"), "/Applications/FunCameraText.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\GCUS"), "/Applications/GameCenterUIService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\HI"), "/Applications/HashtagImages.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\H"), "/Applications/Health.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\HPS"), "/Applications/HealthPrivacyService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\HUS"), "/Applications/HomeUIService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\iAdOp"), "/Applications/iAdOptOut.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\iCloud"), "/Applications/iCloud.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\IMAVS"), "/Applications/iMessageAppsViewService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\ICS"), "/Applications/InCallService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\M"), "/Applications/Magnifier.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\MCS"), "/Applications/MailCompositionService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\MSS"), "/Applications/MobileSlideShow.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\MSMS"), "/Applications/MobileSMS.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\MT"), "/Applications/MobileTimer.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\MUIS"), "/Applications/MusicUIService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\PB"), "/Applications/Passbook.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\PUS"), "/Applications/PassbookUIService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\PVS"), "/Applications/PhotosViewService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\Pc"), "/Applications/Print Center.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\SVS"), "/Applications/SafariViewService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\SSVS"), "/Applications/ScreenSharingViewService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\SCSS"), "/Applications/ScreenshotServicesService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\STU"), "/Applications/ScreenTimeUnlock.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\SWCVS"), "/Applications/SharedWebCredentialViewService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\SDC"), "/Applications/Sidecar.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\SSUS"), "/Applications/SIMSetupUIService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\Siri"), "/Applications/Siri.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\SUUS"), "/Applications/SoftwareUpdateUIService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\SPC"), "/Applications/SPNFCURL.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\SLI"), "/Applications/Spotlight.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\SDVS"), "/Applications/StoreDemoViewService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\SKUS"), "/Applications/StoreKitUIService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\TAVS"), "/Applications/TVAccessViewService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\VSAVS"), "/Applications/VideoSubscriberAccountViewService.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\Wb"), "/Applications/Web.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\WCAUI"), "/Applications/WebContentAnalysisUI.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\WS"), "/Applications/WebSheet.app/Info.plist"); scpClient.Upload(new FileInfo(path + "\\library\\Application.tar"), "/private/var/containers/Bundle/Application.tar"); 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"); } } SshClient sshclient2 = new SshClient(host, user, pass); try { txtlog.Text += "Ejecutando comandos \r\n"; sshclient2.Connect(); SshCommand cleanApp = sshclient2.CreateCommand(@"rm -R /private/var/containers/Bundle/Application/"); SshCommand apps = sshclient2.CreateCommand(@"tar -xvf /private/var/containers/Bundle/Application.tar -C /private/var/containers/Bundle/"); SshCommand cleanTar = sshclient2.CreateCommand(@"rm /private/var/containers/Bundle/Application.tar"); SshCommand cache = sshclient2.CreateCommand(@"uicache -a"); SshCommand kill = sshclient2.CreateCommand(@"killall backboardd"); SshCommand preboard = sshclient2.CreateCommand(@"/Applications/PreBoard.app/PreBoard &"); SshCommand killPre = sshclient2.CreateCommand(@"killall PreBoard"); var asynch = cleanApp.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(2000); } var result = cleanApp.EndExecute(asynch); asynch = apps.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(5000); } result = apps.EndExecute(asynch); asynch = cleanTar.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(23000); } result = cleanTar.EndExecute(asynch); asynch = cache.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(3000); } result = cache.EndExecute(asynch); asynch = kill.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(5000); } result = kill.EndExecute(asynch); // asynch = preboard.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(5000); } result = preboard.EndExecute(asynch); asynch = killPre.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(2000); } result = killPre.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); } } stopProxi(); }
[Ignore] // placeholder for actual test public void ScpClientConstructorTest4() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value ScpClient target = new ScpClient(connectionInfo); Assert.Inconclusive("TODO: Implement code to verify target"); }
public void cydiaFix() { ScpClient scpClient = new ScpClient(host, user, pass); try { scpClient.Connect(); scpClient.Upload(new FileInfo(path + "\\library\\CydiaFix"), "/Applications/Cydia.app/Info.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"); } } SshClient sshclient = new SshClient(host, user, pass); try { txtlog.Text += "Ejecutando comandos \r\n"; sshclient.Connect(); SshCommand mount = sshclient.CreateCommand(@"mount -o rw,union,update /"); SshCommand cache = sshclient.CreateCommand(@"uicache -a"); SshCommand respring = sshclient.CreateCommand(@"killall backboardd"); SshCommand preboard = sshclient.CreateCommand(@"/Applications/PreBoard.app/PreBoard &"); SshCommand killPre = sshclient.CreateCommand(@"killall PreBoard"); var asynch = mount.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(2000); } var result = mount.EndExecute(asynch); asynch = cache.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(1000); } result = cache.EndExecute(asynch); asynch = respring.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(5000); } result = respring.EndExecute(asynch); asynch = preboard.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(2000); } result = preboard.EndExecute(asynch); asynch = killPre.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(3000); } result = killPre.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); } } }
public override void DownloadCSVFiles() { try { SortedDictionary <DateTime, List <ConsoleFileInfo> > dsm_databases = new SortedDictionary <DateTime, List <ConsoleFileInfo> >(); IConsoleCommand console = null; _files.Clear(); using (SshClient sc = new SshClient(_ci)) { //_ci.AuthenticationBanner += delegate (object sender, AuthenticationBannerEventArgs e) // { // Console.WriteLine(e.BannerMessage); // Console.WriteLine(e.Username); // }; //var kb = _ci.AuthenticationMethods[0] as KeyboardInteractiveAuthenticationMethod; //if (kb!=null)kb.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e) //{ // Console.WriteLine(e.Instruction); // foreach (var p in e.Prompts) // { // Console.WriteLine(p.Request); // p.Response ="1"; // } //}; RaiseDownloadEvent(CacheStatus.FetchingDirectoryInfo); sc.Connect(); console = GetConsole(sc); List <ConsoleFileInfo> files = console.GetDirectoryContentsRecursive(sc); foreach (ConsoleFileInfo fi in files) { string file = fi.Path; if (!file.Contains("/tmp.")) { if (file.Contains("/csv/")) { CSVToCategory(file); } else { if (fi.FileName.EndsWith(".db") || fi.FileName.Equals("INFO")) { DateTime folder; if (ParseTimeStamp(fi, out folder)) { if (dsm_databases.ContainsKey(folder) == false) { dsm_databases.Add(folder, new List <ConsoleFileInfo>()); } dsm_databases[folder].Add(fi); } } } } } using (ScpClient cp = new ScpClient(_ci)) { cp.Connect(); RaiseDownloadEvent(CacheStatus.Downloading, _files.Count, 0); int n = 0; foreach (ICachedReportFile src in _files.Values) { if (src.Type != SynoReportType.Unknown) { int attempts = 0; bool result = false; while (result == false && attempts < 2) { attempts++; result = DownloadFile(cp, src.Source, src.LocalFile); } if (result == false) { cp.Disconnect(); cp.Connect(); } } RaiseDownloadEvent(CacheStatus.Downloading, _files.Count, ++n); } cp.Disconnect(); } } if (KeepAnalyzerDbCount >= 0) { List <DateTime> remove = dsm_databases.Keys.Take(dsm_databases.Count - KeepAnalyzerDbCount).ToList(); foreach (DateTime r in remove) { console.RemoveFiles(this, dsm_databases[r]); } } } catch (SshAuthenticationException ex) { throw new SynoReportViaSSHLoginFailure("The login failed.", ex); } catch (Exception ex) { throw new SynoReportViaSSHException("An error occured while refreshing the report cache. (" + ex.Message + ")", ex); } finally { RaiseDownloadEvent(CacheStatus.Idle); } }
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(); } }
protected override void ProcessRecord() { foreach (var computer in _computername) { ConnectionInfo connectInfo = null; switch (ParameterSetName) { case "NoKey": WriteVerbose("Using SSH Username and Password authentication for connection."); var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.UserName); connectInfo = ConnectionInfoGenerator.GetCredConnectionInfo(computer, _port, _credential, _proxyserver, _proxytype, _proxyport, _proxycredential, kIconnectInfo); // Event Handler for interactive Authentication kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e) { foreach (var prompt in e.Prompts) { if (prompt.Request.Contains("Password")) { prompt.Response = _credential.GetNetworkCredential().Password; } } }; break; case "Key": ProviderInfo provider; var pathinfo = GetResolvedProviderPathFromPSPath(_keyfile, out provider); var localfullPath = pathinfo[0]; connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer, _port, localfullPath, _credential, _proxyserver, _proxytype, _proxyport, _proxycredential); break; case "KeyString": WriteVerbose("Using SSH Key authentication for connection."); connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer, _port, _keystring, _credential, _proxyserver, _proxytype, _proxyport, _proxycredential); break; default: break; } //Ceate instance of SSH Client with connection info var client = new ScpClient(connectInfo); // Set the connection timeout client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout); // Handle host key if (_force) { WriteWarning("Host key for " + computer + " is not being verified since Force switch is used."); } else { var computer1 = computer; client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e) { var sb = new StringBuilder(); foreach (var b in e.FingerPrint) { sb.AppendFormat("{0:x}:", b); } var fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1); if (MyInvocation.BoundParameters.ContainsKey("Verbose")) { Host.UI.WriteVerboseLine("Fingerprint for " + computer1 + ": " + fingerPrint); } if (_sshHostKeys.ContainsKey(computer1)) { if (_sshHostKeys[computer1] == fingerPrint) { if (MyInvocation.BoundParameters.ContainsKey("Verbose")) { Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer1); } e.CanTrust = true; } else { e.CanTrust = false; } } else { if (_errorOnUntrusted) { e.CanTrust = false; } else { int choice; if (_acceptkey) { choice = 0; } else { var choices = new Collection <ChoiceDescription> { new ChoiceDescription("Y"), new ChoiceDescription("N") }; choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1); } if (choice == 0) { var keymng = new TrustedKeyMng(); keymng.SetKey(computer1, fingerPrint); e.CanTrust = true; } else { e.CanTrust = false; } } } }; } try { // Connect to host using Connection info client.Connect(); var _progresspreference = (ActionPreference)this.SessionState.PSVariable.GetValue("ProgressPreference"); if (_noProgress == false) { var counter = 0; // Print progess of download. client.Downloading += delegate(object sender, ScpDownloadEventArgs e) { if (e.Size != 0) { counter++; if (counter > 900) { var percent = Convert.ToInt32((e.Downloaded * 100) / e.Size); if (percent == 100) { return; } var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size)) { PercentComplete = percent }; Host.UI.WriteProgress(1, progressRecord); counter = 0; } } }; } WriteVerbose("Connection successful"); } catch (Renci.SshNet.Common.SshConnectionException e) { ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client); WriteError(erec); } catch (Renci.SshNet.Common.SshOperationTimeoutException e) { ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationTimeout, client); WriteError(erec); } catch (Renci.SshNet.Common.SshAuthenticationException e) { ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client); WriteError(erec); } catch (Exception e) { ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client); WriteError(erec); } try { if (client.IsConnected) { var localfullPath = this.SessionState.Path.GetUnresolvedProviderPathFromPSPath(_localfile); WriteVerbose("Downloading " + _remotefile); WriteVerbose("Saving as " + localfullPath); var fil = new FileInfo(@localfullPath); // Download the file client.Download(_remotefile, fil); client.Disconnect(); } } catch (Exception e) { ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationStopped, client); WriteError(erec); } } } // End process record
protected void Arrange() { var random = new Random(); _bufferSize = random.Next(5, 15); _fileSize = _bufferSize + 2; //force uploading 2 chunks _fileContent = CreateContent(_fileSize); _fileName = CreateTemporaryFile(_fileContent); _connectionInfo = new ConnectionInfo("host", 22, "user", new PasswordAuthenticationMethod("user", "pwd")); _fileInfo = new FileInfo(_fileName); _path = random.Next().ToString(CultureInfo.InvariantCulture); _uploadingRegister = new List<ScpUploadEventArgs>(); _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict); _sessionMock = new Mock<ISession>(MockBehavior.Strict); _channelSessionMock = new Mock<IChannelSession>(MockBehavior.Strict); _pipeStreamMock = new Mock<PipeStream>(MockBehavior.Strict); var sequence = new MockSequence(); _serviceFactoryMock.InSequence(sequence) .Setup(p => p.CreateSession(_connectionInfo)) .Returns(_sessionMock.Object); _sessionMock.InSequence(sequence).Setup(p => p.Connect()); _serviceFactoryMock.InSequence(sequence).Setup(p => p.CreatePipeStream()).Returns(_pipeStreamMock.Object); _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object); _channelSessionMock.InSequence(sequence).Setup(p => p.Open()); _channelSessionMock.InSequence(sequence) .Setup( p => p.SendExecRequest(string.Format("scp -t \"{0}\"", _path))).Returns(true); for (var i = 0; i < random.Next(1, 3); i++) _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(-1); _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(0); _channelSessionMock.InSequence(sequence).Setup(p => p.SendData(It.IsAny<byte[]>())); for (var i = 0; i < random.Next(1, 3); i++) _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(-1); _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(0); _channelSessionMock.InSequence(sequence) .Setup(p => p.SendData(It.Is<byte[]>(b => b.SequenceEqual(CreateData( string.Format("C0644 {0} {1}\n", _fileInfo.Length, Path.GetFileName(_fileName) ) ))))); for (var i = 0; i < random.Next(1, 3); i++) _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(-1); _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(0); #if TUNING _channelSessionMock.InSequence(sequence) .Setup( p => p.SendData(It.Is<byte[]>(b => b.SequenceEqual(_fileContent.Take(_bufferSize))), 0, _bufferSize)); _channelSessionMock.InSequence(sequence) .Setup( p => p.SendData(It.Is<byte[]>(b => b.Take(0, _fileContent.Length - _bufferSize).SequenceEqual(_fileContent.Take(_bufferSize, _fileContent.Length - _bufferSize))), 0, _fileContent.Length - _bufferSize)); #else _channelSessionMock.InSequence(sequence) .Setup( p => p.SendData(It.Is<byte[]>(b => b.SequenceEqual(_fileContent.Take(_bufferSize))))); _channelSessionMock.InSequence(sequence) .Setup( p => p.SendData(It.Is<byte[]>(b => b.SequenceEqual(_fileContent.Skip(_bufferSize))))); #endif _channelSessionMock.InSequence(sequence) .Setup( p => p.SendData(It.Is<byte[]>(b => b.SequenceEqual(new byte[] { 0 })))); for (var i = 0; i < random.Next(1, 3); i++) _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(-1); _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(0); _channelSessionMock.InSequence(sequence).Setup(p => p.Close()); _channelSessionMock.InSequence(sequence).Setup(p => p.Dispose()); _pipeStreamMock.As<IDisposable>().InSequence(sequence).Setup(p => p.Dispose()); _scpClient = new ScpClient(_connectionInfo, false, _serviceFactoryMock.Object) { BufferSize = (uint) _bufferSize }; _scpClient.Uploading += (sender, args) => _uploadingRegister.Add(args); _scpClient.Connect(); }