private static void connect(string hostName, string userName, string password) { if (client != null && client.IsConnected) return; var connectionInfo = new KeyboardInteractiveConnectionInfo(hostName, userName); connectionInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e) { foreach (var prompt in e.Prompts) prompt.Response = password; }; client = new SshClient(connectionInfo); client.Connect(); sshStream = client.CreateShellStream("", 80, 40, 80, 40, 1024); shellCommand("python", null); using (var sr = new System.IO.StreamReader("queryJoints.py")) { String line; while ((line = sr.ReadLine()) != null) pythonCommand(line); } }
private void GetNextImage() { KeyboardInteractiveConnectionInfo connectionInfo = new KeyboardInteractiveConnectionInfo("192.168.42.1", 22, "pi"); connectionInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e) { foreach (var prompt in e.Prompts) { if (prompt.Request.Equals("Password: "******"banjobob"; } else { Debug.Log(prompt.Request + " Prompt Request"); } } }; string password = "******"; //using (var sftp = new SftpClient(new ConnectionInfo("192.168.42.1","pi",))) //{ // Debug.Log( " :Is connected" + sftp.IsConnected ); // try // { // sftp.Connect(); // } // catch (UnityException e) // { // Debug.Log(e.Message); // } // var files = sftp.ListDirectory("/var/www/"); // Debug.Log(Application.persistentDataPath); // foreach (var file in files) // { // if (!file.Name.StartsWith(".")) // { // if (file.Name.EndsWith(".jpg")) // { // DownloadFile(sftp, file, Application.dataPath); // } // } // } //} }
public PythonConnection(string hostName, string userName, string password) { var connectionInfo = new KeyboardInteractiveConnectionInfo(hostName, userName); connectionInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e) { foreach (var prompt in e.Prompts) prompt.Response = password; }; client = new SshClient(connectionInfo); client.Connect(); sshStream = client.CreateShellStream("", 80, 40, 80, 40, 1024); shellCommand("python", null); }
/// <summary> /// Establishes the connection to the server, using the specified <paramref name="terminal"/> for connection initialization (authentication, etc.). /// </summary> /// <param name="terminal">The terminal to use for connection initialization.</param> /// <returns>A value indicating whether the connection was successfully established.</returns> /// <exception cref="ObjectDisposedException">The connection object is already disposed.</exception> /// <exception cref="InvalidOperationException">The connection object is currently connected.</exception> public async Task<bool> ConnectAsync(IConnectionInitializingTerminal terminal) { this.CheckDisposed(); this.MustBeConnected(false); Lazy<string> username = new Lazy<string>(() => { if (string.IsNullOrEmpty(this.connectionData.Username)) { return terminal.ReadLineAsync("Username: "******"Username: "******"Password: "******"Password expired for user " + e.Username); do { var readNewPassword1Task = terminal.ReadLineAsync("New password: "******"Repeat new password: "******"Performing keyboard-interactive authentication."); } if (!string.IsNullOrEmpty(e.Instruction)) { terminal.WriteLine(e.Instruction); } foreach (var prompt in e.Prompts) { var readLineTask = terminal.ReadLineAsync(prompt.Request, echo: prompt.IsEchoed); readLineTask.Wait(); prompt.Response = readLineTask.Result; } }; connectionInfo = keyboardInteractiveConnectionInfo; break; case Model.AuthenticationType.PrivateKey: if (this.privateKeyData == null) { throw new Exception("Private Key '" + connectionData.PrivateKeyName + "' not found. Please correct the authentication details of the connection."); } PrivateKeyFile privateKey; try { using (var privateKeyStream = new MemoryStream(privateKeyData.Data)) { privateKey = new PrivateKeyFile(privateKeyStream); } } catch (SshPassPhraseNullOrEmptyException) { privateKey = null; } // In the normal PrivateKey authentication there is only a connection-local PrivateKeyAgent. var localPprivateKeyAgent = new Lazy<PrivateKeyAgent>(() => { terminal.WriteLine("Performing authentication with Private Key '" + connectionData.PrivateKeyName + "'."); if (privateKey == null) { string privateKeyPassword = terminal.ReadLineAsync("Private Key password: "******"Wrong Private Key password, please try again.", ex); } } } var pka = new PrivateKeyAgent(); pka.AddSsh2(privateKey.HostKey, connectionData.PrivateKeyName); return pka; }); var privateKeyConnectionInfo = new PrivateKeyConnectionInfo(this.connectionData.Host, this.connectionData.Port, username, localPprivateKeyAgent); connectionInfo = privateKeyConnectionInfo; break; case AuthenticationType.PrivateKeyAgent: if (PrivateKeyAgentManager.PrivateKeyAgent.ListSsh2().Count == 0) { throw new SshAuthenticationException("The private key agent doesn't contain any private keys."); } var globalPrivateKeyAgent = new Lazy<PrivateKeyAgent>(() => { var pka = PrivateKeyAgentManager.PrivateKeyAgent; terminal.WriteLine("Performing private key agent authentication."); return pka; }); var privateKeyAgentConnectionInfo = new PrivateKeyConnectionInfo(this.connectionData.Host, this.connectionData.Port, username, globalPrivateKeyAgent); connectionInfo = privateKeyAgentConnectionInfo; if (connectionData.PrivateKeyAgentForwarding == true) { forwardedPrivateKeyAgent = globalPrivateKeyAgent; terminal.WriteLine("Agent forwarding is enabled."); } break; default: throw new NotImplementedException("Authentication method '" + this.connectionData.Authentication + "' not implemented."); } connectionInfo.AuthenticationBanner += (sender, e) => { terminal.WriteLine(e.BannerMessage.Replace("\n", "\r\n")); }; this.client = new SshClient(connectionInfo); this.client.HostKeyReceived += (s, e) => { string fingerprint = string.Join(":", e.FingerPrint.Select(b => b.ToString("x2"))); bool trustHostKey = true; bool storeHostKey = false; string newHostKey = string.Join(null, e.HostKey.Select(b => b.ToString("x2"))); if (oldHostKey == null) { terminal.WriteLine("Remote Terminal has not yet cached a host key for this server."); terminal.WriteLine("Host key's fingerprint: " + fingerprint); terminal.WriteLine("Please make sure the fingerprint matches the server's actual host key."); trustHostKey = QueryYesNo(terminal, "Do you want to continue connecting to the host?"); if (trustHostKey) { storeHostKey = QueryYesNo(terminal, "Do you want to store this host key in the cache?"); } } else if (oldHostKey != newHostKey) { terminal.WriteLine("POSSIBLE SECURITY BREACH DETECTED!"); terminal.WriteLine("Remote Terminal has cached another host key for this server."); terminal.WriteLine("This could mean one of two things:"); terminal.WriteLine(" * the server's host key was changed by an administrator"); terminal.WriteLine(" * another computer is trying to intercept your connection"); terminal.WriteLine("Host key's new fingerprint: " + fingerprint); trustHostKey = QueryYesNo(terminal, "Do you want to continue connecting to the host?"); if (trustHostKey) { storeHostKey = QueryYesNo(terminal, "Do you want to update the cache with the new host key?"); } } e.CanTrust = trustHostKey; if (trustHostKey) { oldHostKey = newHostKey; } if (storeHostKey) { HostKeysDataSource.AddOrUpdate(this.connectionData.Host, this.connectionData.Port, newHostKey); } }; this.client.ConnectionInfo.Timeout = new TimeSpan(0, 15, 0); await Task.Run(() => { this.client.Connect(); }); this.client.ConnectionInfo.Timeout = new TimeSpan(0, 1, 0); var terminalModes = new Dictionary<TerminalModes, uint>(); terminalModes[TerminalModes.TTY_OP_ISPEED] = 0x00009600; terminalModes[TerminalModes.TTY_OP_OSPEED] = 0x00009600; this.stream = this.client.CreateShellStream(terminal.TerminalName, (uint)terminal.Columns, (uint)terminal.Rows, 0, 0, 1024, forwardedPrivateKeyAgent.Value, terminalModes.ToArray()); this.reader = new StreamReader(this.stream); this.writer = new StreamWriter(this.stream); this.writer.AutoFlush = true; return true; } catch (SshConnectionException ex) { terminal.WriteLine(ex.Message); retry = false; } catch (SshAuthenticationException ex) { terminal.WriteLine(ex.Message); if (connectionData.Authentication == AuthenticationType.PrivateKeyAgent) { terminal.WriteLine("Please load the necessary private key(s) into the private key agent."); retry = false; } else { retry = true; } } catch (Exception ex) { terminal.WriteLine(ex.Message); retry = false; } if (!retry || numRetries++ > 5) { return false; } } while (true); }
public static MacSecureEnrolResponse MacSecureEnrol(DiscoDataContext Database, string Host) { MacEnrol trustedRequest = new MacEnrol(); string sessionId = Guid.NewGuid().ToString("B"); MacSecureEnrolResponse MacSecureEnrol; try { EnrolmentLog.LogSessionStarting(sessionId, Host, EnrolmentTypes.MacSecure); EnrolmentLog.LogSessionProgress(sessionId, 0, $"Connecting to '{Host}' as '{Database.DiscoConfiguration.Bootstrapper.MacSshUsername}'"); var sshConnectionInfo = new KeyboardInteractiveConnectionInfo(Host, Database.DiscoConfiguration.Bootstrapper.MacSshUsername); sshConnectionInfo.AuthenticationPrompt += (sender, e) => { foreach (var prompt in e.Prompts) { if (prompt.Request.StartsWith("Password", StringComparison.OrdinalIgnoreCase)) { EnrolmentLog.LogSessionProgress(sessionId, 10, $"Authenticating at '{Host}' as '{Database.DiscoConfiguration.Bootstrapper.MacSshUsername}'"); prompt.Response = Database.DiscoConfiguration.Bootstrapper.MacSshPassword; } } }; using (var sshClient = new SshClient(sshConnectionInfo)) { sshClient.Connect(); try { EnrolmentLog.LogSessionProgress(sessionId, 30, "Retrieving System Profile Information"); var sshResult = sshClient.RunCommand("system_profiler -xml SPHardwareDataType SPNetworkDataType SPSoftwareDataType"); ArrayNode profilerData; using (var sshResultStream = new MemoryStream()) { using (var sshResultWriter = new StreamWriter(sshResultStream, Encoding.UTF8, 0x400, true)) { sshResultWriter.Write(sshResult.Result); } sshResultStream.Position = 0; profilerData = PList.Load(sshResultStream) as ArrayNode; } EnrolmentLog.LogSessionProgress(sessionId, 90, "Processing System Profile Information"); DictionaryNode profilerDataHardware = null; ArrayNode profilerDataNetwork = null; DictionaryNode profilerDataSoftware = null; if (profilerData == null) throw new InvalidOperationException("System Profiler didn't return the expected response"); foreach (var node in profilerData.OfType<DictionaryNode>()) { var nodeItems = ((ArrayNode)node["_items"]); PNode nodeDataType; if (node.TryGetValue("_dataType", out nodeDataType) && nodeDataType is StringNode) { switch (((StringNode)nodeDataType).Value) { case "SPHardwareDataType": profilerDataHardware = (DictionaryNode)nodeItems[0]; break; case "SPNetworkDataType": profilerDataNetwork = nodeItems; break; case "SPSoftwareDataType": profilerDataSoftware = (DictionaryNode)nodeItems[0]; break; } } } if (profilerDataHardware == null || profilerDataNetwork == null || profilerDataSoftware == null) throw new InvalidOperationException("System Profiler didn't return information for a requested data type"); trustedRequest.DeviceSerialNumber = ((StringNode)profilerDataHardware["serial_number"]).Value; trustedRequest.DeviceUUID = ((StringNode)profilerDataHardware["platform_UUID"]).Value; trustedRequest.DeviceComputerName = ((StringNode)profilerDataSoftware["local_host_name"]).Value; var profilerDataNetworkEthernet = profilerDataNetwork.OfType<DictionaryNode>().FirstOrDefault(e => ((StringNode)e["_name"]).Value == "Ethernet"); if (profilerDataNetworkEthernet != null) { trustedRequest.DeviceLanMacAddress = ((StringNode)((DictionaryNode)profilerDataNetworkEthernet["Ethernet"])["MAC Address"]).Value; } var profilerDataNetworkWiFi = profilerDataNetwork.OfType<DictionaryNode>().FirstOrDefault(e => ((StringNode)e["_name"]).Value == "Wi-Fi"); if (profilerDataNetworkWiFi != null) { trustedRequest.DeviceWlanMacAddress = ((StringNode)((DictionaryNode)profilerDataNetworkWiFi["Ethernet"])["MAC Address"]).Value; } trustedRequest.DeviceManufacturer = "Apple Inc."; trustedRequest.DeviceModel = ((StringNode)profilerDataHardware["machine_model"]).Value; trustedRequest.DeviceModelType = ParseMacModelType(((StringNode)profilerDataHardware["machine_name"]).Value); EnrolmentLog.LogSessionProgress(sessionId, 99, "Disconnecting"); sshClient.Disconnect(); } catch (Exception) { throw; } finally { if (sshClient != null) { bool connected = sshClient.IsConnected; if (connected) { sshClient.Disconnect(); } } } } EnrolmentLog.LogSessionProgress(sessionId, 100, "Disconnected, Starting Disco Enrolment"); MacSecureEnrolResponse response = MacSecureEnrolResponse.FromMacEnrolResponse(MacEnrol(Database, trustedRequest, true, sessionId)); EnrolmentLog.LogSessionFinished(sessionId); MacSecureEnrol = response; } catch (System.Exception ex) { ex.ToExceptionless().Submit(); EnrolmentLog.LogSessionError(sessionId, ex); throw ex; } return MacSecureEnrol; }