public void Test_Sftp_CreateDirectory_In_Forbidden_Directory() { if (Resources.USERNAME == "root") Assert.Fail("Must not run this test as root!"); using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); sftp.CreateDirectory("/sbin/test"); sftp.Disconnect(); } }
public void Test_Sftp_SynchronizeDirectories() { RemoveAllFiles(); using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); string uploadedFileName = Path.GetTempFileName(); string sourceDir = Path.GetDirectoryName(uploadedFileName); string destDir = "/"; string searchPattern = Path.GetFileName(uploadedFileName); var upLoadedFiles = sftp.SynchronizeDirectories(sourceDir, destDir, searchPattern); Assert.IsTrue(upLoadedFiles.Count() > 0); foreach (var file in upLoadedFiles) { Debug.WriteLine(file.FullName); } sftp.Disconnect(); } }
protected void Arrange() { _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Loose); _sessionMock = new Mock<ISession>(MockBehavior.Strict); _sftpSessionMock = new Mock<ISftpSession>(MockBehavior.Strict); _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth")); _operationTimeout = TimeSpan.FromSeconds(new Random().Next(1, 10)); _sftpClient = new SftpClient(_connectionInfo, false, _serviceFactoryMock.Object); _sftpClient.OperationTimeout = _operationTimeout; _serviceFactoryMock.Setup(p => p.CreateSession(_connectionInfo)) .Returns(_sessionMock.Object); _sessionMock.Setup(p => p.Connect()); _serviceFactoryMock.Setup(p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding)) .Returns(_sftpSessionMock.Object); _sftpSessionMock.Setup(p => p.Connect()); _sftpClient.Connect(); _sftpClient = null; _serviceFactoryMock.Setup(p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding)) .Returns((ISftpSession) null); _serviceFactoryMock.ResetCalls(); // we need to dereference all other mocks as they might otherwise hold the target alive _sessionMock = null; _connectionInfo = null; _serviceFactoryMock = null; }
protected void Arrange() { _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict); _sessionMock = new Mock<ISession>(MockBehavior.Strict); _sftpSessionMock = new Mock<ISftpSession>(MockBehavior.Strict); _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth")); _operationTimeout = TimeSpan.FromSeconds(new Random().Next(1, 10)); _sftpClient = new SftpClient(_connectionInfo, false, _serviceFactoryMock.Object); _sftpClient.OperationTimeout = _operationTimeout; 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.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding)) .Returns(_sftpSessionMock.Object); _sftpSessionMock.InSequence(sequence).Setup(p => p.Connect()); _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); _sftpSessionMock.InSequence(sequence).Setup(p => p.Disconnect()); _sftpSessionMock.InSequence(sequence).Setup(p => p.Dispose()); _sessionMock.InSequence(sequence).Setup(p => p.Disconnect()); _sessionMock.InSequence(sequence).Setup(p => p.Dispose()); _sftpClient.Connect(); _sftpClient.Disconnect(); }
public void Test_KeyboardInteractiveConnectionInfo() { var host = Resources.HOST; var username = Resources.USERNAME; var password = Resources.PASSWORD; #region Example KeyboardInteractiveConnectionInfo AuthenticationPrompt var connectionInfo = new KeyboardInteractiveConnectionInfo(host, username); connectionInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e) { System.Console.WriteLine(e.Instruction); foreach (var prompt in e.Prompts) { Console.WriteLine(prompt.Request); prompt.Response = Console.ReadLine(); } }; using (var client = new SftpClient(connectionInfo)) { client.Connect(); // Do something here client.Disconnect(); } #endregion Assert.AreEqual(connectionInfo.Host, Resources.HOST); Assert.AreEqual(connectionInfo.Username, Resources.USERNAME); }
public void Test_Sftp_CreateDirectory_Without_Connecting() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.CreateDirectory("test"); } }
public void Test_Sftp_DeleteFile_Null() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.DeleteFile(null); } }
public void Test_Sftp_SftpFile_MoveTo() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); string uploadedFileName = Path.GetTempFileName(); string remoteFileName = Path.GetRandomFileName(); string newFileName = Path.GetRandomFileName(); this.CreateTestFile(uploadedFileName, 1); using (var file = File.OpenRead(uploadedFileName)) { sftp.UploadFile(file, remoteFileName); } var sftpFile = sftp.Get(remoteFileName); sftpFile.MoveTo(newFileName); Assert.AreEqual(newFileName, sftpFile.Name); sftp.Disconnect(); } }
public void Test_Sftp_Rename_File() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); string uploadedFileName = Path.GetTempFileName(); string remoteFileName1 = Path.GetRandomFileName(); string remoteFileName2 = Path.GetRandomFileName(); this.CreateTestFile(uploadedFileName, 1); using (var file = File.OpenRead(uploadedFileName)) { sftp.UploadFile(file, remoteFileName1); } sftp.RenameFile(remoteFileName1, remoteFileName2); File.Delete(uploadedFileName); sftp.Disconnect(); } RemoveAllFiles(); }
public void Test_Sftp_ChangeDirectory_Subfolder_With_Slash_Dont_Exists() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); sftp.ChangeDirectory("/asdasd/sssddds/"); } }
public void Test_Sftp_ChangeDirectory_Root_Dont_Exists() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); sftp.ChangeDirectory("/asdasd"); } }
[Ignore] // placeholder for actual test public void SftpClientConstructorTest2() { string host = string.Empty; // 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 SftpClient target = new SftpClient(host, username, password); Assert.Inconclusive("TODO: Implement code to verify target"); }
[Ignore] // placeholder for actual test public void SftpClientConstructorTest() { string host = string.Empty; // 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 SftpClient target = new SftpClient(host, username, keyFiles); Assert.Inconclusive("TODO: Implement code to verify target"); }
public void Test_Sftp_ChangeDirectory_Which_Exists() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); sftp.ChangeDirectory("/usr"); Assert.AreEqual("/usr", sftp.WorkingDirectory); } }
public void AppendAllTextTest() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value string path = string.Empty; // TODO: Initialize to an appropriate value string contents = string.Empty; // TODO: Initialize to an appropriate value target.AppendAllText(path, contents); Assert.Inconclusive("A method that does not return a value cannot be verified."); }
public void Test_Get_Invalid_Directory() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); sftp.Get("/xyz"); } }
public void Test_Sftp_BeginUploadFile_StreamIsNull() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); sftp.BeginUploadFile(null, "aaaaa", null, null); sftp.Disconnect(); } }
public void Test_Sftp_BeginUploadFile_FileNameIsWhiteSpace() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); sftp.BeginUploadFile(new MemoryStream(), " ", null, null); sftp.Disconnect(); } }
public void Test_Sftp_Call_EndListDirectory_Twice() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); var ar = sftp.BeginListDirectory("/", null, null); var result = sftp.EndListDirectory(ar); var result1 = sftp.EndListDirectory(ar); } }
public void AppendAllLinesTest1() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value string path = string.Empty; // TODO: Initialize to an appropriate value IEnumerable<string> contents = null; // TODO: Initialize to an appropriate value Encoding encoding = null; // TODO: Initialize to an appropriate value target.AppendAllLines(path, contents, encoding); Assert.Inconclusive("A method that does not return a value cannot be verified."); }
public void Test_Sftp_ListDirectory_Without_Connecting() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { var files = sftp.ListDirectory("."); foreach (var file in files) { Debug.WriteLine(file.FullName); } } }
public void Test_Sftp_ChangeDirectory_Null() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); sftp.ChangeDirectory(null); sftp.Disconnect(); } }
public void Test_Get_File_Null() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); var file = sftp.Get(null); sftp.Disconnect(); } }
public void Test_Sftp_CreateDirectory_In_Current_Location() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); sftp.CreateDirectory("test"); sftp.Disconnect(); } }
public void Test_Sftp_RenameFile_Null() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); sftp.RenameFile(null, null); sftp.Disconnect(); } }
public void Test_Sftp_CreateDirectory_Invalid_Path() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); sftp.CreateDirectory("/abcdefg/abcefg"); sftp.Disconnect(); } }
public void Test_Sftp_DeleteDirectory_Which_Doesnt_Exists() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); sftp.DeleteDirectory("abcdef"); sftp.Disconnect(); } }
public void Test_Get_Root_Directory() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); var directory = sftp.Get("/"); Assert.AreEqual("/", directory.FullName); Assert.IsTrue(directory.IsDirectory); Assert.IsFalse(directory.IsRegularFile); } }
public void Test_Sftp_EndUploadFile_Invalid_Async_Handle() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); var async1 = sftp.BeginListDirectory("/", null, null); var filename = Path.GetTempFileName(); this.CreateTestFile(filename, 100); var async2 = sftp.BeginUploadFile(File.OpenRead(filename), "test", null, null); sftp.EndUploadFile(async1); } }
public void Test_Sftp_CreateDirectory_Already_Exists() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); sftp.CreateDirectory("test"); sftp.CreateDirectory("test"); sftp.Disconnect(); } }
public bool Connect(string server = null, string user = null, string privateKeyPath = null, string privateKeyPassphrase = null) { string _stage = ""; #if DEBUG pDebug = true; #else pDebug = false; #endif try { // _stage = "Checkings"; if (pSFtp != null && pSFtp.IsConnected) { throw new Exception($"Already connected to {pSFtp.ConnectionInfo.Host}."); } // Override current values with the parameter values if (server != null) { Server = server; } if (user != null) { User = user; } if (privateKeyPath != null) { PrivateKeyPath = privateKeyPath; } if (privateKeyPassphrase != null) { PrivateKeyPassphrase = privateKeyPassphrase; } // if (Server == "") { throw new Exception("Server is mandatory."); } if (User == "") { throw new Exception("User is mandatory."); } if (PrivateKeyPath == "") { throw new Exception("Private Key Path is mandatory."); } if (PrivateKeyPassphrase == "") { throw new Exception("Private Key Passphrase is mandatory."); } // _stage = "Preparing private key"; PrivateKeyFile _keyFile = new PrivateKeyFile(PrivateKeyPath, PrivateKeyPassphrase); var _keyFiles = new[] { _keyFile }; var methods = new List <AuthenticationMethod>(); methods.Add(new PrivateKeyAuthenticationMethod(User, _keyFiles)); // _stage = "Preparing connection"; ConnectionInfo _con = new ConnectionInfo(Server, 22, User, methods.ToArray()); _con.Encoding = System.Text.Encoding.GetEncoding("UTF-8"); pSFtp = new SftpClient(_con); // _stage = "Connecting"; pSFtp.Connect(); _con.Encoding = System.Text.Encoding.GetEncoding("UTF-8"); //pSftp.BufferSize = 4 * 1024; } catch (Exception ex) { throw new Exception($"[Connect#{_stage}] {ex.Message}"); } return(true); }
public void Test_Sftp_Change_Directory() { using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester"); sftp.CreateDirectory("test1"); sftp.ChangeDirectory("test1"); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1"); sftp.CreateDirectory("test1_1"); sftp.CreateDirectory("test1_2"); sftp.CreateDirectory("test1_3"); var files = sftp.ListDirectory("."); Assert.IsTrue(files.First().FullName.StartsWith(string.Format("{0}", sftp.WorkingDirectory))); sftp.ChangeDirectory("test1_1"); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1"); sftp.ChangeDirectory("../test1_2"); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_2"); sftp.ChangeDirectory(".."); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1"); sftp.ChangeDirectory(".."); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester"); files = sftp.ListDirectory("test1/test1_1"); Assert.IsTrue(files.First().FullName.StartsWith(string.Format("{0}/test1/test1_1", sftp.WorkingDirectory))); sftp.ChangeDirectory("test1/test1_1"); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1"); sftp.ChangeDirectory("/home/tester/test1/test1_1"); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_1"); sftp.ChangeDirectory("/home/tester/test1/test1_1/../test1_2"); Assert.AreEqual(sftp.WorkingDirectory, "/home/tester/test1/test1_2"); sftp.ChangeDirectory("../../"); sftp.DeleteDirectory("test1/test1_1"); sftp.DeleteDirectory("test1/test1_2"); sftp.DeleteDirectory("test1/test1_3"); sftp.DeleteDirectory("test1"); sftp.Disconnect(); } }
// Implementation Note: // -------------------- // The following PDF documents are handy resources for learning about the // XE command line tool. // // https://docs.citrix.com/content/dam/docs/en-us/xenserver/current-release/downloads/xenserver-vm-users-guide.pdf // https://docs.citrix.com/content/dam/docs/en-us/xenserver/xenserver-7-0/downloads/xenserver-7-0-management-api-guide.pdf /// <summary> /// Constructor. Note that you should dispose the instance when you're finished with it. /// </summary> /// <param name="addressOrFQDN">The target XenServer IP address or FQDN.</param> /// <param name="username">The user name.</param> /// <param name="password">The password.</param> /// <param name="name">Optionally specifies the XenServer name.</param> /// <param name="logFolder"> /// The folder where log files are to be written, otherwise or <c>null</c> or /// empty if logging is disabled. /// </param> public XenClient(string addressOrFQDN, string username, string password, string name = null, string logFolder = null) { Covenant.Requires <ArgumentNullException>(!string.IsNullOrEmpty(username), nameof(username)); Covenant.Requires <ArgumentNullException>(password != null, nameof(password)); string platformSubfolder; if (NeonHelper.IsWindows) { platformSubfolder = "win"; } else { throw new NotImplementedException($"[{nameof(XenClient)}] is currently only supported on Windows: https://github.com/nforgeio/neonKUBE/issues/113"); } if (!NetHelper.TryParseIPv4Address(addressOrFQDN, out var address)) { try { var hostEntry = Dns.GetHostEntry(addressOrFQDN); if (hostEntry.AddressList.Length == 0) { throw new XenException($"[{addressOrFQDN}] is not a valid IP address or fully qualified domain name of a XenServer host."); } address = hostEntry.AddressList.First(); } catch { throw new XenException($"[{addressOrFQDN}] DNS lookup failed."); } } this.logWriter = (TextWriter)null; if (!string.IsNullOrEmpty(logFolder)) { Directory.CreateDirectory(logFolder); this.logWriter = new StreamWriter(new FileStream(Path.Combine(logFolder, $"XENSERVER-{addressOrFQDN}.log"), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)); } this.Address = addressOrFQDN; this.username = username; this.password = password; this.Name = name ?? $"XENSERVER-{addressOrFQDN}"; this.xePath = Path.Combine(NeonHelper.GetBaseDirectory(), "assets-Neon.XenServer", platformSubfolder, "xe.exe"); this.xeFolder = Path.GetDirectoryName(xePath); // Connect via SFTP. this.sftpClient = new SftpClient(addressOrFQDN, username, password); this.sftpClient.Connect(); // Initialize the operation classes. this.Repository = new RepositoryOperations(this); this.Template = new TemplateOperations(this); this.Machine = new MachineOperations(this); }
public Dotnet(SocketIO client) { this.client = client; client.On("_visualizedependency", repo => { Task.Run(async() => { GithubRepository githubRepository = JsonConvert.DeserializeObject <GithubRepository>(repo.Text); if (githubRepository != null) { IServer _SServer = new SServer(new DbContext()); Console.WriteLine($"{githubRepository.full_name} Proje Bağımlılıkları Görüntüleme İşlemi Başladı."); Server server = _SServer.GetRandomServer(); if (server != null) { Console.WriteLine($"{githubRepository.full_name} Projesi {server.server_name} Sunucusunda İşlenecek!"); SshClient sshClient = null; if (Debugger.IsAttached) { sshClient = new SshClient(server.local_ip, server.local_port, "root", ""); } else { sshClient = new SshClient(server.remote_ip, server.remote_port, "root", ""); } using (sshClient) { try { sshClient.Connect(); SshCommand lsCommand = sshClient.CreateCommand("ls"); using (lsCommand) { lsCommand.Execute(); string message = lsCommand.Result; string[] bufferArr = message.Split('\n'); List <string> directories = new List <string>(bufferArr); directories.RemoveAll(x => String.IsNullOrEmpty(x)); if (directories.Contains(githubRepository.name)) { Console.WriteLine($"{githubRepository.full_name} {server.server_name} Sunucusunda Bulundu ve Silindi!"); SshCommand rmCommand = sshClient.CreateCommand($"rm -r {githubRepository.name}"); using (rmCommand) { rmCommand.Execute(); } } } SshCommand cloneCommand = sshClient.CreateCommand($"git clone {githubRepository.clone_url} && echo repository cloned"); using (cloneCommand) { cloneCommand.BeginExecute(); while (true) { Stream commandStream = cloneCommand.OutputStream; byte[] streamArr = new byte[commandStream.Length]; commandStream.Read(streamArr, 0, (int)commandStream.Length); string message = Encoding.ASCII.GetString(streamArr); if (message.Contains("repository cloned")) { Console.WriteLine($"{githubRepository.full_name} Projesi {server.server_name} Sunucusuna Başarıyla İndirildi!"); break; } Thread.Sleep(2000); } } SshCommand searchCommand = sshClient.CreateCommand($"find /root/{githubRepository.name}/ -name '*.csproj'"); using (searchCommand) { searchCommand.Execute(); string searchCommandResult = searchCommand.Result; string[] bufferArr = searchCommandResult.Split('\n'); List <string> csprojFiles = new List <string>(bufferArr); csprojFiles.RemoveAll(x => String.IsNullOrEmpty(x)); if (csprojFiles.Count > 0) { Console.WriteLine($"{githubRepository.full_name} Projesine Ait {csprojFiles.Count} Adet CSPROJ Dosyası Bulundu!"); SftpClient sftp = null; if (Debugger.IsAttached) { sftp = new SftpClient(server.local_ip, server.local_port, "root", ""); } else { sftp = new SftpClient(server.remote_ip, server.remote_port, "root", ""); } using (sftp) { sftp.Connect(); SocketEntity socketEntity = new SocketEntity(); foreach (string csprojfile in csprojFiles) { string[] csprojArr = csprojfile.Split('/'); string projectName = (csprojArr[csprojArr.Length - 1]).Replace(".csproj", ""); string fileName = Guid.NewGuid().ToString() + ".csproj"; string path = Directory.GetCurrentDirectory() + $"/{fileName}"; using (Stream stream = File.Create(path)) { sftp.DownloadFile(csprojfile, stream); } if (File.Exists(path)) { string csprojContent = File.ReadAllText(path); File.Delete(path); Project project = null; using (var stringReader = new System.IO.StringReader(csprojContent)) { var serializer = new XmlSerializer(typeof(Project)); project = serializer.Deserialize(stringReader) as Project; } if (project != null) { SocketEntity.Project socketProject = new SocketEntity.Project(); socketProject.name = projectName; socketProject.sdk = project.Sdk; foreach (ItemGroup itemGroup in project.ItemGroup) { if (itemGroup.PackageReference.Count > 0) { List <SocketEntity.Reference> references = itemGroup.PackageReference.Select(x => new SocketEntity.Reference { include = x.Include, includeType = (int)enumIncludeType.package, version = x.Version }).ToList(); socketProject.references.AddRange(references); } if (itemGroup.ProjectReference.Count > 0) { foreach (ProjectReference projectReference in itemGroup.ProjectReference) { string include = projectReference.Include; string[] includeArr = include.Split('\\'); include = (includeArr[includeArr.Length - 1]).Replace(".csproj", ""); socketProject.references.Add(new SocketEntity.Reference { include = include, includeType = (int)enumIncludeType.project, version = "" }); } } } foreach (PropertyGroup propertyGroup in project.PropertyGroup) { if (!String.IsNullOrEmpty(propertyGroup.TargetFramework)) { socketProject.targetFramework = propertyGroup.TargetFramework; } if (!String.IsNullOrEmpty(socketProject.targetFramework)) { break; } } socketEntity.projects.Add(socketProject); } else { Console.WriteLine($"{githubRepository.full_name} CSPROJ Dosyası Okunamadı!"); return; } } else { Console.WriteLine($"{githubRepository.full_name} CSPROJ Dosyası İndirilemedi!"); return; } } Console.WriteLine($"{githubRepository.full_name} Projesi Başarıyla İşlendi!"); client.EmitAsync("showDependency", githubRepository, socketEntity).Wait(); } } else { Console.WriteLine($"{githubRepository.full_name} Reposuna Ait Bir CSPROJ Dosyası Bulunamadı!"); return; } } } catch (Exception ex) { Console.WriteLine($"{ex.Message}"); } } } else { Console.WriteLine("Aktif Bir Sunucu Bulunamadı!"); return; } } else { Console.WriteLine("Hatalı Bir Veri Geldi!"); return; } }); }); }
string GetLog(string no, string fileName) { log.Info("GetLog " + no); status = SerialStatus.Reading; logfile = Settings.Instance.LogDir + Path.DirectorySeparatorChar + MakeValidFileName(fileName) + ".bin"; // make log dir Directory.CreateDirectory(Path.GetDirectoryName(logfile)); log.Info("about to write: " + logfile); // save memorystream to file SftpClient client = new SftpClient(_connectionInfo); client.Connect(); using (var logstream = File.Open(logfile, FileMode.Create, FileAccess.Write)) { client.DownloadFile(no, logstream, downloadCallback); } client.Disconnect(); log.Info("about to convertbin: " + logfile); // create ascii log BinaryLog.ConvertBin(logfile, logfile + ".log"); //update the new filename logfile = logfile + ".log"; // rename file if needed log.Info("about to GetFirstGpsTime: " + logfile); // get gps time of assci log DateTime logtime = new DFLog().GetFirstGpsTime(logfile); // rename log is we have a valid gps time if (logtime != DateTime.MinValue) { string newlogfilename = Settings.Instance.LogDir + Path.DirectorySeparatorChar + logtime.ToString("yyyy-MM-dd HH-mm-ss") + ".log"; try { File.Move(logfile, newlogfilename); // rename bin as well File.Move(logfile.Replace(".log", ""), newlogfilename.Replace(".log", ".bin")); logfile = newlogfilename; } catch { CustomMessageBox.Show(Strings.ErrorRenameFile + " " + logfile + "\nto " + newlogfilename, Strings.ERROR); } } MainV2.comPort.Progress -= comPort_Progress; return(logfile); }
private void btnProcess_Click(object sender, EventArgs e) { try { if (MessageBox.Show("This will update the DHCP server assignments and will restart the service.\n Are you sure? ", "Info", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) { string _serverDHCP = txtServerName.Text; string _tmpFile = System.IO.Path.GetTempPath() + cboCOD3.Text + "_NET.conf"; string _configFile = ""; //create the temp File var _RSD = new DynamicRS("Select * from vDHCPConfig where COD3='" + cboCOD3.Text + "'", Values.gDatos); _RSD.Open(); string _group = ""; while (!_RSD.EOF) { if (_RSD["Group"].ToString() != _group) { if (_group != "") { _configFile += "\t}\n"; } _group = _RSD["Group"].ToString(); _configFile += "# " + _group + '\n' + "group " + _group + "{" + '\n'; } _configFile += "\t# " + _RSD["Comment"].ToString() + '\n'; _configFile += "\thost " + _RSD["Host"].ToString() + " {" + '\n'; _configFile += "\t\thardware ethernet " + _RSD["MAC"].ToString() + ";" + '\n'; _configFile += "\t\tfixed-address " + _RSD["IP"].ToString() + ";" + '\n'; _configFile += "\t\t}\n"; _RSD.MoveNext(); } _configFile += "\t}\n"; _RSD.Close(); File.WriteAllText(_tmpFile, _configFile); lblMsg.Text = "File created OK."; //move the file to the server using (var client = new SftpClient(_serverDHCP, txtUser.Text, txtPassword.Text)) { lblMsg.Text = "Connecting the server."; client.Connect(); lblMsg.Text = "Server Connected!"; client.ChangeDirectory("/etc/dhcp/"); using (var fileStream = new FileStream(_tmpFile, FileMode.Open)) { client.BufferSize = 4 * 1024; // bypass Payload error large files client.UploadFile(fileStream, Path.GetFileName(_tmpFile)); } lblMsg.Text = "File updated!"; client.Disconnect(); } //restart the dhcp service using (var client = new SshClient(_serverDHCP, txtUser.Text, txtPassword.Text)) { client.Connect(); client.RunCommand("service isc-dhcp-server restart"); lblMsg.Text = "DHCP Service restarted!"; client.Disconnect(); } MessageBox.Show("The process has finished correctly.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public async static Task <bool> UploadFiles(Boolean UploadPrompt = true, Boolean AllLogs = true) { Global global = FormsApp.config.Global; // Path where the file should be saved once downloaded (locally) string path = (AllLogs) ? Mobile.LogPath : Mobile.LogUserPath; // Only upload if there are files available List <FileInfo> filesToUpload = LogFilesToUpload(path); var upload = false; if (filesToUpload.Count > 0) { upload = true; } if (UploadPrompt && filesToUpload.Count > 0) { upload = await Application.Current.MainPage.DisplayAlert( "Pending log files", "Do you want to Upload them?", "Ok", "Cancel"); } // else upload = false; if (!upload) { return(false); } // The FTP credentiales are not present in Global.xml if (!global.IsFtpUploadSet) { await Errors.ShowAlert(new FtpCredentialsMissingException()); return(false); } // Has the devices internet connection if (!Mobile.IsNetAvailable()) { await Errors.ShowAlert(new NoInternetException()); return(false); } // Cancel action bool cancelled = false; System.Action OnCancel = () => { cancelled = true; }; TaskCompletionSource <bool> tcs = new TaskCompletionSource <bool> (); Device.BeginInvokeOnMainThread(async() => { // Progress bar using (Acr.UserDialogs.IProgressDialog progress = UserDialogs.Instance.Progress("Uploading", OnCancel, "Cancel")) { // Is necessary for appear the progress bar right now await Task.Delay(10); NumFilesUploaded = 0; SftpClient sftp = null; try { string remotePath = global.ftpRemotePath; using (sftp = new SftpClient(global.ftpRemoteHost, 22, global.ftpUserName, global.ftpPassword)) { sftp.Connect(); // If not exist create the remote path from global.xml if (!sftp.Exists(remotePath)) { sftp.CreateDirectory(remotePath); } using (MD5 md5Hash = MD5.Create()) { byte[] md5Local; byte[] md5Remote; foreach (FileInfo file in filesToUpload) { if (cancelled) { throw new Exception(); } // Is necessary for update the progress bar await Task.Delay(10); // Upload local file to the FTP server using (FileStream fileStream = new FileStream(file.FullName, FileMode.Open)) { // Folder path remotePath = Path.Combine(global.ftpRemotePath, file.Directory.Name); // Logs + User folder if (!sftp.Exists(remotePath)) { sftp.CreateDirectory(remotePath); } // File path string sTick = DateTime.Now.Ticks.ToString(); string sName = file.Name.Substring(0, 10) + "-" + sTick + "Log.xml"; remotePath = Path.Combine(remotePath, sName); sftp.UploadFile(fileStream, remotePath, null); } // Compare local and remote files using (StreamReader stream = new StreamReader(file.FullName)) md5Local = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(stream.ReadToEnd())); md5Remote = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(sftp.ReadAllText(remotePath))); // If both files are equal, move local file to backup folder if (Enumerable.SequenceEqual(md5Local, md5Remote)) { // Only create backup file ( "moving" log to backup folder ) in interactive mode if (!Data.Get.IsFromScripting) { string url_to_copy = Mobile.LogUserBackupPath;// Path.Combine ( file.Directory.FullName, Mobile.PATH_BACKUP ); if (!Directory.Exists(url_to_copy)) { Directory.CreateDirectory(url_to_copy); } File.Copy(file.FullName, Path.Combine(url_to_copy, file.Name), true); } File.Delete(file.FullName); NumFilesUploaded += 1; progress.PercentComplete = ( int )(NumFilesUploaded * 100 / filesToUpload.Count); Utils.Print("- " + file.Directory.Name + " uploaded"); } } } sftp.Disconnect(); } } catch (Exception e) { // Catch all exceptions and then always show the number of // files uploaded using the exception FtpUpdateLogsException } finally { if (sftp != null) { sftp.Dispose(); } sftp = null; // Is necessary for appear the progress full ( 100% ) await Task.Delay(10); tcs.SetResult(NumFilesUploaded == filesToUpload.Count); } } }); bool result = await tcs.Task; // Wait for upload completion // Finish ok if all files have been uploaded if (result) { return(true); } if (!cancelled) { await Errors.ShowAlert(new FtpUpdateLogsException ( NumFilesUploaded + "/" + filesToUpload.Count )); } else { await PageLinker.ShowAlert("Uploading canceled", "Only uploaded " + NumFilesUploaded + " / " + filesToUpload.Count + " log files"); } return(false); }
/// <summary> /// 构造 /// </summary> /// <param name="ip">IP</param> /// <param name="port">端口</param> /// <param name="user">用户名</param> /// <param name="pwd">密码</param> public SFTPHelper(string ip, string port, string user, string pwd) { sftp = new SftpClient(ip, Int32.Parse(port), user, pwd); Connect(); }
public static async void UploadImage(bool showCursor, Size curSize, Point curPos, Point TopLeft, Point BottomRight, string extension) { int longRunningTask = await LongRunningOperationAsync(); Size pictureSize = new Size(BottomRight.X - TopLeft.X, BottomRight.Y - TopLeft.Y); using (Bitmap bitmap = new Bitmap(pictureSize.Width, pictureSize.Height)) { using (Graphics g = Graphics.FromImage(bitmap)) { g.CopyFromScreen(TopLeft, Point.Empty, pictureSize); if (showCursor) { Rectangle cursorBounds = new Rectangle(curPos, curSize); Cursors.Default.Draw(g, cursorBounds); } } MemoryStream ms = new MemoryStream(); switch (extension) { case ".bmp": bitmap.Save(ms, ImageFormat.Bmp); break; case ".jpg": bitmap.Save(ms, jpgEncoder, myEncoderParameters); break; case ".gif": bitmap.Save(ms, ImageFormat.Gif); break; case ".tiff": bitmap.Save(ms, ImageFormat.Tiff); break; case ".png": bitmap.Save(ms, ImageFormat.Png); break; default: bitmap.Save(ms, ImageFormat.Jpeg); break; } bitmap.Dispose(); using (SftpClient client = new SftpClient(host, port, username, password)) { UploadUtils.UploadType type = UploadUtils.UploadType.IMAGE; client.Connect(); client.ChangeDirectory(type.getDestination()); client.BufferSize = 2 * 1024; string name = NameUtils.RandomString(8) + extension; while (UploadUtils.Instance.checkFileExists(client, name, type)) { name = NameUtils.RandomString(8) + extension; } using (var tempPath = new TempFile(@System.IO.Path.GetTempPath() + name)) { using (var fileStream = new FileStream(tempPath.Path, FileMode.Create)) { ms.Seek(0, SeekOrigin.Begin); ms.CopyTo(fileStream); } UploadUtils.Instance.UploadFile(client, tempPath.Path, name, type); } } } }
///////////////////////////////////////////////////////// // 概要:ssh接続処理 // はまみ:2020/02/20 ///////////////////////////////////////////////////////// static public Boolean Connect(string strHostName, string strLoginId, string strPassword, ref string strResult) { Boolean bRet = true; try { // 接続情報 ConnectionInfo ConnNfo = new ConnectionInfo(strHostName, 22, strLoginId, new PasswordAuthenticationMethod(strLoginId, strPassword)); // SSHクライアント生成 m_sshClient = new SshClient(ConnNfo); m_sshClient.ConnectionInfo.Timeout = new TimeSpan(0, 0, 5); // SSH接続 m_sshClient.Connect(); // SSH接続成功 if (m_sshClient.IsConnected) { using (var client = new SftpClient(ConnNfo)) { //接続してアップロードディレクトリに移動 client.Connect(); client.ChangeDirectory("opensmile"); string fileName = (@"C:\Users\kikuc\Desktop\gokon-master-2018\Assets\WAV\result.wav"); Debug.Log(fileName); using (var fs = System.IO.File.OpenRead(fileName)) { //ファイルのアップロード(trueで上書き) client.UploadFile(fs, "result.wav", true); } //接続してダウンロードディレクトリに移動 m_shellStream = m_sshClient.CreateShellStream("", 80, 40, 80, 40, 1024); StreamReader streamReader = new StreamReader(m_shellStream, Encoding.GetEncoding("shift_jis")); StreamWriter streamWriter = new StreamWriter(m_shellStream, Encoding.GetEncoding("shift_jis")); streamWriter.AutoFlush = true; //Thread.Sleep(2000); var cmd = "sh /home/yutaka/opensmile/opensmile.sh"; streamWriter.WriteLine(cmd); SshCommand sc = m_sshClient.CreateCommand(cmd); sc.Execute(); string answer = sc.Result; f_answer = answer; Debug.Log("1:" + answer); //var result = streamReader.ReadToEnd(); ResultData.result = answer; //Debug.Log("2:"+result); client.Disconnect(); //client.Connect(); //client.ChangeDirectory("opensmile"); //using (var fs = System.IO.File.OpenWrite("text.txt")) //{ //ファイルのダウンロード //client.DownloadFile(@"C:\Users\kikuc\Desktop\gokon-master-2018\Assets\WAV\text.txt", fs); //} //client.Disconnect(); } // コマンド実行 m_shellStream.Dispose(); m_sshClient.Disconnect(); m_sshClient.Dispose(); //別手法 } } catch (Exception ex) { bRet = false; strResult = ex.ToString(); } return(bRet); }
private void upload_Click(object sender, EventArgs e) { saveConfig(); string host, username, password, fixedOut = ""; int port = -1; try { host = hostName.Text.Split('@')[1].Split(':')[0]; try { port = int.Parse(hostName.Text.Split('@')[1].Split(':')[1]); } catch (Exception) { port = 22; } username = hostName.Text.Split('@')[0]; password = userPass.Text; fixedOut = outputDir.Text.EndsWith("/") ? outputDir.Text : outputDir.Text + "/"; } catch (Exception) { MessageBox.Show("Invalid argument(s)."); return; } bool fail = false; var coninf = new ConnectionInfo(host, port, username, new PasswordAuthenticationMethod(username, userPass.Text), new PrivateKeyAuthenticationMethod(username, new PrivateKeyFile(keyPath.Text))); using (var client = new SftpClient(coninf)) { try { client.Connect(); if (uploadFile.Checked) { fixedOut += Path.GetFileName(sourcePath.Text); FileStream fs = File.OpenRead(sourcePath.Text); client.UploadFile(fs, fixedOut); } else { foreach (string file in Directory.EnumerateFiles(sourcePath.Text, "*.*", SearchOption.AllDirectories)) { var separator = unixPath.Checked ? '/' : '\\'; var revseparator = unixPath.Checked ? '\\' : '/'; var formattedpath = fixedOut + (Path.GetFileName(sourcePath.Text) + "/" + file.ReplaceFirst(sourcePath.Text.EndsWith("\\") ? sourcePath.Text : sourcePath.Text + "\\", "")); formattedpath = formattedpath.Replace(revseparator, separator); FileStream fs = File.OpenRead(file); var splitpath = new List <string>(formattedpath.Split(separator)); splitpath.RemoveAt(splitpath.Count - 1); var dirname = string.Join(separator.ToString(), splitpath.ToArray()); Debug.WriteLine(formattedpath); Debug.WriteLine(dirname); for (int i = 1; i < splitpath.Count; i++) { string check = string.Join(separator.ToString(), splitpath.Take(i + 1).ToArray()); Debug.WriteLine(check); if (!client.Exists(check)) { client.CreateDirectory(check); } } client.UploadFile(fs, formattedpath); } } client.Disconnect(); } catch (Exception err) { MessageBox.Show("SFTP error: " + err.Message); fail = true; } finally { client.Dispose(); } } if (!fail) { MessageBox.Show("File upload was successful!"); } }
public FileProvider(ConnectionInfo conInfo, DirectoryInfo virtualizationDir) { ConnectionInfo = conInfo; VirtualizationDirectory = virtualizationDir; SftpClient = new SftpClient(ConnectionInfo); }
public void disConnect() { client.Disconnect(); client.Dispose(); client = null; }
protected override async Task Execute(IServiceProvider serviceProvider, ImportProductsProperties props, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(props.ConnectionString)) { throw new Exception("ConnectionString является обязательным параметром"); } if (string.IsNullOrEmpty(props.Folder)) { props.Folder = "/"; } if (string.IsNullOrEmpty(props.FileNamePattern)) { props.FileNamePattern = @"^.*MATMAS.*\.xml$"; } if (string.IsNullOrEmpty(props.ViewHours)) { props.ViewHours = "24"; } int viewHours; if (!int.TryParse(props.ViewHours, out viewHours)) { throw new Exception("Параметр ViewHours должен быть целым числом"); } try { Regex fileNameRe = new Regex(props.FileNamePattern, RegexOptions.IgnoreCase); IInjectionsService injectionsService = serviceProvider.GetService <IInjectionsService>(); ConnectionInfo sftpConnection = GetSftpConnection(props.ConnectionString); using (SftpClient sftpClient = new SftpClient(sftpConnection)) { sftpClient.Connect(); DateTime barrierTime = DateTime.UtcNow.AddHours(-viewHours); IEnumerable <InjectionDto> processedInjections = injectionsService.GetByTaskName(TaskName); HashSet <string> processedFileNames = new HashSet <string>(processedInjections.Select(i => i.FileName)); var files = sftpClient.ListDirectory(props.Folder); files = files.Where(f => f.LastWriteTimeUtc >= barrierTime && f.IsRegularFile) .OrderBy(f => f.LastWriteTimeUtc); foreach (SftpFile file in files) { if (!fileNameRe.IsMatch(file.Name)) { continue; } if (!processedFileNames.Contains(file.Name)) { Log.Information("Найден новый файл: {FullName}.", file.FullName); InjectionDto injection = new InjectionDto { Type = TaskName, FileName = file.Name, ProcessTimeUtc = DateTime.UtcNow }; try { string content = sftpClient.ReadAllText(file.FullName); bool isSuccess = ProcessProductsFile(serviceProvider, file.Name, content); injection.Status = isSuccess ? InjectionStatus.Success : InjectionStatus.Failed; } catch (Exception ex) { Log.Error(ex, "Не удалось обработать файл {Name}.", file.Name); injection.Status = InjectionStatus.Failed; } injectionsService.SaveOrCreate(injection); } } } } catch (Exception ex) { Log.Error(ex, $"Ошибка при обработке {TaskName} инжекции."); throw ex; } }
public override WebResponse GetResponse() { NetworkCredential cred = (m_cred as NetworkCredential); string strUser = ((cred != null) ? cred.UserName : null); string strPassword = ((cred != null) ? cred.Password : null); BaseClient m_Client = null; int l_port = m_uri.Port == -1 ? 22 : m_uri.Port; Uri uriTo = null; if (m_strMethod == KeePassLib.Serialization.IOConnection.WrmMoveFile) { uriTo = new Uri(m_whcHeaders.Get( IOConnection.WrhMoveFileTo)); } MemoryStream reqStream = null; if (m_reqBody.Count > 0) { reqStream = new MemoryStream(m_reqBody.ToArray()); } ConnectionInfo n_con_info; if (File.Exists(m_props.Get("SSHKey"))) { using (FileStream keyStream = new FileStream(m_props.Get("SSHKey"), FileMode.Open)) { PrivateKeyFile v_keyauth; if (strPassword == null) { v_keyauth = new PrivateKeyFile(keyStream); } else { v_keyauth = new PrivateKeyFile(keyStream, strPassword); } n_con_info = new PrivateKeyConnectionInfo(m_uri.Host, l_port, strUser, v_keyauth); } } else if (!String.IsNullOrWhiteSpace(m_props.Get("SSHKey"))) { string keyString = m_props.Get("SSHKey").Replace("\\n", "\n"); using (MemoryStream keyStream = new MemoryStream(Encoding.ASCII.GetBytes(keyString))) { PrivateKeyFile v_keyauth; if (strPassword == null) { v_keyauth = new PrivateKeyFile(keyStream); } else { v_keyauth = new PrivateKeyFile(keyStream, strPassword); } n_con_info = new PrivateKeyConnectionInfo(m_uri.Host, l_port, strUser, v_keyauth); } } else if (String.IsNullOrWhiteSpace(m_props.Get("SSHKey")) && String.IsNullOrWhiteSpace(strPassword)) { // No password, no keyfile, try pageant PageantProtocol agent = new PageantProtocol(); n_con_info = new AgentConnectionInfo(m_uri.Host, l_port, strUser, agent); } else { KeyboardInteractiveAuthenticationMethod v_kauth = new KeyboardInteractiveAuthenticationMethod(strUser); v_kauth.AuthenticationPrompt += SftpWebRequest_AuthenticationPrompt; PasswordAuthenticationMethod v_pauth = new PasswordAuthenticationMethod(strUser, strPassword); n_con_info = new ConnectionInfo(m_uri.Host, l_port, strUser, v_pauth, v_kauth); } m_Client = new SftpClient(n_con_info); //Set timeout to reasonable setting of 30 seconds for default. int connectionTimeout = 30000; if (m_props.Get("SSHTimeout") != null) { int.TryParse(m_props.Get("SSHTimeout"), out connectionTimeout); } m_Client.ConnectionInfo.Timeout = new TimeSpan(0, 0, 0, 0, connectionTimeout); if (m_props.Get("HostKey") != null) { string[] v_ssh_dss_parts = m_props.Get("HostKey").Split(':'); if (v_ssh_dss_parts.Length != 16) { throw new Exception("Input incorrect host fingerprint. Check it. Must look like: 12:34:56:78:90:ab:cd:ef:12:34:56:78:90:ab:cd:ef"); } List <byte> v_ssh_dss_parts_b = new List <byte>(); foreach (string str in v_ssh_dss_parts) { try { v_ssh_dss_parts_b.Add(byte.Parse(str, System.Globalization.NumberStyles.AllowHexSpecifier)); } catch (Exception) { throw new Exception("Input incorrect host fingerprint. Check it. Must look like: 12:34:56:78:90:ab:cd:ef:12:34:56:78:90:ab:cd:ef"); } } m_fingerprint = v_ssh_dss_parts_b.ToArray(); m_Client.HostKeyReceived += M_Client_HostKeyReceived; } return(new SftpWebResponse(m_Client, m_strMethod, m_uri, uriTo, reqStream)); }
/// <summary> /// Starts the user interaction. /// </summary> /// <param name="sshClient">The SSH client.</param> /// <param name="sftpClient">The SFTP client.</param> /// <param name="shellStream">The shell stream.</param> /// <param name="verbOptions">The verb options.</param> private static void StartUserInteraction( SshClient sshClient, SftpClient sftpClient, ShellStream shellStream, MonitorVerbOptions verbOptions) { _forwardShellStreamInput = false; while (true) { var readKey = Console.ReadKey(true); if (readKey.Key == ConsoleKey.F1) { _forwardShellStreamInput = !_forwardShellStreamInput; if (_forwardShellStreamInput) { Program.Title = "Monitor (Interactive)"; " >> Entered console input forwarding.".WriteLine(ConsoleColor.Green); _forwardShellStreamOutput = true; } else { Program.Title = "Monitor (Press H for Help)"; " >> Left console input forwarding.".WriteLine(ConsoleColor.Red); } continue; } if (_forwardShellStreamInput) { if (readKey.Key == ConsoleKey.Enter) { shellStream.Write("\r\n"); } else { shellStream.WriteByte((byte)readKey.KeyChar); } shellStream.Flush(); continue; } switch (readKey.Key) { case ConsoleKey.Q: return; case ConsoleKey.C: Console.Clear(); break; case ConsoleKey.N: CreateNewDeployment(sshClient, sftpClient, shellStream, verbOptions); break; case ConsoleKey.E: RunSshClientCommand(sshClient, verbOptions); break; case ConsoleKey.S: RunShellStreamCommand(shellStream, verbOptions); break; case ConsoleKey.H: const ConsoleColor helpColor = ConsoleColor.Cyan; "Console help".WriteLine(helpColor); " H Prints this screen".WriteLine(helpColor); " Q Quits this application".WriteLine(helpColor); " C Clears the screen".WriteLine(helpColor); " N Force a deployment cycle".WriteLine(helpColor); " E Run the Pre-deployment command".WriteLine(helpColor); " S Run the Post-deployment command".WriteLine(helpColor); " F1 Toggle shell-interactive mode".WriteLine(helpColor); string.Empty.WriteLine(); break; default: $"Unrecognized command '{readKey.KeyChar}' -- Press 'H' to get a list of available commands." .WriteLine(ConsoleColor.Red); break; } } }
/// <summary> /// Starts the user interaction. /// </summary> /// <param name="fsMonitor">The fs monitor.</param> /// <param name="sshClient">The SSH client.</param> /// <param name="sftpClient">The SFTP client.</param> /// <param name="shellStream">The shell stream.</param> /// <param name="verbOptions">The verb options.</param> private static void StartUserInteraction(FileSystemMonitor fsMonitor, SshClient sshClient, SftpClient sftpClient, ShellStream shellStream, MonitorVerbOptions verbOptions) { ForwardShellStreamInput = false; while (true) { var readKey = Console.ReadKey(true); if (readKey.Key == ConsoleKey.F1) { ForwardShellStreamInput = !ForwardShellStreamInput; if (ForwardShellStreamInput) { ConsoleManager.WriteLine(" >> Entered console input forwarding.", ConsoleColor.Green); ForwardShellStreamOutput = true; } else { ConsoleManager.WriteLine(" >> Left console input forwarding.", ConsoleColor.Red); } continue; } if (ForwardShellStreamInput) { if (readKey.Key == ConsoleKey.Enter) { shellStream.WriteLine(string.Empty); } else { shellStream.WriteByte((byte)readKey.KeyChar); } shellStream.Flush(); continue; } if (readKey.Key == ConsoleKey.Q) { break; } if (readKey.Key == ConsoleKey.C) { ConsoleManager.Clear(); continue; } if (readKey.Key == ConsoleKey.N) { CreateNewDeployment(sshClient, sftpClient, shellStream, verbOptions); continue; } if (readKey.Key == ConsoleKey.E) { RunSshClientCommand(sshClient, verbOptions); continue; } if (readKey.Key == ConsoleKey.S) { RunShellStreamCommand(shellStream, verbOptions); continue; } if (readKey.Key != ConsoleKey.H) { ConsoleManager.WriteLine("Unrecognized command '" + readKey.KeyChar + "' -- Press 'H' to get a list of available commands.", ConsoleColor.Red); } if (readKey.Key == ConsoleKey.H) { var helpColor = ConsoleColor.Cyan; ConsoleManager.WriteLine("Console help", helpColor); ConsoleManager.WriteLine(" H Prints this screen", helpColor); ConsoleManager.WriteLine(" Q Quits this application", helpColor); ConsoleManager.WriteLine(" C Clears the screen", helpColor); ConsoleManager.WriteLine(" N Force a deployment cycle", helpColor); ConsoleManager.WriteLine(" E Run the Pre-deployment command", helpColor); ConsoleManager.WriteLine(" S Run the Post-deployment command", helpColor); ConsoleManager.WriteLine(" F1 Toggle shell-interactive mode", helpColor); ConsoleManager.WriteLine(string.Empty); continue; } } }
protected void btnEnviar_Command(object sender, CommandEventArgs e) { try { LoDevices objLo = new LoDevices(); EnDevices objEn = new EnDevices(); DataTable dt = new DataTable(); int index = Convert.ToInt32(e.CommandArgument); Label rowid = (Label)grvListado.Rows[index].FindControl("lblrowid"); Label lblDip = (Label)grvListado.Rows[index].FindControl("lblDip"); dt = objLo.DevicesJson_Selecionar(Convert.ToInt32(rowid.Text)); string ruta = "/files/config.json"; // Setup Credentials and Server Information ConnectionInfo ConnNfo = new ConnectionInfo("104.248.211.185", 22, "root", new AuthenticationMethod[] { // Pasword based Authentication new PasswordAuthenticationMethod("root", "iota2019123"), // Key Based Authentication (using keys in OpenSSH Format) new PrivateKeyAuthenticationMethod("root", new PrivateKeyFile[] { new PrivateKeyFile(@"..\openssh.key", "passphrase") }), } ); // Execute a (SHELL) Command - prepare upload directory using (var sshclient = new SshClient(ConnNfo)) { sshclient.Connect(); using (var cmd = sshclient.CreateCommand("mkdir -p /tmp/uploadtest && chmod +rw /tmp/uploadtest")) { cmd.Execute(); Console.WriteLine("Command>" + cmd.CommandText); Console.WriteLine("Return Value = {0}", cmd.ExitStatus); } sshclient.Disconnect(); } // Upload A File using (var sftp1 = new SftpClient(ConnNfo)) { string uploadfn = "Renci.SshNet.dll"; sftp1.Connect(); sftp1.ChangeDirectory("/opt/prueba/"); using (var uplfileStream = System.IO.File.OpenRead(uploadfn)) { sftp1.UploadFile(uplfileStream, uploadfn, true); } sftp1.Disconnect(); } // Execute (SHELL) Commands using (var sshclient = new SshClient(ConnNfo)) { sshclient.Connect(); // quick way to use ist, but not best practice - SshCommand is not Disposed, ExitStatus not checked... Console.WriteLine(sshclient.CreateCommand("cd /tmp && ls -lah").Execute()); Console.WriteLine(sshclient.CreateCommand("pwd").Execute()); Console.WriteLine(sshclient.CreateCommand("cd /tmp/uploadtest && ls -lah").Execute()); sshclient.Disconnect(); } Console.ReadKey(); //using (var client = new SshClient("104.248.211.185", "root", "iota2019123")) //{ // client.Connect(); // //client.RunCommand("etc/init.d/networking restart"); // client.RunCommand ChangeDirectory("/opt/prueba/"); // using (var uplfileStream = System.IO.File.OpenRead(ruta)) // { // client.UploadFile(uplfileStream, ruta, true); // } // client.Disconnect(); // client.Disconnect(); //} // SendFileToServer.Send(ruta); return; FileInfo Archivo = new FileInfo(HttpContext.Current.Server.MapPath(ruta)); File.WriteAllText(HttpContext.Current.Server.MapPath(ruta), dt.Rows[0]["DJson"].ToString()); string destino = "/opt/prueba/"; string host = lblDip.Text.Trim(); string username = grvListado.DataKeys[index].Values["usuario"].ToString(); string password = Seguridad.DesEncriptar(grvListado.DataKeys[index].Values["clave"].ToString()); SFTPHelper sftp = new SFTPHelper(host, username, password); sftp.Connect(); sftp.Get(ruta, destino); sftp.Disconnect(); } catch (Exception ex) { throw ex; } }
/// <summary> /// Starts the monitor mode. /// </summary> /// <param name="fsMonitor">The fs monitor.</param> /// <param name="sshClient">The SSH client.</param> /// <param name="sftpClient">The SFTP client.</param> /// <param name="shellStream">The shell stream.</param> /// <param name="verbOptions">The verb options.</param> private static void StartMonitorMode(FileSystemMonitor fsMonitor, SshClient sshClient, SftpClient sftpClient, ShellStream shellStream, MonitorVerbOptions verbOptions) { fsMonitor.FileSystemEntryChanged += (s, e) => { // Detect changes to the monitor file by ignoring deletions and checking file paths. if (e.ChangeType != FileSystemEntryChangeType.FileAdded && e.ChangeType != FileSystemEntryChangeType.FileModified) { return; } // If the change was not in the monitor file, then ignore it if (e.Path.ToLowerInvariant().Equals(verbOptions.MonitorFile.ToLowerInvariant()) == false) { return; } // Create a new deployment once CreateNewDeployment(sshClient, sftpClient, shellStream, verbOptions); }; fsMonitor.Start(); ConsoleManager.WriteLine("File System Monitor is now running."); ConsoleManager.WriteLine("Writing a new monitor file will trigger a new deployment."); ConsoleManager.WriteLine("Press H for help!"); ConsoleManager.WriteLine("Ground Control to Major Tom: Have a nice trip in space!", ConsoleColor.DarkCyan); }
private void CreateConnection() { if (m_con != null && m_con.IsConnected) { return; } if (m_con != null && !m_con.IsConnected) { m_con.Connect(); return; } SftpClient con; string keyfile; m_options.TryGetValue(SSH_KEYFILE_OPTION, out keyfile); if (string.IsNullOrWhiteSpace(keyfile)) { m_options.TryGetValue(SSH_KEYFILE_INLINE, out keyfile); } if (!string.IsNullOrWhiteSpace(keyfile)) { con = new SftpClient(m_server, m_port, m_username, ValidateKeyFile(keyfile, m_password)); } else { con = new SftpClient(m_server, m_port, m_username, m_password ?? string.Empty); } con.HostKeyReceived += delegate(object sender, HostKeyEventArgs e) { e.CanTrust = false; if (m_fingerprintallowall) { e.CanTrust = true; return; } string hostFingerprint = e.HostKeyName + " " + e.KeyLength.ToString() + " " + BitConverter.ToString(e.FingerPrint).Replace('-', ':'); if (string.IsNullOrEmpty(m_fingerprint)) { throw new Library.Utility.HostKeyException(Strings.SSHv2Backend.FingerprintNotSpecifiedManagedError(hostFingerprint.ToLower(), SSH_FINGERPRINT_OPTION, SSH_FINGERPRINT_ACCEPT_ANY_OPTION), hostFingerprint, m_fingerprint); } if (!String.Equals(hostFingerprint, m_fingerprint, StringComparison.OrdinalIgnoreCase)) { throw new Library.Utility.HostKeyException(Strings.SSHv2Backend.FingerprintNotMatchManagedError(hostFingerprint.ToLower()), hostFingerprint, m_fingerprint); } else { e.CanTrust = true; } }; if (m_operationtimeout.Ticks != 0) { con.OperationTimeout = m_operationtimeout; } if (m_keepaliveinterval.Ticks != 0) { con.KeepAliveInterval = m_keepaliveinterval; } con.Connect(); m_con = con; }
/// <summary> /// 更新指定存档路径下的集群服务器列表 /// </summary> /// <param name="keyword">筛选关键词</param> /// <param name="saveFolder">存档文件夹名</param> /// <param name="clusterList">Listbox控件</param> /// <param name="client">远程服务器连接</param> private void RefreshClusterData(string saveFolder, string keyword, ref ListBox clusterList, SftpClient client) { //获取集群文件夹名称并更新显示 ObservableCollection <string> clusterFolder = null; if (client == null) { clusterFolder = SavesManager.GetClusterFolder(saveFolder, keyword); } else { clusterFolder = SavesManager.GetClusterFolder(saveFolder, keyword, client); } clusterList.Items.Clear(); foreach (var item in clusterFolder) { if (!clusterList.Items.Contains(item)) { clusterList.Items.Add(item); } } }
private static void Upload() { if (Command.Length <= 7) { Command = "upload -h"; } if ((Command = Command.Remove(0, 7)) == "-h") { Console.WriteLine( "upload [--dir]* [args] [user@host]:[location]\n\n'args' are seperated using spaces ( ) and last 'arg' will be treated as server data whic" + "h includes username and host location as well as the location of data to upload, part after the colon (:), where the data is to be uplo" + "aded. Use flag '--dir' to upload directiories. Do not use absolute paths for local path, change working directory to navigate."); } else { var toupload = Command.StartsWith("--dir") ? Command.Replace("--dir", "").Trim().Split(' ').ToList() : Command.Trim().Split(' ').ToList(); try { var serverData = toupload.Pop().Split(':'); var data = serverData[0]; var location = serverData[1]; try { var ccinfo = CreateConnection(data); if (ccinfo != null) { if (Command.StartsWith("--dir")) { using (var sftp = new SftpClient(ccinfo)) { Command = Command.Replace("--dir", ""); sftp.Connect(); toupload.ForEach(x => { var path = $"{WorkingDirectory}/{x.Trim()}"; location = serverData[1] + (serverData[1].EndsWith("/") ? "" : "/") + x.Trim(); if (!sftp.Exists(location)) { sftp.CreateDirectory(location); } Color($"Uploading <directory>: {x.Trim()}\n", ConsoleColor.Yellow); UploadDir(sftp, path, location); Color("Done.\n", ConsoleColor.Green); }); } } else { using (var scp = new ScpClient(ccinfo)) { scp.Connect(); toupload.ForEach(x => { var path = $"{WorkingDirectory}/{x.Trim()}"; if (File.Exists(path)) { Color($"Uploading <file>: {x.Trim()}", ConsoleColor.Yellow); scp.Upload(new FileInfo(path), location); Color(" -> Done\n", ConsoleColor.Green); } else { Error($"SWSH -> {path.Replace('/', '\\')} -> file does not exists.\n"); } }); } } } } catch (Exception exp) { Error($"{exp.Message}\n"); } } catch { Error($"SWSH -> upload {Command} -> is not the correct syntax for this command.\n"); } } void UploadDir(SftpClient client, string localPath, string remotePath) { new DirectoryInfo(localPath).EnumerateFileSystemInfos().ToList().ForEach(x => { if (x.Attributes.HasFlag(FileAttributes.Directory)) { var subPath = $"{remotePath}/{x.Name}"; if (!client.Exists(subPath)) { client.CreateDirectory(subPath); } UploadDir(client, x.FullName, $"{remotePath}/{x.Name}"); } else { using (Stream fileStream = new FileStream(x.FullName, FileMode.Open)) { Console.ForegroundColor = ConsoleColor.Yellow; Console.Write($"\tUploading <file>: {x} ({((FileInfo)x).Length:N0} bytes)"); client.UploadFile(fileStream, $"{remotePath}/{x.Name}"); Color(" -> Done\n", ConsoleColor.Green); } } }); } }
private void download_sftp(string remote_path, string local_path) { // https://stackoverflow.com/questions/43555982/displaying-progress-of-file-upload-in-a-progressbar-with-ssh-net // https://stackoverflow.com/questions/44442714/displaying-progress-of-file-download-in-a-progressbar-with-ssh-net download_status = DOWNLOAD_STATUS.start; update_ui(); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); // remove previus download files SftpClient sftp = new SftpClient(Constants.SFTP_ADDR, Constants.SFTP_ID, Constants.SFTP_PWD); try { using (var stream = new FileStream(local_path, FileMode.Create)) using (sftp) { if (!sftp.IsConnected) { sftp.Connect(); } SftpFileAttributes attributes = sftp.GetAttributes(remote_path); // Set progress bar maximum on foreground thread Application.Current.Dispatcher.Invoke(() => { var file_size = ByteSize.FromBytes((double)attributes.Size); prgbDownload.Value = 0; prgbDownload.Maximum = (int)file_size.Bytes; prgbDownloadText.Text = string.Format("{0} / {1:F1} MB", 0, file_size.MegaBytes); }); sftp.DownloadFile(remote_path, stream, download_sftp_progress); extract_zipfile(local_path); download_status = DOWNLOAD_STATUS.end; update_ui(); } } catch (Exception e) { download_status = DOWNLOAD_STATUS.ini; update_ui(); MessageBox.Show(e.Message); } stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); if (download_status == DOWNLOAD_STATUS.end) { Application.Current.Dispatcher.Invoke(() => { prgbDownloadText.Text += "(" + elapsedTime + ")"; }); } sftp.Dispose(); }
public RequiredCallbacks(VirtualizationInstance virtualization, SftpClient client) { _virtInstance = virtualization; _sftpClient = client; }
internal static void UploadFile(this SftpClient sftp, string fileName, bool overwrite = false, string remoteDirectoryPath = null) { UploadFile(sftp, new FileInfo(fileName), overwrite, remoteDirectoryPath); }
/// <summary> /// Sync <paramref name="sourceDir"/> with <paramref name="destDir"/> /// </summary> /// <param name="connectInfo">Credentials to access host where synchronization takes place.</param> /// <param name="sourceDir">Source directory on the local host.</param> /// <param name="destDir">Destination directory on the remote host</param> /// <param name="logger">Logging facility</param> /// <returns><c>true</c> if successful; otherwise, <c>false</c>.</returns> private static bool SyncTo(ConnectionInfo connectInfo, UDirectory sourceDir, UDirectory destDir, LoggerResult logger) { // Copy files over using (var sftp = new SftpClient(connectInfo)) { try { sftp.Connect(); if (!sftp.IsConnected) { return(false); } } catch { logger.Error("Cannot connect"); return(false); } // Perform recursive copy of all the folders under `sourceDir`. This is required // as the sftp client only synchronize directories at their level only, no // subdirectory. var dirs = new Queue <DirectoryInfo>(); dirs.Enqueue(new DirectoryInfo(sourceDir)); var parentPath = sourceDir; while (dirs.Count != 0) { var currentDir = dirs.Dequeue(); var currentPath = new UDirectory(currentDir.FullName); foreach (var subdir in currentDir.EnumerateDirectories()) { dirs.Enqueue(subdir); } // Get the destination path by adding to `Location` the relative path of `sourceDir` to `currentDir`. var destination = UPath.Combine(destDir, currentPath.MakeRelative(parentPath)); logger.Info("Synchronizing " + currentPath + " with " + destination.FullPath); // Try to create a remote directory. If it throws an exception, we will assume // for now that the directory already exists. See https://github.com/sshnet/SSH.NET/issues/25 try { sftp.CreateDirectory(destination.FullPath); logger.Info("Creating remote directory " + destination.FullPath); } catch (SshException) { // Do nothing, as this is when the directory already exists } // Synchronize files. foreach (var file in sftp.SynchronizeDirectories(currentPath.FullPath, destination.FullPath, "*")) { logger.Info("Updating " + file.Name); // Some of our files needs executable rights, however we do not know in advance which one // need it. For now all files will be rwxr.xr.x (0755 in octal but written in decimal for readability). sftp.ChangePermissions(destination.FullPath + "/" + file.Name, 755); } } return(true); } }
internal static SftpClient CreateSftpClient(this string connectionString) { if (connectionString == null) { throw new ArgumentNullException("connectionString"); } // get parts of connection string var csb = new DbConnectionStringBuilder { ConnectionString = connectionString }; var host = csb["host"] as string; var username = csb["username"] as string; var password = csb["password"] as string; var hostkey = csb["hostkey"] as string; var port = Attempt.Get(() => Convert.ToInt32(csb["port"])); // do this when connstring is bad Action <string> badConnString = detail => { throw new FormatException( string.Format( "SFTP connection string invalid. {0} Example: username=USERNAME;password=PASSWORD;host=HOSTNAME;hostkey=ssh-dss 1024 3b:1c:20:aa:27:00:83:4f:7a:49:9c:9f:e7:67:ab:03", detail ?? "")); }; // check required conn string params if (new[] { host, username, password, hostkey }.Any(string.IsNullOrWhiteSpace)) { badConnString("Missing required parameter."); } // check format of host key var hostKeyParts = hostkey.Split().Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim().ToLower()).ToArray(); // host key needs 3 parts: name, length, fingerprint if (hostKeyParts.Length != 3) { badConnString(string.Format("Host key '{0}' is incorrectly formatted.", hostkey)); } // length neeeds to be an int int hostKeyLength; if (!int.TryParse(hostKeyParts[1], out hostKeyLength)) { badConnString(string.Format("Host key length '{0}' is not an integer.", hostKeyParts[1])); } // finter print needs to be a byte array as hex string var hostKeyPrint = Attempt.Get(() => SoapHexBinary.Parse(string.Concat(hostKeyParts[2].Where(char.IsLetterOrDigit))).Value); if (!hostKeyPrint.Succeeded) { badConnString(string.Format("Invalid host key fingerprint '{0}'.", hostKeyParts[2])); } // using only pw auth for time being var pwAuthMethod = new PasswordAuthenticationMethod(username, password); var connInfo = port.Succeeded ? new ConnectionInfo(host, port.Value, username, pwAuthMethod) : new ConnectionInfo(host, username, pwAuthMethod); var sftpClient = new SftpClient(connInfo); // validate host key sftpClient.HostKeyReceived += (s, e) => { e.CanTrust = hostKeyParts[0].Equals(e.HostKeyName.Trim(), StringComparison.OrdinalIgnoreCase) && hostKeyLength == e.KeyLength && hostKeyPrint.Value.SequenceEqual(e.FingerPrint); }; return(sftpClient); }
private static SftpFile GetFile(SftpClient client, string path, string name) { return(client.ListDirectory(path).FirstOrDefault(f => f.Name.ToLower().Contains(name.ToLower()))); }
/// <summary> /// Конструктор /// </summary> /// <param name="scp"></param> public Scp(SftpClient scp) { _sftpClient = scp; _sftpClient.Connect(); }
private List <string> SearchDirectory(string remoteDirectory, string pattern, bool includeDirectories, bool recursive, SftpClient sftp) { var results = new List <string>(); //Basic checks if (!sftp.IsConnected) { logger.Error("SFTP client is not connected!"); } if (string.IsNullOrWhiteSpace(remoteDirectory)) { remoteDirectory = "."; } //Get listing var files = sftp.ListDirectory(remoteDirectory); foreach (var file in files) { //Should not mess with current and parrent directories if (file.FullName.EndsWith(".") || file.FullName.EndsWith("..")) { continue; } //Add match when needed if ((string.IsNullOrEmpty(pattern) || file.FullName.Contains(pattern)) && ((file.IsDirectory && includeDirectories) || !file.IsDirectory)) { results.Add(file.FullName); } //Check for recursive search if (recursive && file.IsDirectory) { //Recursive call var response = SearchDirectory(file.FullName, pattern, includeDirectories, recursive, sftp); //Add results if (response != null && response.Count > 0) { results.AddRange(response); } } } return(results); }