public void Test_Connect_Handle_HostKeyReceived() { var host = Resources.HOST; var username = Resources.USERNAME; var password = Resources.PASSWORD; var hostKeyValidated = false; #region Example SshClient Connect HostKeyReceived using (var client = new SshClient(host, username, password)) { client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e) { hostKeyValidated = true; if (e.FingerPrint.SequenceEqual(new byte[] { 0x00, 0x01, 0x02, 0x03 })) { e.CanTrust = true; } else { e.CanTrust = false; } }; client.Connect(); // Do something here client.Disconnect(); } #endregion Assert.IsTrue(hostKeyValidated); }
public void Test_KeyExchange_Rekeying() { var connectionInfo = new PasswordConnectionInfo(Resources.HOST, 22, Resources.USERNAME, Resources.PASSWORD); using (var client = new SshClient(connectionInfo)) { client.Connect(); // TODO: Add test to test re-keying Assert.Inconclusive(); client.Disconnect(); } }
public void BeginExecuteTest() { string expected = "123\n"; string result; using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { #region Example SshCommand CreateCommand BeginExecute IsCompleted EndExecute client.Connect(); var cmd = client.CreateCommand("sleep 15s;echo 123"); // Perform long running task var asynch = cmd.BeginExecute(); while (!asynch.IsCompleted) { // Waiting for command to complete... Thread.Sleep(2000); } result = cmd.EndExecute(asynch); client.Disconnect(); #endregion Assert.IsNotNull(asynch); Assert.AreEqual(expected, result); } }
static void Main(string[] args) { // Setup Credentials and Server Information ConnectionInfo ConnNfo = new ConnectionInfo("10.141.3.110",22,"root", new AuthenticationMethod[]{ // Pasword based Authentication new PasswordAuthenticationMethod("root","ismail"), } ); // 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("telnet localhost 6571"); Console.WriteLine("denemeeeeeee"); //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(); }
public void Test_Execute_Command_Asynchronously_With_Callback() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); var callbackCalled = false; var cmd = client.CreateCommand("sleep 5s; echo 'test'"); var asyncResult = cmd.BeginExecute(new AsyncCallback((s) => { callbackCalled = true; }), null); while (!asyncResult.IsCompleted) { Thread.Sleep(100); } cmd.EndExecute(asyncResult); Assert.IsTrue(callbackCalled); client.Disconnect(); } }
public void CleanCurrentFolder() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); client.RunCommand("rm -rf *"); client.Disconnect(); } }
public void Test_AddForwardedPort_Invalid_PortNumber() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); var port1 = client.AddForwardedPort<ForwardedPortRemote>("localhost", IPEndPoint.MaxPort+1, "www.renci.org", IPEndPoint.MaxPort+1); client.Disconnect(); } }
public void Test_AddForwardedPort_Remote_Hosts_Are_Null() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); var port1 = client.AddForwardedPort<ForwardedPortRemote>(null, 8080, null, 80); client.Disconnect(); } }
public void Test_EndExecute_Before_BeginExecute() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); var cmd = client.CreateCommand("ls -l"); cmd.EndExecute(null); client.Disconnect(); } }
public void Test_HMac_Sha256_Connection() { var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD); connectionInfo.HmacAlgorithms.Clear(); connectionInfo.HmacAlgorithms.Add("hmac-sha2-256", new HashInfo(32 * 8, HashAlgorithmFactory.CreateHMACSHA256)); using (var client = new SshClient(connectionInfo)) { client.Connect(); client.Disconnect(); } }
public void Test_HostKey_SshDss_Connection() { var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD); connectionInfo.HostKeyAlgorithms.Clear(); connectionInfo.HostKeyAlgorithms.Add("ssh-dss", (data) => { return new KeyHostAlgorithm("ssh-dss", new DsaKey(), data); }); using (var client = new SshClient(connectionInfo)) { client.Connect(); client.Disconnect(); } }
public void Test_HMac_Sha1_96_Connection() { var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD); connectionInfo.HmacAlgorithms.Clear(); connectionInfo.HmacAlgorithms.Add("hmac-sha1", new HashInfo(20 * 8, key => CryptoAbstraction.CreateHMACSHA1(key, 96))); using (var client = new SshClient(connectionInfo)) { client.Connect(); client.Disconnect(); } }
public void Test_HMac_MD5_96_Connection() { var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD); connectionInfo.HmacAlgorithms.Clear(); connectionInfo.HmacAlgorithms.Add("hmac-md5", new HashInfo(16 * 8, key => HashAlgorithmFactory.CreateHMACMD5(key, 96))); using (var client = new SshClient(connectionInfo)) { client.Connect(); client.Disconnect(); } }
public void Test_HMac_Sha1_Connection() { var connectionInfo = new PasswordConnectionInfo(Resources.HOST, 22, Resources.USERNAME, Resources.PASSWORD); connectionInfo.HmacAlgorithms.Clear(); connectionInfo.HmacAlgorithms.Add("hmac-sha1", (key) => { return new HMac<SHA1Hash>(key.Take(20).ToArray()); }); using (var client = new SshClient(connectionInfo)) { client.Connect(); client.Disconnect(); } }
public void Test_AddForwardedPort_Local_Hosts_Are_Empty() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); var port1 = client.AddForwardedPort<ForwardedPortLocal>(string.Empty, 8080, string.Empty, 80); client.Disconnect(); } }
public void Test_Cipher_Cast128CBC_Connection() { var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD); connectionInfo.Encryptions.Clear(); connectionInfo.Encryptions.Add("cast128-cbc", new CipherInfo(128, (key, iv) => { return new CastCipher(key, new CbcCipherMode(iv), null); })); using (var client = new SshClient(connectionInfo)) { client.Connect(); client.Disconnect(); } }
public void Test_Cipher_Aes256CBC_Connection() { var connectionInfo = new PasswordConnectionInfo(Resources.HOST, 22, Resources.USERNAME, Resources.PASSWORD); connectionInfo.Encryptions.Clear(); connectionInfo.Encryptions.Add("aes256-cbc", new CipherInfo(256, (key, iv) => { return new AesCipher(key, new CbcCipherMode(iv), null); })); using (var client = new SshClient(connectionInfo)) { client.Connect(); client.Disconnect(); } }
public void Test_KeyExchange_GroupExchange_Sha256_Connection() { var connectionInfo = new PasswordConnectionInfo(Resources.HOST, 22, Resources.USERNAME, Resources.PASSWORD); connectionInfo.KeyExchangeAlgorithms.Clear(); connectionInfo.KeyExchangeAlgorithms.Add("diffie-hellman-group-exchange-sha256", typeof(KeyExchangeDiffieHellmanGroupExchangeSha256)); using (var client = new SshClient(connectionInfo)) { client.Connect(); client.Disconnect(); } }
public void Test_Connect_Using_Correct_Password() { var host = Resources.HOST; var username = Resources.USERNAME; var password = Resources.PASSWORD; #region Example SshClient(host, username) Connect using (var client = new SshClient(host, username, password)) { client.Connect(); // Do something here client.Disconnect(); } #endregion }
protected void Arrange() { _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth")); _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict); _sessionMock = new Mock<ISession>(MockBehavior.Strict); var sequence = new MockSequence(); _serviceFactoryMock.InSequence(sequence).Setup(p => p.CreateSession(_connectionInfo)).Returns(_sessionMock.Object); _sessionMock.InSequence(sequence).Setup(p => p.Connect()); _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); _sessionMock.InSequence(sequence).Setup(p => p.Dispose()); _sshClient = new SshClient(_connectionInfo, false, _serviceFactoryMock.Object); _sshClient.Connect(); }
protected void RebootButton_Click(object sender, EventArgs e) { try { using (var client = new SshClient("ra-jetson.duckdns.org", "ubuntu", "savingL1v3s")) { client.Connect(); client.RunCommand("sudo /home/ubuntu/Desktop/bandhan/SQL-Scripts/./RightAlertRemoteRebootIssued-SQL"); // SSH Command Here client.RunCommand("sudo reboot"); // SSH Command Here client.Disconnect(); } } catch (Exception ex) { Response.Redirect("Down.html"); } }
//[TestMethod] public void Test_MultipleThread_10000_MultipleSessions() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); System.Threading.Tasks.Parallel.For(0, 10000, (counter) => { var result = ExecuteTestCommand(client); Debug.WriteLine(string.Format("TestMultipleThreadMultipleConnections #{0}", counter)); Assert.IsTrue(result); } ); client.Disconnect(); } }
public void Test_PrivateKeyConnectionInfo() { var host = Resources.HOST; var username = Resources.USERNAME; MemoryStream keyFileStream = new MemoryStream(Encoding.ASCII.GetBytes(Resources.RSA_KEY_WITHOUT_PASS)); #region Example PrivateKeyConnectionInfo PrivateKeyFile var connectionInfo = new PrivateKeyConnectionInfo(host, username, new PrivateKeyFile(keyFileStream)); using (var client = new SshClient(connectionInfo)) { client.Connect(); client.Disconnect(); } #endregion Assert.AreEqual(connectionInfo.Host, Resources.HOST); Assert.AreEqual(connectionInfo.Username, Resources.USERNAME); }
public void Test_Execute_Command_Asynchronously() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); var cmd = client.CreateCommand("sleep 5s; echo 'test'"); var asyncResult = cmd.BeginExecute(null, null); while (!asyncResult.IsCompleted) { Thread.Sleep(100); } cmd.EndExecute(asyncResult); Assert.IsTrue(cmd.Result == "test\n"); client.Disconnect(); } }
public void Test_ForwardedPortRemote() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { #region Example SshClient AddForwardedPort Start Stop ForwardedPortRemote client.Connect(); var port = new ForwardedPortRemote(8082, "www.cnn.com", 80); client.AddForwardedPort(port); port.Exception += delegate(object sender, ExceptionEventArgs e) { Console.WriteLine(e.Exception.ToString()); }; port.Start(); Thread.Sleep(1000 * 60 * 20); // Wait 20 minutes for port to be forwarded port.Stop(); #endregion } Assert.Inconclusive("TODO: Implement code to verify target"); }
public void Test_Run_SingleCommand() { var host = Resources.HOST; var username = Resources.USERNAME; var password = Resources.PASSWORD; using (var client = new SshClient(host, username, password)) { #region Example SshCommand RunCommand Result client.Connect(); var testValue = Guid.NewGuid().ToString(); var command = client.RunCommand(string.Format("echo {0}", testValue)); var result = command.Result; result = result.Substring(0, result.Length - 1); // Remove \n character returned by command client.Disconnect(); #endregion Assert.IsTrue(result.Equals(testValue)); } }
public void Test_PortForwarding_Remote() { // ****************************************************************** // ************* Tests are still in not finished ******************** // ****************************************************************** using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); var port1 = new ForwardedPortRemote(8082, "www.renci.org", 80); client.AddForwardedPort(port1); port1.Exception += delegate(object sender, ExceptionEventArgs e) { Assert.Fail(e.Exception.ToString()); }; port1.Start(); var boundport = port1.BoundPort; System.Threading.Tasks.Parallel.For(0, 5, //new ParallelOptions //{ // MaxDegreeOfParallelism = 1, //}, (counter) => { var cmd = client.CreateCommand(string.Format("wget -O- http://localhost:{0}", boundport)); var result = cmd.Execute(); var end = DateTime.Now; Debug.WriteLine(string.Format("Length: {0}", result.Length)); } ); Thread.Sleep(1000 * 100); port1.Stop(); } }
public void Test_MultipleThread_Example_MultipleConnections() { var host = Resources.HOST; var username = Resources.USERNAME; var password = Resources.PASSWORD; try { #region Example SshCommand RunCommand Parallel System.Threading.Tasks.Parallel.For(0, 10000, () => { var client = new SshClient(host, username, password); client.Connect(); return client; }, (int counter, ParallelLoopState pls, SshClient client) => { var result = client.RunCommand("echo 123"); Debug.WriteLine(string.Format("TestMultipleThreadMultipleConnections #{0}", counter)); return client; }, (SshClient client) => { client.Disconnect(); client.Dispose(); } ); #endregion } catch (Exception exp) { Assert.Fail(exp.ToString()); } }
// Method for Connecting public void Connect() { SSHSess.Connect(); }
public static void Main(string[] args) { using (var sw = new StreamWriter(args[0])) { sw.WriteLine("Welcome to Windows service in .net"); } Console.ReadKey(); { //Connection information Console.WriteLine("Welcome to CMD SSH! I need correct login information and port 22 SSH protocol to be allowed by the firewall to work. Program C 2020 keifmeister."); Console.WriteLine(""); Console.WriteLine("Enter username to be logged into:"); string username = Convert.ToString(Console.ReadLine()); Console.WriteLine("Enter user password."); string password = Convert.ToString(Console.ReadLine()); Console.WriteLine("Enter IP address for SSH connection."); string ipaddr = Convert.ToString(Console.ReadLine()); { // insert stuff here { /* everything inside the `while` loop will be * repeated until `continue` is not `true`. */ } Console.WriteLine("Run another command? Type anything besides no to run a command, or type no to exit."); string ranother = Convert.ToString(Console.ReadLine()); while (ranother != "no") { Console.WriteLine("Enter command to be run."); string rcommand = Convert.ToString(Console.ReadLine()); string user = username; string pass = password; string host = ipaddr; //Set up the SSH connection using (var client = new SshClient(host, user, pass)) try { //Start the connection client.Connect(); var output = client.RunCommand(rcommand); Console.WriteLine(output.Result); } catch (Exception e) { Console.WriteLine("It looks like I couldn't make a connection. Possible reasons for this include: login information (password, username, or ip address) was entered incorrectly. Please double check. Other reasons: The server connecting to is not configured for SSH or I am blocked by a firewall. Cheers"); } } } } }
public static bool BeginForwarding(int linkId, int local_port, int remote_port) { if (client != null && client.ForwardedPorts.Select(port => ((ForwardedPortLocal)port).BoundPort).ToList().Contains((uint)local_port)) { MessageBox.Show("Local port is already forwarding, use a different port", "SSH Error", MessageBoxButton.OK, MessageBoxImage.Error); return(false); } if (spacebridge_key.Count == 0) { var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".hologram"); spacebridge_key.Add(new PrivateKeyFile(path + "/spacebridge.key")); } if (client == null) { client = new SshClient(tunnel_server, tunnel_port, "htunnel", spacebridge_key.ToArray()) { KeepAliveInterval = new TimeSpan(0, 0, 30) }; client.HostKeyReceived += (sender, e) => { if (hologram_fingerprint.Length == e.FingerPrint.Length) { for (var i = 0; i < hologram_fingerprint.Length; i++) { if (hologram_fingerprint[i] != e.FingerPrint[i]) { e.CanTrust = false; break; } } } else { e.CanTrust = false; } }; try { client.Connect(); System.Diagnostics.Debug.WriteLine("Client Connected"); } catch (Exception e) { MessageBox.Show(e.Message, "SSH Error", MessageBoxButton.OK, MessageBoxImage.Error); System.Diagnostics.Debug.WriteLine(e.Message); return(false); } client.ErrorOccurred += Client_ErrorOccurred; } var port = new ForwardedPortLocal("localhost", (uint)local_port, "link" + linkId, (uint)remote_port); client.AddForwardedPort(port); port.Exception += delegate(object sender, ExceptionEventArgs e) { MessageBox.Show("Spacebridge encountered an error:\n" + e.Exception.Message, "SSH Error", MessageBoxButton.OK, MessageBoxImage.Error); System.Diagnostics.Debug.WriteLine(e.Exception.ToString()); }; port.Start(); System.Diagnostics.Debug.WriteLine("Forwarding " + port.BoundHost + ":" + port.BoundPort + " to " + port.Host + ":" + port.Port); return(true); }
public async Task Publish() { Console.WriteLine("Publish started..."); foreach (string file in Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*.csproj", SearchOption.AllDirectories)) { string fileName = Path.GetFileName(file); if (fileName == $"{_projectName}.csproj") { projectFile = fileName; projectFolder = Path.GetDirectoryName(file); } } if (string.IsNullOrEmpty(projectFile)) { Console.WriteLine("The project file cannot be found!"); return; } string profilePath = Path.IsPathRooted(_profile) ? _profile : Path.Combine(projectFolder, _profile); PublishSettings settings = JsonSerializer.Deserialize <PublishSettings>(await File.ReadAllTextAsync(profilePath)); XmlSerializer serializer = new(typeof(PublisherProject)); TextReader reader = new StringReader(await File.ReadAllTextAsync(Path.Combine(projectFolder, projectFile))); PublisherProject propertyGroup = (PublisherProject)serializer.Deserialize(reader); // Publish Process process = new(); process.StartInfo.FileName = "dotnet"; process.StartInfo.Arguments = $"publish {Path.Combine(projectFolder, projectFile)} -c Release -f {propertyGroup.PropertyGroup.TargetFramework}"; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); process.WaitForExit(); if (process.ExitCode != 0) { return; } // Stop service using (var client = new SshClient(settings.Host, settings.Username, settings.Password)) { client.Connect(); string commandStr = $"sc stop \"{settings.ServiceName}\""; Console.WriteLine(commandStr); SshCommand command = client.RunCommand(commandStr); Console.WriteLine(command.Result); client.Disconnect(); if (command.ExitStatus != 0 && command.ExitStatus != 1062) { return; } } // Upload files using (SftpClient client = new(settings.Host, settings.Username, settings.Password)) { client.Connect(); UploadDirectory(client, Path.Combine(projectFolder, "bin", "Release", propertyGroup.PropertyGroup.TargetFramework, "publish"), settings.ServerFolder); client.Disconnect(); } // Start service using (var client = new SshClient(settings.Host, settings.Username, settings.Password)) { client.Connect(); string commandStr = $"sc start \"{settings.ServiceName}\""; Console.WriteLine(commandStr); SshCommand command = client.RunCommand(commandStr); Console.WriteLine(command.Result); client.Disconnect(); if (command.ExitStatus != 0) { return; } } Console.WriteLine("Publish Succeeded."); }
private void TrySshConnect() { client = new SshClient(IP, UserName, Password); client.Connect(); }
/// <summary> /// /// </summary> /// <param name="target"></param> /// <returns></returns> public SSHData SendS2(string target, string user) { var reponse = new SSHData { }; var numbers = "0123456789"; var upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var lowerLetters = upperLetters.ToLower(); var all = upperLetters + numbers + lowerLetters; var str = all; var results = from e in Range(0, BigInteger.Pow(2, str.Length)) let p = from b in Enumerable.Range(1, str.Length) select(e & BigInteger.Pow(2, b - 1)) == 0 ? (char?)null : str[b - 1] select string.Join(string.Empty, p); bool valid = false; SshClient CS = new SshClient(target, 22, "user", "pass"); BigInteger index = 0; foreach (var pass in results.Cast <object>() .Select((r, i) => new { Value = r, Index = i })) { if (pass.Value.ToString().Length >= 6) { Console.ForegroundColor = ConsoleColor.Cyan; Console.Write("\nIndex of string resulted is "); Console.ForegroundColor = ConsoleColor.DarkMagenta; Console.WriteLine(pass.Index); Console.ForegroundColor = ConsoleColor.Cyan; Console.Write("Index of string with length >= 6 is "); Console.ForegroundColor = ConsoleColor.DarkMagenta; Console.WriteLine(++index); Console.ForegroundColor = ConsoleColor.DarkMagenta; Console.ResetColor(); Console.WriteLine("Check for user=\"" + user + "\" and password=\"" + pass.Value + "\""); CS = new SshClient(target, 22, user, pass.Value.ToString()); try { CS.Connect(); } catch (Exception Ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(Ex.Message); Console.ResetColor(); } bool IsConnected = CS.IsConnected; if (IsConnected) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Success! The password are indentificated!"); reponse = new SSHData { SSHUser = user, SSHPasword = pass.Value.ToString(), SSHTarget = target }; Console.ResetColor(); break; } } } CS.Disconnect(); return(reponse); }
// Method for Connecing public void Connect() { Session.Connect(); }
/// <summary> /// Launch <paramref name="exePath"/> on remote host using credentials stored in EditorSettings. /// Before launching all the files requires by <paramref name="exePath"/> are copied over to host /// using the location specified in EditorSettings.Location. If <paramref name="isCoreCLR"/> is set /// all the Stride native libraries are copied over to the current directory of the game on the remote /// host via the `CoreCLRSetup` script. /// </summary> /// <param name="logger">Logger to show progress and any issues that may occur.</param> /// <param name="exePath">Path on the local machine where the executable was compiled.</param> /// <param name="isCoreCLR">Is <paramref name="exePath"/> executed against .NET Core?</param> /// <returns>True when launch was successful, false otherwise.</returns> internal static bool Launch([NotNull] LoggerResult logger, [NotNull] UFile exePath, bool isCoreCLR) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } if (exePath == null) { throw new ArgumentNullException(nameof(exePath)); } var host = StrideEditorSettings.Host.GetValue(); var username = StrideEditorSettings.Username.GetValue(); var port = StrideEditorSettings.Port.GetValue(); var password = Decrypt(StrideEditorSettings.Password.GetValue()); var location = new UDirectory(StrideEditorSettings.Location.GetValue()); var display = StrideEditorSettings.Display.GetValue(); var connectInfo = NewConnectionInfo(host, port, username, password); if (SyncTo(connectInfo, exePath.GetFullDirectory(), UPath.Combine(location, new UDirectory(exePath.GetFileNameWithoutExtension())), logger)) { var sshClient = new SshClient(connectInfo); try { sshClient.Connect(); if (sshClient.IsConnected) { string cmdString; SshCommand cmd; // Due to lack of Dllmap config for CoreCLR, we have to ensure that our native libraries // are copied next to the executable. The CoreCLRSetup script will check the 32-bit vs 64-bit // of the `dotnet` runner and copy the .so files from the proper x86 or x64 directory. if (isCoreCLR) { cmdString = "bash -c 'source /etc/profile ; cd " + location + "/" + exePath.GetFileNameWithoutExtension() + ";" + "sh ./CoreCLRSetup.sh'"; cmd = sshClient.CreateCommand(cmdString); cmd.Execute(); var err = cmd.Error; if (!string.IsNullOrEmpty(err)) { logger.Error(err); // We don't exit here in case of failure, we just print the error and continue // Users can then try to fix the issue directly on the remote host. } else { err = cmd.Result; if (!string.IsNullOrEmpty(err)) { logger.Info(err); } } } // Try to get the main IP of the machine var ipv4 = GetAllLocalIPv4().FirstOrDefault(); var connectionRouter = string.Empty; if (!string.IsNullOrEmpty(ipv4)) { connectionRouter = " StrideConnectionRouterRemoteIP=" + ipv4; } var dotnetEngine = StrideEditorSettings.UseCoreCLR.GetValue() ? " dotnet " : " mono "; if (!string.IsNullOrEmpty(display)) { display = " DISPLAY=" + display; } else { display = " DISPLAY=:0.0"; } cmdString = "bash -c 'source /etc/profile ; cd " + location + "/" + exePath.GetFileNameWithoutExtension() + ";" + display + connectionRouter + dotnetEngine + "./" + exePath.GetFileName() + "'"; cmd = sshClient.CreateCommand(cmdString); cmd.BeginExecute((callback) => { var res = cmd.Error; if (!string.IsNullOrEmpty(res)) { logger.Error(res); } else { res = cmd.Result; if (!string.IsNullOrEmpty(res)) { logger.Info(res); } } // Dispose of our resources as soon as we are done. cmd.Dispose(); sshClient.Dispose(); }); return(true); } } catch (Exception) { var message = Tr._p("Message", "Unable to launch {0} on host {1}"); logger.Error(string.Format(message, exePath, host)); } } return(false); }
public GameResult Connect() { Client.Connect(); return(new GameResult()); }
private async Task <string> SendCommandSSH(string command, bool silent = false) { // Handle SSH login connection if (_sshUsername.Equals(String.Empty)) { _sshUsername = command; _terminalData.Add("Enter password:"******"Connecting..."); // Attempt connection _sshClient = new SshClient(_sshServer, _sshUsername, _terminalWindow._password); try { _sshClient.Connect(); _terminalWindow._passwordMode = false; _terminalWindow._password = String.Empty; var modes = new Dictionary <Renci.SshNet.Common.TerminalModes, uint>(); _sshStream = _sshClient.CreateShellStream("bgtTerm", 255, 50, 800, 600, 1024, modes); _sshStream.DataReceived += async(object sender, ShellDataEventArgs e) => { if (_sshStream != null && _sshStream.CanRead) { byte[] buffer = new byte[2048]; int i = 0; if ((i = await _sshStream.ReadAsync(buffer, 0, buffer.Length)) != 1) { _terminalData.Add(_sshClient.ConnectionInfo.Encoding.GetString(buffer, 0, i)); } } }; if (_sshClient.IsConnected) { _terminalData.Add("Connected to " + _sshServer); } else { _terminalData.Add("There was a problem connecting."); _sshMode = false; _sshUsername = String.Empty; } } catch (Exception e) { _terminalData.Add(e.Message); } } // Handle SSH commands else { if (_sshClient.IsConnected) { try { _sshStream.WriteLine(command); } catch (Exception e) { _terminalData.Add(e.Message); } } else { _terminalData.Add("You are no longer connected to SSH. Exiting."); _sshMode = false; _sshUsername = String.Empty; } } return(null); }
public static void HandleInput(string input, object sender = null) { sender = Program.sender ?? sender; StartupForm form = null; if (sender != null) { form = (StartupForm)sender; form.prgBar.Style = ProgressBarStyle.Blocks; form.prgBar.Value = 0; } string[] args = input.Split(' '); switch (args[0].ToLower()) { #region "help" case "help": Help(); break; #endregion #region "connect" case "connect": if (form != null) { form.prgBar.Maximum = 6; } try { host = args[1]; if (form != null) { form.prgBar.Value++; } Settings.Default.host = host; if (form != null) { form.prgBar.Value++; } username = args[2]; if (form != null) { form.prgBar.Value++; } password = args[3]; if (form != null) { form.prgBar.Value++; } } catch (IndexOutOfRangeException) { } connection = new SshClient( host: host, username: username, password: password); if (form != null) { form.prgBar.Value++; } connection.Connect(); if (form != null) { form.prgBar.Value++; } if (sender == null) { Console.WriteLine($"Connected to {host}'s user {username} with password {new string('*', password.Length)}"); } username = "******"; password = "******"; break; #endregion #region "disconnect" case "disconnect": if (form != null) { form.prgBar.Maximum = 1; } connection.Disconnect(); if (form != null) { form.prgBar.Value++; } break; #endregion #region "shutdown" case "shutdown": if (form != null) { form.prgBar.Maximum = 3; } using (ShellStream shellStream = connection.CreateShellStream("xterm", 255, 50, 800, 600, 1024, new Dictionary <Renci.SshNet.Common.TerminalModes, uint>())) { shellStream.Write("sudo poweroff\n"); if (form != null) { form.prgBar.Value++; } shellStream.Expect($"[sudo] password for {username}:"); if (form != null) { form.prgBar.Value++; } shellStream.Write($"{password}\n"); if (form != null) { form.prgBar.Value++; } } break; #endregion #region "gui" case "gui": FormTools.RunInNewThread(new StartupForm(), true); break; #endregion #region "ssh" case "ssh": if (form != null) { form.prgBar.Maximum = 2; } using (ShellStream shellStream = connection.CreateShellStream("xterm", 255, 50, 800, 600, 2048, new Dictionary <Renci.SshNet.Common.TerminalModes, uint>())) { Console.WriteLine(); if (form != null) { form.prgBar.Value++; } Console.Write(shellStream.Read()); if (form != null) { form.prgBar.Value++; } if (form != null) { form.prgBar.Style = ProgressBarStyle.Marquee; } while (true) { string streamInput = Console.ReadLine(); if (streamInput == "exit") { break; } shellStream.WriteLine(streamInput); Console.Write(shellStream.Read().TrimStart(streamInput.ToCharArray())); } } break; #endregion #region motor case "motor": HardwareController.MoveMotor(address: args[1], action: args[2]); break; #endregion case "run": if (HardwareController.State) { HardwareController.MoveMotor(HardwareController.MotorList["outB"], MotorMoveActions.run_forever); } break; case "": break; default: throw new NotSupportedException($"Unsupported Command: {input}"); } }
private UploadModResult UploadMod(Action <double> progressCallback = null, Action <TaskbarItemProgressState> setTaskbarProgressState = null) { #region online fetch //Fetch current production manifest for mod (it may not exist) setTaskbarProgressState?.Invoke(TaskbarItemProgressState.Indeterminate); using var wc = new System.Net.WebClient(); try { CurrentActionText = M3L.GetString(M3L.string_checkingIfUpdaterServiceIsConfiguredForMod); string validationUrl = $@"{UpdaterServiceCodeValidationEndpoint}?updatecode={mod.ModClassicUpdateCode}&updatexmlname={mod.UpdaterServiceServerFolderShortname}.xml"; string isBeingServed = wc.DownloadStringAwareOfEncoding(validationUrl); if (string.IsNullOrWhiteSpace(isBeingServed) || isBeingServed != @"true") //we don't parse for bool because it might have a different text that is not specifically true or false. It might // have an error for example { //Not being served Log.Error(@"This mod is not configured for serving on the Updater Service. Please contact Mgamerz."); CurrentActionText = M3L.GetString(M3L.string_serverNotConfiguredForModContactMgamerz); HideChangelogArea(); return(UploadModResult.NOT_BEING_SERVED); } } catch (Exception ex) { Log.Error(@"Error validating mod is configured on updater service: " + ex.Message); CurrentActionText = M3L.GetString(M3L.string_interp_errorCheckingUpdaterServiceConfiguration, ex.Message); HideChangelogArea(); return(UploadModResult.ERROR_VALIDATING_MOD_IS_CONFIGURED); } #endregion #region get current production version to see if we should prompt user var latestVersionOnServer = OnlineContent.GetLatestVersionOfModOnUpdaterService(mod.ModClassicUpdateCode); if (latestVersionOnServer != null) { if (latestVersionOnServer >= mod.ParsedModVersion) { bool cancel = false; setTaskbarProgressState?.Invoke(TaskbarItemProgressState.Paused); Application.Current.Dispatcher.Invoke(delegate { // server is newer or same as version we are pushing var response = M3L.ShowDialog(mainwindow, M3L.GetString(M3L.string_interp_dialog_serverVersionSameOrNewerThanLocal, mod.ParsedModVersion, latestVersionOnServer), M3L.GetString(M3L.string_serverVersionSameOrNewerThanLocal), MessageBoxButton.YesNo, MessageBoxImage.Warning); if (response == MessageBoxResult.No) { CurrentActionText = M3L.GetString(M3L.string_uploadAbortedModOnServerIsSameOrNewerThanLocalOneBeingUploaded); HideChangelogArea(); cancel = true; return; } }); setTaskbarProgressState?.Invoke(TaskbarItemProgressState.Indeterminate); if (cancel) { return(UploadModResult.ABORTED_BY_USER_SAME_VERSION_UPLOADED); } } } #endregion #region mod variables //get refs var files = mod.GetAllRelativeReferences(true); files = files.OrderByDescending(x => new FileInfo(Path.Combine(mod.ModPath, x)).Length).ToList(); long totalModSizeUncompressed = files.Sum(x => new FileInfo(Path.Combine(mod.ModPath, x)).Length); #endregion #region compress and stage mod void updateCurrentTextCallback(string newText) { CurrentActionText = newText; } bool?canceledCheckCallback() => CancelOperations; CurrentActionText = M3L.GetString(M3L.string_compressingModForUpdaterService); progressCallback?.Invoke(0); setTaskbarProgressState?.Invoke(TaskbarItemProgressState.Normal); var lzmaStagingPath = OnlineContent.StageModForUploadToUpdaterService(mod, files, totalModSizeUncompressed, canceledCheckCallback, updateCurrentTextCallback, progressCallback); #endregion if (CancelOperations) { AbortUpload(); return(UploadModResult.ABORTED_BY_USER); } setTaskbarProgressState?.Invoke(TaskbarItemProgressState.Indeterminate); #region hash mod and build server manifest CurrentActionText = M3L.GetString(M3L.string_buildingServerManifest); long amountHashed = 0; ConcurrentDictionary <string, SourceFile> manifestFiles = new ConcurrentDictionary <string, SourceFile>(); Parallel.ForEach(files, new ParallelOptions() { MaxDegreeOfParallelism = Math.Max(1, Environment.ProcessorCount - 1) }, x => { if (CancelOperations) { return; } SourceFile sf = new SourceFile(); var sFile = Path.Combine(mod.ModPath, x); var lFile = Path.Combine(lzmaStagingPath, x + @".lzma"); sf.hash = Utilities.CalculateMD5(sFile); sf.lzmahash = Utilities.CalculateMD5(lFile); var fileInfo = new FileInfo(sFile); sf.size = fileInfo.Length; sf.timestamp = fileInfo.LastWriteTimeUtc.Ticks; sf.relativefilepath = x; sf.lzmasize = new FileInfo(lFile).Length; manifestFiles.TryAdd(x, sf); var done = Interlocked.Add(ref amountHashed, sf.size); CurrentActionText = M3L.GetString(M3L.string_buildingServerManifest) + $@" {Math.Round(done * 100.0 / totalModSizeUncompressed)}%"; }); if (CancelOperations) { AbortUpload(); return(UploadModResult.ABORTED_BY_USER); } //Build document XmlDocument xmlDoc = new XmlDocument(); XmlNode rootNode = xmlDoc.CreateElement(@"mod"); xmlDoc.AppendChild(rootNode); foreach (var mf in manifestFiles) { if (CancelOperations) { AbortUpload(); return(UploadModResult.ABORTED_BY_USER); } XmlNode sourceNode = xmlDoc.CreateElement(@"sourcefile"); var size = xmlDoc.CreateAttribute(@"size"); size.InnerText = mf.Value.size.ToString(); var hash = xmlDoc.CreateAttribute(@"hash"); hash.InnerText = mf.Value.hash; var lzmasize = xmlDoc.CreateAttribute(@"lzmasize"); lzmasize.InnerText = mf.Value.lzmasize.ToString(); var lzmahash = xmlDoc.CreateAttribute(@"lzmahash"); lzmahash.InnerText = mf.Value.lzmahash; var timestamp = xmlDoc.CreateAttribute(@"timestamp"); timestamp.InnerText = mf.Value.timestamp.ToString(); sourceNode.InnerText = mf.Key; sourceNode.Attributes.Append(size); sourceNode.Attributes.Append(hash); sourceNode.Attributes.Append(lzmasize); sourceNode.Attributes.Append(lzmahash); sourceNode.Attributes.Append(timestamp); rootNode.AppendChild(sourceNode); } if (CancelOperations) { AbortUpload(); return(UploadModResult.ABORTED_BY_USER); } foreach (var bf in mod.UpdaterServiceBlacklistedFiles) { if (CancelOperations) { AbortUpload(); return(UploadModResult.ABORTED_BY_USER); } var bfn = xmlDoc.CreateElement(@"blacklistedfile"); bfn.InnerText = bf; rootNode.AppendChild(bfn); } if (CancelOperations) { AbortUpload(); return(UploadModResult.ABORTED_BY_USER); } var updatecode = xmlDoc.CreateAttribute(@"updatecode"); updatecode.InnerText = mod.ModClassicUpdateCode.ToString(); rootNode.Attributes.Append(updatecode); var version = xmlDoc.CreateAttribute(@"version"); version.InnerText = mod.ParsedModVersion.ToString(); rootNode.Attributes.Append(version); var serverfolder = xmlDoc.CreateAttribute(@"folder"); serverfolder.InnerText = mod.UpdaterServiceServerFolder; rootNode.Attributes.Append(serverfolder); setTaskbarProgressState?.Invoke(TaskbarItemProgressState.Indeterminate); #endregion //wait to ensure changelog is set. while (ChangelogNotYetSet) { setTaskbarProgressState?.Invoke(TaskbarItemProgressState.Paused); if (CancelOperations) { AbortUpload(); return(UploadModResult.ABORTED_BY_USER); } CurrentActionText = M3L.GetString(M3L.string_waitingForChangelogToBeSet); Thread.Sleep(250); //wait for changelog to be set. } setTaskbarProgressState?.Invoke(TaskbarItemProgressState.Indeterminate); #region Finish building manifest var changelog = xmlDoc.CreateAttribute(@"changelog"); changelog.InnerText = ChangelogText; rootNode.Attributes.Append(changelog); using var stringWriter = new StringWriterWithEncoding(Encoding.UTF8); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = @" "; settings.Encoding = Encoding.UTF8; using var xmlTextWriter = XmlWriter.Create(stringWriter, settings); xmlDoc.WriteTo(xmlTextWriter); xmlTextWriter.Flush(); #endregion var finalManifestText = stringWriter.GetStringBuilder().ToString(); #region Connect to ME3Tweaks CurrentActionText = M3L.GetString(M3L.string_connectingToME3TweaksUpdaterService); Log.Information(@"Connecting to ME3Tweaks as " + Username); string host = @"ftp.me3tweaks.com"; string username = Username; string password = Settings.DecryptUpdaterServicePassword(); using SftpClient sftp = new SftpClient(host, username, password); sftp.Connect(); Log.Information(@"Connected to ME3Tweaks over SSH (SFTP)"); CurrentActionText = M3L.GetString(M3L.string_connectedToME3TweaksUpdaterService); var serverFolderName = mod.UpdaterServiceServerFolderShortname; //sftp.ChangeDirectory(LZMAStoragePath); //Log.Information(@"Listing files/folders for " + LZMAStoragePath); //var lzmaStorageDirectoryItems = sftp.ListDirectory(LZMAStoragePath); var serverModPath = LZMAStoragePath + @"/" + serverFolderName; bool justMadeFolder = false; if (!sftp.Exists(serverModPath)) { CurrentActionText = M3L.GetString(M3L.string_creatingServerFolderForMod); Log.Information(@"Creating server folder for mod: " + serverModPath); sftp.CreateDirectory(serverModPath); justMadeFolder = true; } var dirContents = sftp.ListDirectory(serverModPath).ToList(); Dictionary <string, string> serverHashes = new Dictionary <string, string>(); //Open SSH connection as we will need to hash files out afterwards. Log.Information(@"Connecting to ME3Tweaks Updater Service over SSH (SSH Shell)"); using SshClient sshClient = new SshClient(host, username, password); sshClient.Connect(); Log.Information(@"Connected to ME3Tweaks Updater Service over SSH (SSH Shell)"); if (!justMadeFolder && dirContents.Any(x => x.Name != @"." && x.Name != @"..")) { CurrentActionText = M3L.GetString(M3L.string_hashingFilesOnServerForDelta); Log.Information(@"Hashing existing files on server to compare for delta"); serverHashes = getServerHashes(sshClient, serverFolderName, serverModPath); } //Calculate what needs to be updated or removed from server List <string> filesToUploadToServer = new List <string>(); List <string> filesToDeleteOffServer = new List <string>(); //Files to upload foreach (var sourceFile in manifestFiles) { //find matching server file if (serverHashes.TryGetValue(sourceFile.Key.Replace('\\', '/') + @".lzma", out var matchingHash)) { //exists on server, compare hash if (matchingHash != sourceFile.Value.lzmahash) { //server hash is different! Upload new file. Log.Information(@"Server version of file is different from local: " + sourceFile.Key); filesToUploadToServer.Add(sourceFile.Key); } else { Log.Information(@"Server version of file is same as local: " + sourceFile.Key); } } else { Log.Information(@"Server does not have file: " + sourceFile.Key); filesToUploadToServer.Add(sourceFile.Key); } } //Files to remove from server foreach (var serverfile in serverHashes.Keys) { if (!manifestFiles.Any(x => (x.Key + @".lzma") == serverfile.Replace('/', '\\'))) { Log.Information(@"File exists on server but not locally: " + serverfile); filesToDeleteOffServer.Add(serverfile); } } #endregion long amountUploaded = 0, amountToUpload = 1; //Confirm changes if (filesToDeleteOffServer.Any() || filesToUploadToServer.Any()) { var text = M3L.GetString(M3L.string_interp_updaterServiceDeltaConfirmationHeader, mod.ModName); if (filesToUploadToServer.Any()) { text += M3L.GetString(M3L.string_nnFilesToUploadToServern) + @" " + string.Join('\n' + @" - ", filesToUploadToServer); //weird stuff to deal with localizer } if (filesToDeleteOffServer.Any()) { text += M3L.GetString(M3L.string_nnFilesToDeleteOffServern) + @" " + string.Join('\n' + @" - ", filesToDeleteOffServer); //weird stuff to deal with localizer } text += M3L.GetString(M3L.string_interp_updaterServiceDeltaConfirmationFooter); bool performUpload = false; Log.Information(@"Prompting user to accept server delta"); setTaskbarProgressState?.Invoke(TaskbarItemProgressState.Paused); Application.Current.Dispatcher.Invoke(delegate { performUpload = M3L.ShowDialog(mainwindow, text, M3L.GetString(M3L.string_confirmChanges), MessageBoxButton.OKCancel, MessageBoxImage.Exclamation) == MessageBoxResult.OK; }); setTaskbarProgressState?.Invoke(TaskbarItemProgressState.Indeterminate); if (performUpload) { Log.Information(@"User has accepted the delta, applying delta to server"); #region upload files //Create directories SortedSet <string> directoriesToCreate = new SortedSet <string>(); foreach (var f in filesToUploadToServer) { string foldername = f; var lastIndex = foldername.LastIndexOf(@"\"); while (lastIndex > 0) { foldername = foldername.Substring(0, lastIndex); directoriesToCreate.Add(foldername.Replace('\\', '/')); lastIndex = foldername.LastIndexOf(@"\"); } } #endregion //UploadDirectory(sftp, lzmaStagingPath, serverModPath, (ucb) => Debug.WriteLine("UCB: " + ucb)); var dirsToCreateOnServerSorted = directoriesToCreate.ToList(); dirsToCreateOnServerSorted.Sort((a, b) => a.Length.CompareTo(b.Length)); //short to longest so we create top levels first! int numFoldersToCreate = dirsToCreateOnServerSorted.Count(); int numDone = 0; if (dirsToCreateOnServerSorted.Count > 0) { CurrentActionText = M3L.GetString(M3L.string_creatingModDirectoriesOnServer); foreach (var f in dirsToCreateOnServerSorted) { var serverFolderStr = serverModPath + @"/" + f; if (!sftp.Exists(serverFolderStr)) { Log.Information(@"Creating directory on server: " + serverFolderStr); sftp.CreateDirectory(serverFolderStr); } else { Log.Information(@"Server folder already exists, skipping: " + serverFolderStr); } numDone++; CurrentActionText = M3L.GetString(M3L.string_creatingModDirectoriesOnServer) + @" " + Math.Round(numDone * 100.0 / numFoldersToCreate) + @"%"; } } //Upload files progressCallback?.Invoke(0); setTaskbarProgressState?.Invoke(TaskbarItemProgressState.Normal); amountToUpload = filesToUploadToServer.Sum(x => new FileInfo(Path.Combine(lzmaStagingPath, x + @".lzma")).Length); foreach (var file in filesToUploadToServer) { if (CancelOperations) { AbortUpload(); return(UploadModResult.ABORTED_BY_USER); } var fullPath = Path.Combine(lzmaStagingPath, file + @".lzma"); var serverFilePath = serverModPath + @"/" + file.Replace(@"\", @"/") + @".lzma"; Log.Information(@"Uploading file " + fullPath + @" to " + serverFilePath); long amountUploadedBeforeChunk = amountUploaded; using Stream fileStream = new FileStream(fullPath, FileMode.Open); sftp.UploadFile(fileStream, serverFilePath, true, (x) => { if (CancelOperations) { CurrentActionText = M3L.GetString(M3L.string_abortingUpload); return; } amountUploaded = amountUploadedBeforeChunk + (long)x; var uploadedHR = ByteSize.FromBytes(amountUploaded).ToString(@"0.00"); var totalUploadHR = ByteSize.FromBytes(amountToUpload).ToString(@"0.00"); if (amountToUpload > 0) { progressCallback?.Invoke(amountUploaded * 1.0 / amountToUpload); } CurrentActionText = M3L.GetString(M3L.string_interp_uploadingFilesToServerXY, uploadedHR, totalUploadHR); }); } setTaskbarProgressState?.Invoke(TaskbarItemProgressState.Indeterminate); if (CancelOperations) { AbortUpload(); return(UploadModResult.ABORTED_BY_USER); } //delete extra files int numdone = 0; foreach (var file in filesToDeleteOffServer) { CurrentActionText = M3L.GetString(M3L.string_interp_deletingObsoleteFiles, numdone, filesToDeleteOffServer.Count); var fullPath = $@"{LZMAStoragePath}/{serverFolderName}/{file}"; Log.Information(@"Deleting unused file off server: " + fullPath); sftp.DeleteFile(fullPath); numdone++; } //Upload manifest using var manifestStream = finalManifestText.ToStream(); var serverManifestPath = $@"{ManifestStoragePath}/{serverFolderName}.xml"; Log.Information(@"Uploading manifest to server: " + serverManifestPath); sftp.UploadFile(manifestStream, serverManifestPath, true, (x) => { var uploadedAmountHR = ByteSize.FromBytes(amountUploaded).ToString(@"0.00"); var uploadAmountTotalHR = ByteSize.FromBytes(amountToUpload).ToString(@"0.00"); CurrentActionText = M3L.GetString(M3L.string_uploadingUpdateManifestToServer) + $@"{uploadedAmountHR}/{uploadAmountTotalHR}"; }); } else { Log.Warning(@"User has declined uploading the delta. We will not change anything on the server."); CancelOperations = true; AbortUpload(); return(UploadModResult.ABORTED_BY_USER); } CurrentActionText = M3L.GetString(M3L.string_validatingModOnServer); Log.Information(@"Verifying hashes on server for new files"); var newServerhashes = getServerHashes(sshClient, serverFolderName, serverModPath); var badHashes = verifyHashes(manifestFiles, newServerhashes); if (badHashes.Any()) { CurrentActionText = M3L.GetString(M3L.string_someHashesOnServerAreIncorrectContactMgamerz); return(UploadModResult.BAD_SERVER_HASHES_AFTER_VALIDATION); } else { CurrentActionText = M3L.GetString(M3L.string_modUploadedToUpdaterService); return(UploadModResult.UPLOAD_OK); } } return(UploadModResult.ABORTED_BY_USER); }
/// <summary> /// Setup SSH Connection to given Host. /// </summary> /// <returns></returns> private bool SetupConnection() { bool retVal = true; if (_sshClient == null || !_sshClient.IsConnected) { try { //make sure a host exists, if not ask for one. if (!DataFiles.CheckHost()) { return(false); } //make sure an environment exists, if not ask for one. DataFiles.CheckEnv(); //make sure a username exists, if not ask for one. if (!DataFiles.CheckUser()) { return(false); } //make sure a password exists, if not ask for one. if (!DataFiles.CheckPass()) { return(false); } //display welcome text for application. General.ApplicationHeader(true); //let the user know what we are doing. Log.Verbose("\n\n Setting authentication...", ConsoleColor.Yellow); //account setup.. KeyboardInteractiveAuthenticationMethod kauth = new KeyboardInteractiveAuthenticationMethod(Defs.UserName); PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod(Defs.UserName, Defs.PassWord); kauth.AuthenticationPrompt += new EventHandler <AuthenticationPromptEventArgs>(HandleKeyEvent); //setup connection ConnectionInfo connectionInfo = new ConnectionInfo(Defs.HostName, Defs.Port, Defs.UserName, pauth, kauth); connectionInfo.Timeout = Defs.ConnectionTimeout; //pass connection data _sshClient = new SshClient(connectionInfo); //let the user know what we are doing. Log.Verbose("Attempting to connect...", ConsoleColor.Yellow); //connect to linux _sshClient.Connect(); //let the user know what we are doing. Log.Verbose("Connected, creating shell stream...", ConsoleColor.Green); //lets build out a stream that will each back what we request. var terminalMode = new Dictionary <TerminalModes, uint>(); //terminalMode.Add(TerminalModes.ECHO, 53); //create shell stream _shellStream = _sshClient.CreateShellStream("input", 255, 50, 400, 600, 4096, terminalMode); //keep track of remote directory. Can be useful, in case response of User@Server isn't configured to return. SendCommand("pwd -P", false); //it is possible that sometimes Messages come back on first connection to linux machine, before the information. if (Defs.DataContent.Length > 50) { Defs.DataContent.Clear(); SendCommand("pwd -P", false); } //break it down for prompt. string[] remote = Defs.DataContent.ToString().Replace(Environment.NewLine, "").Split('/'); Defs.DataContent.Clear(); //Don't set prompt if still showing message. if (string.Join("/", remote).Trim().Length < 40 && remote.Length <= 3) { Defs.PromptsRemoteDir = remote[remote.Length - 1].Trim(); } //if default Remote Path not setup, give it the current folder. don't set remote path if still showing message. if (Defs.RemotePath.Equals("/") && string.Join("/", remote).Trim().Length < 40 && remote.Length <= 3) { Defs.RemotePath = string.Join("/", remote).Trim(); } //save host and user to history. if (Defs.NewHost) { DataFiles.SaveHostHistory(); } //let the user know what we are doing. Log.Verbose("Successful Connection Established...\n", ConsoleColor.Green); //set the current folder as local path Directory.SetCurrentDirectory(Defs.LocalPath); Console.Title = $"{Defs.ConsoleTitle} -=[{Defs.UserName}@{Defs.HostName}]=-"; //clear screen and display new header General.ApplicationHeader(true); //let the user know what's configured. Log.Verbose($"Local Path has been set to {Defs.LocalPath}...", ConsoleColor.Yellow); Log.Verbose($"Remote Path has been set to {Defs.RemotePath}...\n", ConsoleColor.Yellow); Log.Verbose($"Change these paths with \"set-local\" and \"set-remote\"...\n\n", ConsoleColor.Yellow); } catch (Exception ex) { retVal = false; Log.Error($"Exception - {ex.Message}", 1); Log.Verbose("Press any key to continues.", ConsoleColor.White); Console.ReadKey(); //connection didn't work right, shut it down. Defs.Shutdown = true; } } return(retVal); }
protected override void ProcessRecord() { if (_keyfile.Equals("")) { //Username authentication //found a problem where domain name wasn't passed when using the format of {domain}\{username} //So, if the domain exists, prefix it properly //If using {username}@{domain}, this is not an issue string _UserNameMod = ""; if (_credential.GetNetworkCredential().Domain.Length > 0) { _UserNameMod = _credential.GetNetworkCredential().Domain + "\\" + _credential.GetNetworkCredential().UserName; } else { _UserNameMod = _credential.GetNetworkCredential().UserName; } var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_UserNameMod); foreach (var computer in _computername) { ConnectionInfo connectInfo; if (_proxyserver != "") { // Set the proper proxy type var ptype = ProxyTypes.Http; //WriteVerbose("A Proxy Server has been specified"); switch (_proxytype) { case "HTTP": ptype = ProxyTypes.Http; break; case "Socks4": ptype = ProxyTypes.Socks4; break; case "Socks5": ptype = ProxyTypes.Socks5; break; } var passconnectInfo = new PasswordAuthenticationMethod(_UserNameMod, _credential.GetNetworkCredential().Password); WriteVerbose("Connecting to " + computer + " with user " + _UserNameMod); connectInfo = new ConnectionInfo(computer, _port, _credential.GetNetworkCredential().UserName, ptype, _proxyserver, _proxyport, _proxycredential.GetNetworkCredential().UserName, _proxycredential.GetNetworkCredential().Password, kIconnectInfo, passconnectInfo); } else { // Connection info for Keyboard Interactive var passconnectInfo = new PasswordAuthenticationMethod(_UserNameMod, _credential.GetNetworkCredential().Password); connectInfo = new ConnectionInfo(computer, _port, _UserNameMod, passconnectInfo, 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; } } }; //Ceate instance of SSH Client with connection info var client = new SshClient(connectInfo); // Handle host key string computer1 = computer; client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e) { var sb = new StringBuilder(); foreach (var b in e.FingerPrint) { sb.AppendFormat("{0:x}:", b); } string fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1); //WriteVerbose("Key algorithm of " + client.ConnectionInfo.CurrentHostKeyAlgorithm); //WriteVerbose("Key exchange alhorithm " + client.ConnectionInfo.CurrentKeyExchangeAlgorithm); //WriteVerbose("Host key fingerprint: " + fingerPrint); if (_sshHostKeys.ContainsKey(computer1)) { if (_sshHostKeys[computer1] == fingerPrint) { //WriteVerbose("Fingerprint matched trusted fingerpring for host " + computer); e.CanTrust = true; } else { throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer1); } } 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 TrustedKeyManagement(); //WriteVerbose("Saving fingerprint " + fingerPrint + " for host " + computer); keymng.SetKey(computer1, fingerPrint); e.CanTrust = true; } else { e.CanTrust = false; } } }; // Set the connection timeout client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout); // Set Keepalive for connections client.KeepAliveInterval = TimeSpan.FromSeconds(_keepaliveinterval); // Connect to host using Connection info //WriteVerbose("Connecting to " + computer + " with user " + _UserNameMod); client.Connect(); WriteObject(SSHModuleHelper.AddToSSHSessionCollection(client, SessionState), true); } } else { //Use SSH Key for authentication WriteVerbose("Using SSH Key authentication for connection."); var fullPath = Path.GetFullPath(_keyfile); if (File.Exists(fullPath)) { foreach (var computer in _computername) { PrivateKeyConnectionInfo connectionInfo; if (_proxyserver != "") { // Set the proper proxy type var ptype = ProxyTypes.Http; //WriteVerbose("A Proxy Server has been specified"); switch (_proxytype) { case "HTTP": ptype = ProxyTypes.Http; break; case "Socks4": ptype = ProxyTypes.Socks4; break; case "Socks5": ptype = ProxyTypes.Socks5; break; } if (_credential.GetNetworkCredential().Password == "") { WriteVerbose("Using key with no passphrase."); var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath)); connectionInfo = new PrivateKeyConnectionInfo(computer, _port, _credential.GetNetworkCredential().UserName, sshkey); } else { WriteVerbose("Using key with passphrase."); var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), _credential.GetNetworkCredential().Password); if (_proxycredential.UserName == "") { connectionInfo = new PrivateKeyConnectionInfo(computer, _port, _credential.GetNetworkCredential().UserName, ptype, _proxyserver, _proxyport, sshkey); } else { connectionInfo = new PrivateKeyConnectionInfo(computer, _port, _credential.GetNetworkCredential().UserName, ptype, _proxyserver, _proxyport, _proxycredential.GetNetworkCredential().UserName, _proxycredential.GetNetworkCredential().Password, sshkey); } } } else { WriteVerbose("Using SSH Key authentication for connection."); if (_credential.GetNetworkCredential().Password == "") { WriteVerbose("Using key with no passphrase."); var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath)); connectionInfo = new PrivateKeyConnectionInfo(computer, _credential.GetNetworkCredential().UserName, sshkey); } else { WriteVerbose("Using key with passphrase."); var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), _credential.GetNetworkCredential().Password); connectionInfo = new PrivateKeyConnectionInfo(computer, _credential.GetNetworkCredential().UserName, sshkey); } } //Ceate instance of SSH Client with connection info var client = new SshClient(connectionInfo); // Handle host key string computer1 = computer; client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e) { var sb = new StringBuilder(); foreach (var b in e.FingerPrint) { sb.AppendFormat("{0:x}:", b); } string fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1); if (_sshHostKeys.ContainsKey(computer1)) { if (_sshHostKeys[computer1] == fingerPrint) { //WriteVerbose("Fingerprint matched trusted fingerpring for host " + computer); e.CanTrust = true; } else { throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer1); } } 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 TrustedKeyManagement(); //WriteVerbose("Saving fingerprint " + fingerPrint + " for host " + computer); keymng.SetKey(computer1, fingerPrint); e.CanTrust = true; } else { e.CanTrust = false; } } }; // Set the connection timeout client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout); // Set Keepalive for connections client.KeepAliveInterval = TimeSpan.FromSeconds(_keepaliveinterval); // Connect to host using Connection info client.Connect(); WriteObject(SSHModuleHelper.AddToSSHSessionCollection(client, SessionState), true); } } else { throw new FileNotFoundException("Key file " + fullPath + " was not found."); } } }
public bool TrainData(string cfgPath) { try { var pk = new PrivateKeyFile(ApplicationConstant.PrivateKeyFilePath); var url = CommonService.GetUrlApi(); var trainDir = ServerTrainConstant.TrainPath; var darknetDir = ServerTrainConstant.DarknetPath; var datetime = DateTime.Now.ToString(ApplicationConstant.DatetimeFormat).Replace("/", "").Replace(" ", "").Replace(":", ""); var weightPath = $@"backup/{UserLoginModel.User.Id}/{datetime}"; var logPath = $@"backup/{UserLoginModel.User.Id}/{datetime}/train.log"; var lossPath = $@"backup/{UserLoginModel.User.Id}/{datetime}/chart.png"; var cfgFileName = Path.GetFileName(cfgPath); var trainServer = CommonService.GetUrlApiTrainServer(); using (var client = new ScpClient(trainServer, 22, ServerTrainConstant.Username, pk)) { client.Connect(); using (var file = File.OpenRead(cfgPath)) { client.Upload(file, $"{darknetDir}/yolo.cfg"); } client.Disconnect(); } using (var client = new SshClient(trainServer, ServerTrainConstant.Username, pk)) { client.Connect(); var createIsTrainCommand = client.CreateCommand($@"cd {trainDir} && echo ""1"" > istrain.txt"); createIsTrainCommand.Execute(); var createDataCommand = client.CreateCommand($@"cd {trainDir} && mkdir -pm 0777 data && python3 label.py"); createDataCommand.Execute(); var createDataTextCommand = client.CreateCommand($@"cd {trainDir} && cd .. && python3 traindata.py"); createDataTextCommand.Execute(); var createWeightsPath = client.CreateCommand($@"cd {darknetDir} && mkdir -pm 0777 {weightPath}"); createWeightsPath.Execute(); var createCfgFile = client.CreateCommand($@"cd {darknetDir} && python3 create_cfg.py --backup {weightPath}"); createCfgFile.Execute(); //var guid = Guid.NewGuid().ToString("screen -dm bash -c 'cd /home/dev/darknet; python3 sendnoti.py --id 35 --authen eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IlF3alZLbnF0WXhUMGhvQWJsVzVzOTVJWlJaQTMiLCJleHAiOjE2NDkyNDYxMzN9.9MpdU7fw2QUUQt1-1KtmKGugYPpNguY2vqkaGQMqBWc --url http://192.168.0.4:8080/api'"); //var command = client.CreateCommand($@"screen -dm bash -c 'cd /home/dev/darknet; ./darknet detector train yolo.data yolo.cfg -dont_show'; curl --location --request POST --header 'Authorization: {UserLoginModel.AccessToken}' --header 'Content-Type: application/json' --data-raw '{{""user"":{UserLoginModel.User.Id},""message"":""Train complete"",""url"":""backup""}}' ""{url}/users/30/notifications"""); var command = client.CreateCommand($@"screen -dm bash -c 'cd {darknetDir};" + $"./darknet detector train yolo.data yolo.cfg -dont_show > {logPath};" + $"cp chart.png {lossPath};" + $"python3 sendnoti.py --id {UserLoginModel.User.Id} --authen {UserLoginModel.AccessToken} --url {url} --backup {weightPath}/yolo_final.weights --log_path {logPath} --loss_function_path {lossPath};" + $"cd {trainDir}; rm -r istrain.txt; rm -r admin '"); //var command = client.CreateCommand($@"screen -dm bash -c 'cd /home/dev/darknet; python sendnoti.py ""$--id {UserLoginModel.User.Id}"" --authen {UserLoginModel.AccessToken} --url {url}"); command.Execute(); client.Disconnect(); } } catch (Exception e) { ExceptionLogging.SendErrorToText(e, nameof(this.TrainData), nameof(DataSetService)); return(false); } return(true); }
public static void Main() { int sampleFrequency = 5; int counter = 0; int logSize; int usageLogSize; int powerLogSize; int iterate = 1; int beforePause = 10000; int afterPause = beforePause; string line; string host = "10.0.0.2"; string userName = "******"; string password = "******"; string serialPortAddress = "COM3"; string[] benchmarks = new string[] { "./NVIDIA_CUDA-6.5_Samples/bin/armv7l/linux/release/gnueabihf/scan" /*"cd darknet-2/ && ./image_yolov3.sh"*//*, "./shooting/build/shooting.x"*/ }; List <double> powerLog; StreamReader boardLog; // creating local log file (for power consumption) powerLogFile = new System.IO.StreamWriter("powerdata.log"); // creating serial connection SerialPort serialPort = new SerialPort(serialPortAddress); serialPort.BaudRate = 115200; serialPort.Parity = Parity.None; serialPort.StopBits = StopBits.One; serialPort.DataBits = 8; serialPort.Handshake = Handshake.None; serialCounter = 0; serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); Console.WriteLine("connecting to serial port " + serialPortAddress); serialPort.Open(); Console.WriteLine("connected (sync)"); previousSampleTime = DateTime.Now; Console.WriteLine("connecting to board on " + host + " under user " + userName); // // board connection // Task.Factory.StartNew(() => { using (var client = new SshClient(host, userName, password)) { // saving logs on tk1 client.Connect(); Console.WriteLine("connected (async)"); Console.WriteLine("started to store log data on board at {0:mm.ss.ffffff}", DateTime.Now); client.RunCommand( "echo " + password + " | sudo -S ./tegrastats " + ((int)(1000 * (1.0 / sampleFrequency))).ToString() + " --logfile usagedata.log" ); client.Disconnect(); } }); // // multimeter connection // Task.Factory.StartNew(() => { while (true) { if (serialPort.IsOpen) { serialPort.WriteLine("VAL1?"); } System.Threading.Thread.Sleep((int)(1000.0 / sampleFrequency)); } }); if (beforePause > 0) { System.Threading.Thread.Sleep(afterPause); } do { iterate--; counter = 0; Task[] tasks = new Task[benchmarks.Length]; foreach (string benchmark in benchmarks) { // // running benchmarks // tasks[counter] = Task.Factory.StartNew(() => { Console.WriteLine("running benchmark " + benchmark); using (var client = new SshClient(host, userName, password)) { // calling benchmark client.Connect(); var output = client.RunCommand(benchmark); // awaiting termination Console.BackgroundColor = ConsoleColor.DarkGreen; Console.Write(output.Result); Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine("benchmark " + benchmark + " done"); client.Disconnect(); } }); counter++; } Task.WaitAll(tasks); } while (iterate != 0); if (afterPause > 0) { // after pause for additional logging Console.WriteLine("logging another " + afterPause + " ms"); System.Threading.Thread.Sleep(afterPause); } // // terminating / deleting // using (var client = new SshClient(host, userName, password)) { // stopping logs on tk1 client.Connect(); var output = client.RunCommand("echo " + password + " | sudo -S ./tegrastats --stop"); Console.BackgroundColor = ConsoleColor.DarkGreen; Console.Write(output.Result); Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine("log on board terminated at {0:mm.ss.ffffff}", DateTime.Now); client.Disconnect(); } serialPort.Close(); powerLogFile.Close(); Console.WriteLine("log from multimiter terminated at {0:mm.ss.ffffff}", DateTime.Now); // downloading data from board using (ScpClient client = new ScpClient(host, userName, password)) { Console.WriteLine("retriving data from board"); client.Connect(); using (Stream localFile = File.Create("usagedata.log")) { client.Download("usagedata.log", localFile); } Console.WriteLine("retrived"); } using (var client = new SshClient(host, userName, password)) { // deleting log on board client.Connect(); var output1 = client.RunCommand("echo " + password + " | sudo chmod 777 usagedata.log"); var output2 = client.RunCommand("rm usagedata.log"); Console.BackgroundColor = ConsoleColor.DarkGreen; Console.Write(output1.Result); Console.Write(output2.Result); Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine("log on board deleted"); client.Disconnect(); } // // processing logs // Console.WriteLine("processing data"); usageLogSize = File.ReadLines(@"usagedata.log").Count(); powerLogSize = File.ReadLines(@"powerdata.log").Count(); logSize = usageLogSize > powerLogSize ? powerLogSize : usageLogSize; // ?? if (Math.Abs(File.ReadLines(@"usagedata.log").Count() - File.ReadLines(@"powerdata.log").Count()) > sampleFrequency * 8) { Console.BackgroundColor = ConsoleColor.DarkRed; Console.WriteLine("data from board and multimeter are unconsistent"); Console.BackgroundColor = ConsoleColor.Black; } counter = 0; powerLog = new List <double>(); boardLog = new StreamReader(@"powerdata.log"); while ((line = boardLog.ReadLine()) != null) { counter++; // ?? if (powerLogSize - usageLogSize - (counter) > 0) { continue; } double power = double.Parse(line, CultureInfo.InvariantCulture); powerLog.Add(power); } counter = 0; boardLog = new StreamReader(@"usagedata.log"); // creating local log file (for power consumption in A) logFile = new System.IO.StreamWriter("data.log"); while ((line = boardLog.ReadLine()) != null && counter < powerLogSize) { string[] stringLine = line.Split(' '); string[] cpuUsage = stringLine[5].Split('@')[0].TrimStart('[').TrimEnd(']').Split(','); double cpuUsageCore1 = double.Parse(cpuUsage[0] == "off" ? "0" : cpuUsage[0].TrimEnd('%')); double cpuUsageCore2 = double.Parse(cpuUsage[1] == "off" ? "0" : cpuUsage[1].TrimEnd('%')); double cpuUsageCore3 = double.Parse(cpuUsage[2] == "off" ? "0" : cpuUsage[2].TrimEnd('%')); double cpuUsageCore4 = double.Parse(cpuUsage[3] == "off" ? "0" : cpuUsage[3].TrimEnd('%')); double gpuUsage = double.Parse(stringLine[13].Split('%')[0]); // time[relative] power[W*10] core1[%] core2 core3 core4 gpu[%] logFile.WriteLine(String.Format(CultureInfo.InvariantCulture, "{0} {1:E} {2:E} {3:E} {4:E} {5:E} {6:E}", counter, powerLog.ElementAt(counter) * 12 * 10, cpuUsageCore1, cpuUsageCore2, cpuUsageCore3, cpuUsageCore4, gpuUsage )); counter++; } logFile.Close(); Console.WriteLine("data processed see data.log"); Console.WriteLine("press any key to continue..."); Console.WriteLine(); Console.ReadKey(); }
public void Test_PortForwarding_Local_Stop_Hangs_On_Wait() { using (var client = new SshClient(Resources.HOST, Int32.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); var port1 = new ForwardedPortLocal("localhost", 8084, "www.google.com", 80); client.AddForwardedPort(port1); port1.Exception += delegate(object sender, ExceptionEventArgs e) { Assert.Fail(e.Exception.ToString()); }; port1.Start(); bool hasTestedTunnel = false; System.Threading.ThreadPool.QueueUserWorkItem(delegate(object state) { try { var url = "http://www.google.com/"; Debug.WriteLine("Starting web request to \"" + url + "\""); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Assert.IsNotNull(response); Debug.WriteLine("Http Response status code: " + response.StatusCode.ToString()); response.Close(); hasTestedTunnel = true; } catch (Exception ex) { Assert.Fail(ex.ToString()); } }); // Wait for the web request to complete. while (!hasTestedTunnel) { System.Threading.Thread.Sleep(1000); } try { // Try stop the port forwarding, wait 3 seconds and fail if it is still started. System.Threading.ThreadPool.QueueUserWorkItem(delegate(object state) { Debug.WriteLine("Trying to stop port forward."); port1.Stop(); Debug.WriteLine("Port forwarding stopped."); }); System.Threading.Thread.Sleep(3000); if (port1.IsStarted) { Assert.Fail("Port forwarding not stopped."); } } catch (Exception ex) { Assert.Fail(ex.ToString()); } client.Disconnect(); Debug.WriteLine("Success."); } }
protected BaseClient CreateConnection(string computer) { 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.Request.Contains("PASSCODE") || prompt.Request.Contains("password")) { prompt.Response = Credential.GetNetworkCredential().Password; } } }; break; case "Key": WriteVerbose("Using SSH Key authentication for connection (file)."); 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; } //Create instance of SSH Client with connection info BaseClient client; switch (Protocol) { case PoshSessionType.SFTP: client = new SftpClient(connectInfo); break; case PoshSessionType.SCP: client = new ScpClient(connectInfo); break; default: client = new SshClient(connectInfo); break; } // Handle host key if (Force) { WriteWarning("Host key is not being verified since Force switch is used."); } else { var savedHostKey = KnownHost.GetKey(computer); // filter out unsupported hostkeynames if (savedHostKey != default && !string.IsNullOrEmpty(savedHostKey.HostKeyName)) { foreach (var keyName in connectInfo.HostKeyAlgorithms.Keys.ToArray()) { if (keyName != savedHostKey.HostKeyName) { connectInfo.HostKeyAlgorithms.Remove(keyName); } } } 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(e.HostKeyName + " Fingerprint for " + computer1 + ": " + fingerPrint); } if (savedHostKey != default) { e.CanTrust = savedHostKey.Fingerprint == fingerPrint && (savedHostKey.HostKeyName == e.HostKeyName || savedHostKey.HostKeyName == string.Empty); if (MyInvocation.BoundParameters.ContainsKey("Verbose")) { Host.UI.WriteVerboseLine("Fingerprint " + (e.CanTrust ? "" : "not ") + "matched trusted " + savedHostKey.HostKeyName + " fingerprint for host " + computer1); } } else { if (ErrorOnUntrusted) { e.CanTrust = false; } else { if (!AcceptKey) { var choices = new Collection <ChoiceDescription> { new ChoiceDescription("Y"), new ChoiceDescription("N") }; e.CanTrust = 0 == Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1); } else // User specified he would accept the key so we can just add it to our list. { e.CanTrust = true; } if (e.CanTrust) { if (!KnownHost.SetKey(computer1, e.HostKeyName, fingerPrint)) { Host.UI.WriteWarningLine("Host key is not saved to store."); } } } } }; } try { // Set the connection timeout client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(ConnectionTimeout); // Set Keepalive for connections client.KeepAliveInterval = TimeSpan.FromSeconds(KeepAliveInterval); // Connect to host using Connection info client.Connect(); return(client); } catch (SshConnectionException e) { ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client); WriteError(erec); } catch (SshOperationTimeoutException e) { ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationTimeout, client); WriteError(erec); } catch (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); } return(default);
public async Task <IActionResult> UploadFiles(List <IFormFile> files) { if (files == null || files.Count == 0) { return(Content("files not selected")); } foreach (var file in files) { var path = Path.Combine( Directory.GetCurrentDirectory(), "upload", file.GetFilename()); using (var stream = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(stream); } } SftpClient client_sftp = new SftpClient("192.168.56.103", "Szymon", "qwerty"); SshClient client_ssh = new SshClient("192.168.56.103", "Szymon", "qwerty"); SftpClient client_sftp2 = new SftpClient("192.168.56.101", "Szymon", "qwerty"); SshClient client_ssh2 = new SshClient("192.168.56.101", "Szymon", "qwerty"); string localDirectoryUpload = @"C:\Users\szymo\Desktop\WebApplication1\WebApplication1\upload"; string localDirectoryDownload = @"C:\Users\szymo\Desktop\WebApplication1\tmp\Scan1.txt"; string localDirectoryDownload2 = @"C:\Users\szymo\Desktop\WebApplication1\tmp\Scan2.txt"; string localPatternUpload = "*.mp3"; string uploadDirectory = "/C:/Users/Szymon/Desktop/Upload/"; string downloadDirectory = "/C:/Users/Szymon/Desktop/Scan/Scan.txt"; string[] filesUpload = Directory.GetFiles(localDirectoryUpload, localPatternUpload); client_sftp.Connect(); foreach (string file in filesUpload) { using (Stream inputStream = new FileStream(file, FileMode.Open)) { client_sftp.UploadFile(inputStream, uploadDirectory + Path.GetFileName(file)); } } System.IO.DirectoryInfo di = new DirectoryInfo(localDirectoryUpload); client_ssh.Connect(); client_ssh.RunCommand("C:/Users/Szymon/Desktop/Scan.bat"); using (Stream fileStream = System.IO.File.OpenWrite(localDirectoryDownload)) { client_sftp.DownloadFile(downloadDirectory, fileStream); } client_ssh.Disconnect(); client_sftp.Disconnect(); client_sftp2.Connect(); client_ssh2.Connect(); foreach (string file in filesUpload) { using (Stream inputStream = new FileStream(file, FileMode.Open)) { client_sftp2.UploadFile(inputStream, uploadDirectory + Path.GetFileName(file)); } } foreach (FileInfo file in di.GetFiles()) { file.Delete(); } client_ssh2.RunCommand("C:/Users/Szymon/Desktop/Scan.bat"); using (Stream fileStream = System.IO.File.OpenWrite(localDirectoryDownload2)) { client_sftp2.DownloadFile(downloadDirectory, fileStream); } client_sftp2.Disconnect(); client_ssh2.Disconnect(); return(RedirectToAction("Index", "AddData")); // return RedirectToAction("Files"); }
public bool TransferData(ICollection <ImageFileModel> data, ICollection <LabelFileModel> labelData, bool isClearData = false) { try { var pk = new PrivateKeyFile(ApplicationConstant.PrivateKeyFilePath); var folder = DateTime.Now.ToString(ApplicationConstant.DatetimeFormat); folder = folder.Replace("/", "").Replace(" ", "").Replace(":", ""); var dataFolder = $"train/admin/{UserLoginModel.User.Id}/data/{folder}"; var labelFolder = $"train/admin/{UserLoginModel.User.Id}/label/{folder}"; var dataDir = $@"{ServerTrainConstant.DarknetPath}"; var trainDir = ServerTrainConstant.TrainPath; var trainServer = CommonService.GetUrlApiTrainServer(); using (var client = new SshClient(trainServer, ServerTrainConstant.Username, pk)) { client.Connect(); if (isClearData) { var deleteDataCommand = client.CreateCommand($@"cd {trainDir}; rm -r admin "); deleteDataCommand.Execute(); } var command = client.CreateCommand($@"cd {dataDir} && mkdir -pm 0777 {dataFolder} && mkdir -pm 0777 {labelFolder}"); command.Execute(); var result = command.Result; Console.WriteLine(result); client.Disconnect(); } using (var client = new ScpClient(trainServer, 22, ServerTrainConstant.Username, pk)) { client.Connect(); foreach (var item in data) { using (var file = File.OpenRead(item.Path)) { client.Upload(file, $"{dataDir}/{dataFolder}/{Path.GetFileName(item.Path)}"); } } foreach (var item in labelData) { using (var file = File.OpenRead(item.Path)) { client.Upload(file, $"{dataDir}/{labelFolder}/{Path.GetFileName(item.Path)}"); } } client.Disconnect(); } } catch { return(false); } return(true); }
static void Main(string[] args) { //Read parameter value from appconfig. string iIP = ConfigurationManager.AppSettings["IP"]; string iUser = ConfigurationManager.AppSettings["User"]; string iPassword = ConfigurationManager.AppSettings["Password"]; string ifilename = "test"; string storageaccount = ConfigurationManager.AppSettings["storageaccount"]; string storagekey = ConfigurationManager.AppSettings["storagekey"]; //create a guid which will be used as the processid Guid g = Guid.NewGuid(); //buiding parameter value for the custom script. //Note calling activate.sh string activatecmd = string.Format( "/home/lkmsft/connector/activate.sh {0} {1} '{2}' '{3}' '{4}' '{5}' ", "/home/lkmsft/connector/testffmpeg/testffmpeg.sh", g, "https://www.wowza.com/downloads/images/Butterfly_HD_1080p.mp4", ifilename, storageaccount, storagekey); SshCommand rt; Console.WriteLine("process id" + g.ToString()); //connect to the VM using (var client = new SshClient(iIP, iUser, iPassword)) { client.Connect(); //run command activate.sh rt = client.RunCommand(activatecmd); Console.WriteLine(rt); //now check status buy calling wait.sh. //keep checking while return status is 0 means still processing. //stop if return code is 1 (finished with error) or 2 (finished with success). do { rt = client.RunCommand("/home/lkmsft/connector/wait.sh " + g); Console.WriteLine(rt.ExitStatus); Console.WriteLine(rt.Result); System.Threading.Thread.Sleep(5000); } while (rt.ExitStatus == 0); if (rt.ExitStatus == 1) { Console.WriteLine("error"); client.RunCommand("/home/lkmsft/connector/clean.sh " + g); } else { Console.WriteLine("process complete"); client.RunCommand("/home/lkmsft/connector/clean.sh " + g); Console.WriteLine("CLean up complete"); } client.Disconnect(); Console.WriteLine("this is my process id " + g); Console.ReadLine(); } }
public ReturnBox TestSsh(Drive drive) { ReturnBox r = new ReturnBox(); if (!File.Exists(drive.AppKey)) { r.MountStatus = MountStatus.BAD_KEY; r.Error = String.Format($"Password is required to connnect to {drive.CurrentUser}@{drive.Host}:{drive.CurrentPort}.\nSSH keys will be generated and used in future conections."); return(r); } try { r.MountStatus = MountStatus.UNKNOWN; var pk = new PrivateKeyFile(drive.AppKey); var keyFiles = new[] { pk }; SshClient client = new SshClient(drive.Host, drive.CurrentPort, drive.CurrentUser, keyFiles); client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(TIMEOUT); client.Connect(); client.Disconnect(); r.MountStatus = MountStatus.OK; r.Success = true; } catch (Exception ex) { r.Error = ex.Message; if (ex is SshAuthenticationException) { r.MountStatus = MountStatus.BAD_KEY; } else if (ex is SocketException || ex is SshConnectionException || ex is InvalidOperationException || ex.Message.Contains("milliseconds")) { r.Error = "Host does not respond"; r.MountStatus = MountStatus.BAD_HOST; } else if (ex.Message.Contains("OPENSSH")) { // openssh keys not supported by ssh.net yet string args = $"-i \"{drive.AppKey}\" -p {drive.CurrentPort} -oPasswordAuthentication=no -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oBatchMode=yes -oConnectTimeout={TIMEOUT} { drive.CurrentUser}@{drive.Host} \"echo ok\""; var r1 = RunLocal("ssh.exe", args, TIMEOUT); var ok = r1.Output.Trim() == "ok"; if (ok) { r.MountStatus = MountStatus.OK; r.Error = ""; r.Success = true; } else { r.MountStatus = MountStatus.BAD_KEY; r.Error = r1.Error; } } } return(r); }
private static async Task Backup(BackupParams backupParams) { if (backupParams.Sources.Length == 0) { Console.WriteLine("Source folder is not specified"); return; } /*if (!Directory.Exists(backupParams.Source)) * { * Console.WriteLine("Source folder does not exist"); * return; * }*/ var targetWin = backupParams.RemoteRootWin; if (string.IsNullOrEmpty(targetWin)) { Console.WriteLine("Target folder is not specified"); return; } _logFileName = backupParams.LogFile; IHardLinkHelper hardLinkHelper; var networkConnection = Helpers.GetDummyDisposable(); SshClient sshClient = null; if (!backupParams.IsSshDefined) { hardLinkHelper = new WinHardLinkHelper(); } else { Console.WriteLine($"Connecting to {backupParams.SshLogin}@{backupParams.SshHost}:{backupParams.SshPort}..."); var ci = new ConnectionInfo(backupParams.SshHost, backupParams.SshPort ?? throw new Exception("SSH port not defined"), backupParams.SshLogin, new PasswordAuthenticationMethod(backupParams.SshLogin, backupParams.SshPassword)); sshClient = new SshClient(ci); sshClient.Connect(); hardLinkHelper = new NetShareSshHardLinkHelper(backupParams.RemoteRootWin, backupParams.RemoteRootUnix, sshClient); networkConnection = new NetworkConnection($@"\\{backupParams.SshHost}", new NetworkCredential(backupParams.SshLogin, backupParams.SshPassword)); } using (networkConnection) using (sshClient ?? Helpers.GetDummyDisposable()) { if (!Directory.Exists(targetWin)) { Console.WriteLine("Target folder does not exist"); return; } try { var testFile = Path.Combine(targetWin, "write_access_test.txt"); if (File.Exists(testFile)) { File.Delete(testFile); } File.WriteAllText(testFile, "Write access test file"); File.Delete(testFile); } catch (Exception e) { Console.WriteLine("Failed to write in target directory:\r\n" + e.Message); return; } await BackupHardLinks(backupParams, hardLinkHelper, sshClient); } }
/// <summary> /// Goes through list of files and sends encode command /// </summary> private void worker_DoEncode(object sender, DoWorkEventArgs e) { bCurrentlyEncoding = true; for (int i = 0; i < lstFilesToEncode.Count;) { Globals.currentFileBeingEncoded = lstFilesToEncode[i].Name; bool bImport = selectedPreset.IsImport; string strPreset; if (bImport) { strPreset = $"{xmlConfig.OutputDirectory}/{selectedPreset.PresetName}"; } else { strPreset = selectedPreset.PresetName; } HandbrakeCommand cmd = new HandbrakeCommand(Globals.BuildInputString(lstFilesToEncode[i], xmlConfig), Globals.BuildOutputString(lstFilesToEncode[i], xmlConfig), strPreset, bImport); try { using (var client = new SshClient(xmlConfig.PlexIP, xmlConfig.Username, strPassword)) { client.Connect(); string strCurrentFile = lstFilesToEncode[i].Name; if (!DoLinuxCommand(cmd.ToString(), client)) { Dispatcher.BeginInvoke(new Action(delegate { txtOutput.AppendText($"FAILED TO ENCODE {strCurrentFile} | ABORTING\n"); txtOutput.ScrollToEnd(); })); break; } else { DispatcherOperation disOp = Dispatcher.BeginInvoke(new Action(delegate { txtOutput.AppendText($"{strCurrentFile} FINISHED ENCODING\n"); if (lstFilesToEncode.Count > 0) { lstFilesToEncode.RemoveAt(i); } prgEncode.Value = 0; })); while (disOp.Status != DispatcherOperationStatus.Completed) { ; } } client.Disconnect(); } } catch (Exception ex) { MessageBox.Show($"ERROR: {ex}", "ERROR", MessageBoxButton.OK); } if (workerEncode.CancellationPending) { return; } } return; }
void SSHConnect(object sender, DoWorkEventArgs e) { if (_MainForm.textBox1.Text == string.Empty) { MessageBox.Show("No hostname specified"); return; } if (_MainForm.textBox2.Text == string.Empty) { MessageBox.Show("No username specified"); } if (!_MainForm.radioButton1.Checked && !_MainForm.radioButton2.Checked) { MessageBox.Show("No authentication specified"); return; } try { using (var client = new SshClient(_MainForm.textBox1.Text, _MainForm.textBox2.Text, _MainForm.getAuth())) { var ProxyPort = new ForwardedPortDynamic("127.0.0.1", 1080); _MainForm.WriteLog("Attempting connection to " + _MainForm.textBox1.Text); client.Connect(); if (client.IsConnected) { //Connect isConnected = true; _MainForm.WriteLog("Connected"); _MainForm.WriteLog("Adding SOCKS port: " + ProxyPort.BoundHost + ":" + ProxyPort.BoundPort); client.AddForwardedPort(ProxyPort); ProxyPort.Start(); _MainForm.WriteLog("Ready for connections"); _MainForm.ConnectionButton.Text = "Disconnect"; _MainForm.textBox1.ReadOnly = true; _MainForm.textBox2.ReadOnly = true; _MainForm.textBox3.ReadOnly = true; _MainForm.radioButton1.Enabled = false; _MainForm.radioButton2.Enabled = false; _MainForm.textBox4.ReadOnly = true; _MainForm.textBox5.ReadOnly = true; _MainForm.button3.Enabled = false; _MainForm.WriteLog("Setting windows proxy"); _MainForm.WriteLog("Connected"); RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true); registry.SetValue("ProxyEnable", 1); registry.SetValue("ProxyServer", "socks=127.0.0.1:1080"); settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0); refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0); ConnectionButton.Enabled = true; while (isConnected) { Thread.Sleep(1000); } //Disconnect _MainForm.WriteLog("Setting windows proxy to default values"); WriteLog("Disconnecting"); registry.SetValue("ProxyEnable", 0); registry.DeleteValue("ProxyServer"); settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0); refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0); ProxyPort.Stop(); client.RemoveForwardedPort(ProxyPort); client.Disconnect(); Thread.Sleep(500); WriteLog("Disconnected"); _MainForm.textBox1.ReadOnly = false; _MainForm.textBox2.ReadOnly = false; _MainForm.textBox3.ReadOnly = false; _MainForm.radioButton1.Enabled = true; _MainForm.radioButton2.Enabled = true; _MainForm.textBox4.ReadOnly = false; _MainForm.textBox5.ReadOnly = false; _MainForm.button3.Enabled = true; ConnectionButton.Enabled = true; _MainForm.ConnectionButton.Text = "Connect"; } } } catch (Exception ex) { _MainForm.WriteLog(ex.Message); MessageBox.Show(ex.Message); _MainForm.textBox1.ReadOnly = false; _MainForm.textBox2.ReadOnly = false; _MainForm.textBox3.ReadOnly = false; _MainForm.radioButton1.Enabled = true; _MainForm.radioButton2.Enabled = true; _MainForm.textBox4.ReadOnly = false; _MainForm.textBox5.ReadOnly = false; _MainForm.button3.Enabled = true; ConnectionButton.Enabled = true; _MainForm.ConnectionButton.Text = "Connect"; } }
/// <summary> /// Continually update all VM status fields /// </summary> private static void StatusUpdater() { var lastProgramType = programType; SshClient client = null; while (updatingStatus) { if (programType != lastProgramType) { lastProgramType = programType; if (client != null) { try { client.Disconnect(); client.Dispose(); client = null; } catch (Exception e) { Debug.Log(e.ToString()); } } } try { if (client == null) { client = new SshClient(DEFAULT_HOST, lastProgramType == UserProgram.Type.JAVA ? DEFAULT_SSH_PORT_JAVA : DEFAULT_SSH_PORT_CPP, USER, PASSWORD); client.Connect(); } VMConnected = client.IsConnected; if (VMConnected) { frcUserProgramPresent = client.RunCommand(CHECK_EXISTS_COMMAND).ExitStatus == 0; if (frcUserProgramPresent) { isRunningRobotCodeRunner = client.RunCommand(CHECK_RUNNER_RUNNING_COMMAND).ExitStatus == 0; isRunningRobotCode = client.RunCommand(CHECK_RUNNING_COMMAND).ExitStatus == 0; if (isRunningRobotCode && !EmulatorNetworkConnection.Instance.IsConnectionOpen()) { EmulatorNetworkConnection.Instance.OpenConnection(); } if (isRunningRobotCode) { Thread.Sleep(3000); // ms } else { Thread.Sleep(1000); // ms } } else { isTryingToRunRobotCode = false; isRunningRobotCodeRunner = false; isRunningRobotCode = false; Thread.Sleep(1000); // ms } } else { frcUserProgramPresent = false; isTryingToRunRobotCode = false; isRunningRobotCodeRunner = false; isRunningRobotCode = false; Thread.Sleep(3000); // ms client.Connect(); } } catch { isTryingToRunRobotCode = false; frcUserProgramPresent = false; isRunningRobotCodeRunner = false; isRunningRobotCode = false; Thread.Sleep(3000); // ms } } }
private async Task OnEvent(WatcherEvent <V1Secret> e) { var id = KubernetesObjectId.For(e.Item.Metadata()); var item = e.Item; _logger.LogTrace("[{eventType}] {kind} {@id}", e.Type, e.Item.Kind, id); if (e.Type != WatchEventType.Added && e.Type != WatchEventType.Modified) { return; } if (!e.Item.Metadata.ReflectionAllowed() || !e.Item.Metadata.FortiReflectionEnabled()) { return; } if (!e.Item.Type.Equals("kubernetes.io/tls", StringComparison.InvariantCultureIgnoreCase)) { return; } var caCrt = Encoding.Default.GetString(item.Data["ca.crt"]); var tlsCrt = Encoding.Default.GetString(item.Data["tls.crt"]); var tlsKey = Encoding.Default.GetString(item.Data["tls.key"]); var tlsCerts = tlsCrt.Split(new[] { "-----END CERTIFICATE-----" }, StringSplitOptions.RemoveEmptyEntries) .Select(s => s.TrimStart()) .Where(s => !string.IsNullOrWhiteSpace(s)) .Select(s => $"{s}-----END CERTIFICATE-----") .ToList(); var hostSecretIds = item.Metadata.FortiReflectionHosts().Select(s => new KubernetesObjectId(s)).ToList(); var fortiCertName = item.Metadata.FortiCertificate(); var fortiCertId = !string.IsNullOrWhiteSpace(fortiCertName) ? fortiCertName : item.Metadata.Name.Substring(0, Math.Min(item.Metadata.Name.Length, 30)); foreach (var hostSecretId in hostSecretIds) { _logger.LogDebug( "Reflecting {secretId} to FortiOS device using host secret {hostSecretId}.", id, hostSecretId, hostSecretId); string fortiHost; string fortiUsername; string fortiPassword; try { var hostSecret = await _apiClient.ReadNamespacedSecretAsync(hostSecretId.Name, hostSecretId.Namespace); if (hostSecret.Data is null || !hostSecret.Data.Keys.Any()) { _logger.LogWarning("Cannot reflect {secretId} to {hostSecretId}. " + "Host secret {hostSecretId} has no data.", id, hostSecretId, hostSecretId); continue; } fortiHost = hostSecret.Data.ContainsKey("host") ? Encoding.Default.GetString(hostSecret.Data["host"]) : null; fortiUsername = hostSecret.Data.ContainsKey("username") ? Encoding.Default.GetString(hostSecret.Data["username"]) : null; fortiPassword = hostSecret.Data.ContainsKey("password") ? Encoding.Default.GetString(hostSecret.Data["password"]) : null; } catch (HttpOperationException ex) when(ex.Response.StatusCode == HttpStatusCode.NotFound) { _logger.LogWarning("Cannot reflect {secretId} to {hostSecretId}. Host secret {hostSecretId} not found.", id, hostSecretId, hostSecretId); continue; } if (string.IsNullOrWhiteSpace(fortiHost) || string.IsNullOrWhiteSpace(fortiUsername) || string.IsNullOrWhiteSpace(fortiPassword)) { _logger.LogWarning( "Cannot reflect {secretId} to FortiOS device using host secret {hostSecretId}. " + "Host secret {hostSecretId} must contain 'host', 'username' and 'password' values.", id, hostSecretId, hostSecretId); continue; } var hostParts = fortiHost.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()) .Where(s => !string.IsNullOrWhiteSpace(s)).ToList(); if (!hostParts.Any() || hostParts.Count > 2) { _logger.LogWarning( "Cannot reflect {secretId} to FortiOS device using host secret {hostSecretId}. " + "Host secret {hostSecretId} contains invalid 'host' data. " + "'host' must be in the format 'host:port' where port is optional.", id, hostSecretId, hostSecretId); } var hostPort = hostParts.Count < 2 ? 22 : int.TryParse(hostParts.Last(), out var port) ? port : 22; using var client = new SshClient(hostParts.First(), hostPort, fortiUsername, fortiPassword) { ConnectionInfo = { Timeout = TimeSpan.FromSeconds(10) } }; try { _logger.LogDebug("Connecting for FortiOS device at {host}", fortiHost); client.Connect(); } catch (Exception exception) { _logger.LogError(exception, "Cannot reflect {secretId} to FortiOS device using host secret {hostSecretId} due to exception.", id, hostSecretId); continue; } _logger.LogDebug("Checking for certificate {certId} on FortiOS device {host}", fortiCertId, fortiHost); string checkOutput; await using (var shell = client.CreateShellStream(nameof(FortiMirror), 128, 1024, 800, 600, 1024)) { var lastLine = string.Empty; var outputBuilder = new StringBuilder(); shell.WriteLine("config vpn certificate local"); shell.WriteLine($"edit {fortiCertId}"); shell.WriteLine("show full"); shell.WriteLine("end"); while (!(lastLine.Contains("#") && lastLine.Contains("end"))) { lastLine = shell.ReadLine(); outputBuilder.AppendLine(lastLine); } shell.Close(); checkOutput = outputBuilder.ToString(); } var localCertificateUpToDate = true; if (!string.IsNullOrWhiteSpace(tlsKey)) { if (checkOutput.Contains("unset private-key")) { localCertificateUpToDate = false; } } if (!checkOutput.Contains("set certificate", StringComparison.InvariantCultureIgnoreCase)) { localCertificateUpToDate = false; } else { var remoteCertificate = checkOutput.Substring(checkOutput.IndexOf("set certificate \"", StringComparison.InvariantCultureIgnoreCase)); remoteCertificate = remoteCertificate.Replace("set certificate \"", string.Empty, StringComparison.InvariantCultureIgnoreCase); remoteCertificate = remoteCertificate.Substring(0, remoteCertificate.IndexOf("\"", StringComparison.InvariantCultureIgnoreCase)); remoteCertificate = remoteCertificate.Replace("\r", string.Empty); if (!tlsCerts.Select(s => s.Replace("\r", string.Empty)).Contains(remoteCertificate)) { localCertificateUpToDate = false; } } var success = true; if (!localCertificateUpToDate) { var commandBuilder = new StringBuilder(); commandBuilder.AppendLine("config vpn certificate local"); commandBuilder.AppendLine($"edit {fortiCertId}"); commandBuilder.AppendLine($"set private-key \"{tlsKey}\""); commandBuilder.AppendLine($"set certificate \"{tlsCrt}\""); commandBuilder.AppendLine("end"); var command = client.RunCommand(commandBuilder.ToString()); if (command.ExitStatus != 0 || !string.IsNullOrWhiteSpace(command.Error)) { _logger.LogWarning( "Checking for certificate {certId} could not be installed on FortiOS device {host} due to error: {error}", id, fortiHost, command.Error); success = false; } } if (!localCertificateUpToDate && success) { var caCerts = tlsCerts.ToList(); if (!string.IsNullOrWhiteSpace(caCrt)) { caCerts.Add(caCrt); } var caId = 0; for (var i = 0; i < caCerts.Count; i++) { _logger.LogDebug("Installing CA certificate {index} for {certId} on FortiOS device {host}", i + 1, id, fortiHost); var commandBuilder = new StringBuilder(); commandBuilder.AppendLine("config vpn certificate ca"); commandBuilder.AppendLine($"edit {fortiCertId}_CA{(caId == 0 ? string.Empty : caId.ToString())}"); commandBuilder.AppendLine($"set ca \"{tlsCerts[i]}\""); commandBuilder.AppendLine("end"); var command = client.RunCommand(commandBuilder.ToString()); if (command.ExitStatus == 0 && string.IsNullOrWhiteSpace(command.Error)) { caId++; continue; } if (command.Error.Contains("This CA certificate is duplicated.")) { _logger.LogWarning("Skipping CA certificate {index} since it is duplicated by another certificate.", i + i); } else if (command.Error.Contains("Input is not a valid CA certificate.")) { _logger.LogDebug("Skipping CA certificate {index} since it is not a valid CA certificate.", i + i); } else { _logger.LogWarning("Could not install CA {index} certificate due to error: {response}", i + 1, command.Result); success = false; } } } if (!success) { _logger.LogError("Reflecting {secretId} to FortiOS device using host secret {hostSecretId} completed with errors.", id, hostSecretId); } else if (!localCertificateUpToDate) { _logger.LogInformation("Reflected {secretId} to FortiOS device using host secret {hostSecretId}.", id, hostSecretId); } } }
private bool ConnectToUnix() { string result = "", s; string passPhrase = null; try { if (string.IsNullOrEmpty(Host) || string.IsNullOrEmpty(Port.ToString()) || string.IsNullOrEmpty(UserName)) { Reporter.ToLog(eLogLevel.WARN, "One of Settings of Agent is Empty "); throw new Exception("One of Settings of Agent is Empty "); } if (Password == null) { Password = ""; } try { System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(Host, Port); } catch (Exception) { Reporter.ToLog(eLogLevel.WARN, "Error Connecting to Host: " + Host + " with Port: " + Port); throw new Exception("Error Connecting to Host: " + Host + " with Port: " + Port); } ConnectionInfo connectionInfo = null; if (KeyboardIntractiveAuthentication) { connectionInfo = KeyboardInteractiveAuthConnectionInfo(); } else { connectionInfo = new ConnectionInfo(Host, Port, UserName, new PasswordAuthenticationMethod(UserName, Password) ); } if (!string.IsNullOrEmpty(PrivateKeyPassPhrase)) { passPhrase = PrivateKeyPassPhrase; } if (File.Exists(PrivateKey)) { connectionInfo = new ConnectionInfo(Host, Port, UserName, new PasswordAuthenticationMethod(UserName, Password), new PrivateKeyAuthenticationMethod(UserName, new PrivateKeyFile(File.OpenRead(PrivateKey), passPhrase) ) ); } connectionInfo.Timeout = new TimeSpan(0, 0, SSHConnectionTimeout); UnixClient = new SshClient(connectionInfo); Task task = Task.Factory.StartNew(() => { UnixClient.Connect(); if (UnixClient.IsConnected) { UnixClient.SendKeepAlive(); ss = UnixClient.CreateShellStream("dumb", 240, 24, 800, 600, 1024); } }); Stopwatch st = Stopwatch.StartNew(); while (!task.IsCompleted && st.ElapsedMilliseconds < SSHConnectionTimeout * 1000) { task.Wait(500); // Give user feedback every 500ms GingerCore.General.DoEvents(); } if (UnixClient.IsConnected) { mConsoleDriverWindow.ConsoleWriteText("Connected!"); s = ss.ReadLine(new TimeSpan(0, 0, 2)); while (!String.IsNullOrEmpty(s)) { result = result + "\n" + s; s = ss.ReadLine(new TimeSpan(0, 0, 2)); } mConsoleDriverWindow.ConsoleWriteText(result); return(true); } else { Reporter.ToLog(eLogLevel.WARN, "Error connecting to UnixServer - " + Host); throw new Exception("Error connecting to UnixServer - " + Host); } } catch (Exception e) { ErrorMessageFromDriver = e.Message; return(false); } }
public async Task Start() { await Task.Run(async() => { List <Task> ServerTaskList = new List <Task>(); foreach (var server in ServerList) { //create the task for each server var ServerTask = Task.Run(() => { //restart the dhcp service //item.Value.Label.Text = "Command started."; SendMessage("Command started", server.ServerName); var serverName = string.Format("{0}.local", server.ServerName); //var serverLabel = item.Value.Label; // check if FileName if (server.FileName != "") { try { string _tmpFile = System.IO.Path.GetTempPath() + Path.GetFileName(server.FileName); File.WriteAllText(_tmpFile, server.FileContent); SendMessage("File created correctly.", server.ServerName); using (var client = new SftpClient(serverName, User, Password)) { client.Connect(); using (var fileStream = new FileStream(_tmpFile, FileMode.Open)) { client.BufferSize = 4 * 1024; // bypass Payload error large files client.UploadFile(fileStream, server.FileName); } SendMessage("File uploaded.", server.ServerName); client.Disconnect(); } } catch (Exception ex) { SendError(string.Format("ERROR: {0}", ex.Message), server.ServerName); } } try { using (var client = new SshClient(serverName, User, Password)) { client.Connect(); var result = client.RunCommand(Command); if (result.ExitStatus != 0) { SendError(string.Format("ERROR: {0}", result.Error), server.ServerName); } else { SendMessage(string.Format("Command completed."), server.ServerName); } client.Disconnect(); } } catch (Exception ex) { SendError("Error: " + ex.Message, ""); return; } }); ServerTaskList.Add(ServerTask); } await Task.WhenAll(ServerTaskList); }); }
public int StartBuild(IVsOutputWindowPane outputPane, uint dwOptions) { var buildHost = this[MonoPropertyPage.BuildHostProperty]; var dteProject = GetDTEProject(project); var projectFolder = Path.GetDirectoryName(dteProject.FullName); outputPane.Log($"Starting build of {projectFolder}..."); // If using Windows Bash... if (string.IsNullOrEmpty(buildHost)) { var bash = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Sysnative", "bash.exe"); if (!File.Exists(bash)) { // outputPane.LogError(dteProject.FullName, $"Error: You must set up a build server on the 'Mono' project property page."); outputPane.Log(VsLogSeverity.Error, dteProject.UniqueName, dteProject.FullName, "Error: You must set up a build server on the 'Mono' project property page."); UpdateBuildStatus(0); return(VSConstants.S_FALSE); } var bashProjectFolder = ConvertToUnixPath(projectFolder); var outputFile = Path.GetTempFileName(); var script = $@"cd ""{bashProjectFolder}"" xbuild > ""{ConvertToUnixPath(outputFile)}"" exit ".Replace("\r\n", "\n"); var scriptFile = Path.GetTempFileName(); var arguments = $"/C {bash} --init-file {ConvertToUnixPath(scriptFile)}"; File.WriteAllText(scriptFile, script); var process = new System.Diagnostics.Process { StartInfo = new ProcessStartInfo("CMD", arguments) { WindowStyle = ProcessWindowStyle.Hidden } }; process.Start(); process.WaitForExit(); outputPane.Log(File.ReadAllText(outputFile)); try { File.Delete(scriptFile); File.Delete(outputFile); } catch (Exception e) { outputPane.Log(e.ToString()); } } else { outputPane.Log("Uploading project to the build server..."); var buildUsername = this[MonoPropertyPage.BuildUsernameProperty]; var buildPassword = this[MonoPropertyPage.BuildPasswordProperty]; var buildFolder = this[MonoPropertyPage.BuildFolderProperty]; using (var client = new SftpClient(buildHost, buildUsername, buildPassword)) { client.Connect(); client.CreateFullDirectory(buildFolder); client.ChangeDirectory(buildFolder); outputPane.Log($"Clearing out the contents of the build folder: {buildFolder}"); client.Clear(); // Upload project var createdDirectories = new HashSet <string>(); var projectFile = Path.GetFileName(dteProject.FullName); client.Upload(projectFolder, projectFile, createdDirectories); outputPane.Log($"Uploaded {projectFile}"); var projectItems = new Queue <ProjectItem>(dteProject.ProjectItems.Cast <ProjectItem>()); while (projectItems.Any()) { var projectItem = projectItems.Dequeue(); for (short i = 1; i <= projectItem.FileCount; i++) { var fileName = projectItem.FileNames[i]; if (File.Exists(fileName)) { fileName = FileUtils.ToRelativePath(projectFolder, fileName); client.Upload(projectFolder, fileName, createdDirectories); outputPane.Log($"Uploaded {fileName}"); } } foreach (ProjectItem childItem in projectItem.ProjectItems) { projectItems.Enqueue(childItem); } } using (var ssh = new SshClient(buildHost, buildUsername, buildPassword)) { outputPane.Log("Starting xbuild to build the project"); ssh.Connect(); var exitCode = ssh.RunCommand($@"cd {buildFolder}; xbuild /p:Configuration={dteProject.ConfigurationManager.ActiveConfiguration.ConfigurationName} > xbuild.output; exitcode=$?; cat xbuild.output; rm xbuild.output; exit ""$exitcode""", outputPane, dteProject.UniqueName); if (exitCode != 0) { UpdateBuildStatus(0); return(VSConstants.S_FALSE); } } var projectConfiguration = dteProject.ConfigurationManager.ActiveConfiguration; var outputFolder = Path.GetDirectoryName(Path.Combine(projectFolder, projectConfiguration.Properties.Item("OutputPath").Value.ToString())); outputPane.Log($"Copying build artifacts to the output folder: {outputFolder}"); var buildServerOutputPath = buildFolder + "/" + FileUtils.ToRelativePath(projectFolder, outputFolder).Replace("\\", "/"); client.CreateFullDirectory(buildServerOutputPath); client.ChangeDirectory(buildServerOutputPath); foreach (var file in client.ListDirectory(".").Where(x => x.IsRegularFile)) { using (var output = new FileStream(Path.Combine(outputFolder, file.Name), FileMode.Create, FileAccess.Write)) { client.DownloadFile(file.FullName, output); outputPane.Log($"Copied {file.Name}"); } } client.Disconnect(); } } UpdateBuildStatus(1); return(VSConstants.S_OK); }
public void Test_PortForwarding_Local() { using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); var port1 = new ForwardedPortLocal("localhost", 8084, "www.renci.org", 80); client.AddForwardedPort(port1); port1.Exception += delegate(object sender, ExceptionEventArgs e) { Assert.Fail(e.Exception.ToString()); }; port1.Start(); System.Threading.Tasks.Parallel.For(0, 100, //new ParallelOptions //{ // MaxDegreeOfParallelism = 20, //}, (counter) => { var start = DateTime.Now; var req = HttpWebRequest.Create("http://localhost:8084"); using (var response = req.GetResponse()) { var data = ReadStream(response.GetResponseStream()); var end = DateTime.Now; Debug.WriteLine(string.Format("Request# {2}: Length: {0} Time: {1}", data.Length, (end - start), counter)); } } ); } }
//[TestMethod] public void Test_MultipleThread_10000_MultipleConnections() { try { System.Threading.Tasks.Parallel.For(0, 10000, () => { var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD); client.Connect(); return client; }, (int counter, ParallelLoopState pls, SshClient client) => { var result = ExecuteTestCommand(client); Debug.WriteLine(string.Format("TestMultipleThreadMultipleConnections #{0}", counter)); Assert.IsTrue(result); return client; }, (SshClient client) => { client.Disconnect(); client.Dispose(); } ); } catch (Exception exp) { Assert.Fail(exp.ToString()); } }