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();
            }
        }
Beispiel #2
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);
            }
        }
 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();
     }
 }
Beispiel #4
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.");
 }
        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();
            }
        }
        public void Test_Execute_Command_Asynchronously()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                client.Connect();

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

                cmd.EndExecute(asyncResult);

                Assert.IsTrue(cmd.Result == "test\n");

                client.Disconnect();
            }
        }
Beispiel #7
0
        public void Test_Execute_SingleCommand()
        {
            var host = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

            using (var client = new SshClient(host, username, password))
            {
                #region Example SshCommand CreateCommand Execute
                client.Connect();

                var testValue = Guid.NewGuid().ToString();
                var command = string.Format("echo {0}", testValue);
                var cmd = client.CreateCommand(command);
                var result = cmd.Execute();
                result = result.Substring(0, result.Length - 1);    //  Remove \n character returned by command

                client.Disconnect();
                #endregion

                Assert.IsTrue(result.Equals(testValue));
            }
        }
        public void Test_PortForwarding_Remote()
        {
            //  ******************************************************************
            //  ************* Tests are still in not finished ********************
            //  ******************************************************************

            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                client.Connect();
                var port1 = new ForwardedPortRemote(8082, "www.renci.org", 80);
                client.AddForwardedPort(port1);
                port1.Exception += delegate(object sender, ExceptionEventArgs e)
                {
                    Assert.Fail(e.Exception.ToString());
                };
                port1.Start();
                var boundport = port1.BoundPort;

                System.Threading.Tasks.Parallel.For(0, 5,

                    //new ParallelOptions
                    //{
                    //    MaxDegreeOfParallelism = 1,
                    //},
                    (counter) =>
                    {
                        var cmd = client.CreateCommand(string.Format("wget -O- http://localhost:{0}", boundport));
                        var result = cmd.Execute();
                        var end = DateTime.Now;
                        Debug.WriteLine(string.Format("Length: {0}", result.Length));
                    }
                );
                Thread.Sleep(1000 * 100);
                port1.Stop();
            }
        }
Beispiel #9
0
 public static string GetKernel(SshClient sshClient) => sshClient.CreateCommand("sudo freebsd-version -k").Execute();
        public void Test_Execute_Command_Asynchronously_With_Error()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                client.Connect();

                var cmd = client.CreateCommand("sleep 5s; ;");
                var asyncResult = cmd.BeginExecute(null, null);
                while (!asyncResult.IsCompleted)
                {
                    Thread.Sleep(100);
                }

                cmd.EndExecute(asyncResult);

                Assert.IsFalse(string.IsNullOrEmpty(cmd.Error));

                client.Disconnect();
            }
        }
Beispiel #11
0
        /// <summary>
        /// Perform some kind of control action
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        public override bool Execute(SshClient client)
        {
            bool success = false;
            var  rxData  = new StringBuilder();

            SshCommand cmd = null;

            try
            {
                if (string.IsNullOrEmpty(ErrorResponse) && string.IsNullOrEmpty(SuccessResponse))
                {
                    throw new Exception("Need Error/Success response defined for StreamCommand");
                }

                Logger.Debug("Command Tx: " + Send);

                cmd = client.CreateCommand(Send);
                cmd.CommandTimeout = new TimeSpan(0, 0, TimeoutSecs);
                cmd.BeginExecute(new AsyncCallback(ExecutionCallback), cmd);

                var reader = new StreamReader(cmd.OutputStream);

                DateTime dtStart = DateTime.Now;
                long     intervalS;
                bool     timedOut = false;
                do
                {
                    if (reader.BaseStream.Length > 0)
                    {
                        rxData.Append(reader.ReadToEnd());
                    }

                    if (rxData.Length > 0)
                    {
                        if (!string.IsNullOrEmpty(ErrorResponse))
                        {
                            if (rxData.ToString().Contains(ErrorResponse))
                            {
                                Logger.Warn("- Error response: " + rxData);
                                return(false);
                            }
                        }

                        if (!string.IsNullOrEmpty(SuccessResponse))
                        {
                            if (rxData.ToString().Contains(SuccessResponse))
                            {
                                Logger.Warn("- Success response: " + rxData);
                                success = true;
                            }
                        }
                    }

                    intervalS = (long)DateTime.Now.Subtract(dtStart).TotalSeconds;
                    if (TimeoutSecs > 0)
                    {
                        timedOut = intervalS > TimeoutSecs;
                    }
                } while (!timedOut && !success);

                if (timedOut)
                {
                    UpdateUI("*** Timed out");
                    return(false);
                }

                // Perform regexp replacement...
                Output = !string.IsNullOrEmpty(OutputRegExp) ? Regex.Match(rxData.ToString(), OutputRegExp).Value : rxData.ToString();

                Logger.Debug("Output: " + (!string.IsNullOrEmpty(Output) ? Output : "<none>"));
            }
            catch (Exception ex)
            {
                Logger.Warn("Exception in worker thread: " + ex.Message);
                success = false;
            }
            finally
            {
                try
                {
                    // TODO: We seem to timeout and disconnect if we try to cancel. Perhaps better for now to kill the process in the next command instead
                    //cmd.CancelAsync();
                    cmd.Dispose();
                    cmd = null;
                }
                catch (Exception e)
                {
                    Logger.Warn("Exception stopping shell: " + e.Message);
                }
            }
            return(success);
        }
Beispiel #12
0
        public void Test_Execute_ExtendedOutputStream()
        {
            var host = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

            using (var client = new SshClient(host, username, password))
            {
                #region Example SshCommand CreateCommand Execute ExtendedOutputStream

                client.Connect();
                var cmd = client.CreateCommand("echo 12345; echo 654321 >&2");
                var result = cmd.Execute();

                Console.Write(result);

                var reader = new StreamReader(cmd.ExtendedOutputStream);
                Console.WriteLine("DEBUG:");
                Console.Write(reader.ReadToEnd());

                client.Disconnect();

                #endregion

                Assert.Inconclusive();
            }
        }
        private async Task <ConnectionResult> SShTunnel(RconServer server, AuthType type, string command)
        {
            ConnectionInfo connectionInfo = null;

            var result = new ConnectionResult();

            //auth
            if (type == AuthType.PrivateKey)
            {
                var keyFiles = new[] { new PrivateKeyFile("KeyFiles/" + server.SshKeyFileName) };
                connectionInfo = new ConnectionInfo(server.Adress, server.SshUsername,
                                                    new PrivateKeyAuthenticationMethod(server.SshUsername, keyFiles));
            }
            else if (type == AuthType.UserPass)
            {
                connectionInfo = new ConnectionInfo(server.Adress, server.SshUsername,
                                                    new PasswordAuthenticationMethod(server.SshUsername, server.SshPassword));
            }
            else if (type == AuthType.PrivateKeyPassphrase)
            {
                var keyFiles = new[] { new PrivateKeyFile("KeyFiles/" + server.SshKeyFileName, server.SshPassphrase) };
                connectionInfo = new ConnectionInfo(server.Adress, server.SshUsername,
                                                    new PasswordAuthenticationMethod(server.SshUsername, server.SshPassphrase),
                                                    new PrivateKeyAuthenticationMethod(server.SshUsername, keyFiles));
            }

            var guid                  = Guid.NewGuid();
            var tmpFolderRemote       = "/tmp/pavlovNetcatRconWebServer/";
            var pavlovLocalScriptPath = "Temp/pavlovNetcatRconWebServerScript" + guid + ".sh";

            File.Copy("pavlovNetcatRconWebServerScript.sh", pavlovLocalScriptPath, true);
            var pavlovRemoteScriptPath = tmpFolderRemote + "Script" + guid + ".sh";
            var commandFilelocal       = "Temp/Command" + guid;

            File.Copy("Command", commandFilelocal, true);
            var commandFileRemote = tmpFolderRemote + "Commands" + guid;

            try
            {
                //connection
                using var client = new SshClient(connectionInfo);
                client.Connect();

                //check if first scripts exist
                using (var sftp = new SftpClient(connectionInfo))
                {
                    try
                    {
                        sftp.Connect();

                        if (sftp.Exists(tmpFolderRemote))
                        {
                            var files = sftp.ListDirectory(tmpFolderRemote);
                            foreach (var file in files.Where(x => x.Name != "." && x.Name != ".."))
                            {
                                var chmodCommandFiles = client.CreateCommand("chmod 7777 " + pavlovRemoteScriptPath);
                                chmodCommandFiles.Execute();
                                sftp.DeleteFile(file.FullName);
                            }

                            var chmodCommandFolder = client.CreateCommand("chmod 7777 " + tmpFolderRemote);
                            chmodCommandFolder.Execute();
                            sftp.DeleteDirectory(tmpFolderRemote);
                        }

                        //sftp clear old files
                        sftp.CreateDirectory(tmpFolderRemote);

                        //That part means that it will not work if more than one requets happen?
                        string text = await File.ReadAllTextAsync(pavlovLocalScriptPath);

                        text = text.Replace("{port}", server.TelnetPort.ToString());
                        await File.WriteAllTextAsync(pavlovLocalScriptPath, text);

                        await File.WriteAllTextAsync(commandFilelocal,
                                                     server.Password + "\n" + command + "\n" + "Disconnect");


                        await using (var uplfileStream = File.OpenRead(pavlovLocalScriptPath))
                        {
                            sftp.UploadFile(uplfileStream, pavlovRemoteScriptPath, true);
                        }

                        await using (var uplfileStream = File.OpenRead(commandFilelocal))
                        {
                            sftp.UploadFile(uplfileStream, commandFileRemote, true);
                        }

                        File.Delete(commandFilelocal);
                        File.Delete(pavlovLocalScriptPath);
                    }
                    finally
                    {
                        sftp.Disconnect();
                    }
                }


                var sshCommand = client.CreateCommand("chmod +x " + pavlovRemoteScriptPath);
                //var sshCommand = client.CreateCommand("telnet localhost " + server.TelnetPort);
                sshCommand.Execute();

                var sshCommandExecuteBtach = client.CreateCommand(pavlovRemoteScriptPath + " " + commandFileRemote);
                sshCommandExecuteBtach.CommandTimeout = TimeSpan.FromMilliseconds(500);
                try
                {
                    sshCommandExecuteBtach.Execute();
                }
                catch (SshOperationTimeoutException)
                {
                    if (!string.IsNullOrEmpty(sshCommandExecuteBtach.Error))
                    {
                        result.errors.Add(sshCommandExecuteBtach.Error);
                    }
                }

                if (!sshCommandExecuteBtach.Result.Contains("Password:"******"After the ssh connection the telnet connection gives strange answers. Can not send command!");
                }

                if (!sshCommandExecuteBtach.Result.Contains("Authenticated=1"))
                {
                    result.errors.Add(
                        "After the ssh connection the telnet connection can not login. Can not send command!");
                }

                Task.Delay(500).Wait();
                // check answer
                result.answer = sshCommandExecuteBtach.Result;

                if (result.errors.Count > 0 && result.answer == "")
                {
                    return(result);
                }

                result.Seccuess = true;
                if (result.answer.Contains("{"))
                {
                    result.answer = result.answer.Substring(result.answer.IndexOf("{", StringComparison.Ordinal));
                }
                if (result.answer.StartsWith("Password: Authenticated=1"))
                {
                    result.answer = result.answer.Replace("Password: Authenticated=1", "");
                }
            }
            catch (Exception e)
            {
                switch (e)
                {
                case SshAuthenticationException _:
                    result.errors.Add("Could not Login over ssh!");
                    break;

                case SshConnectionException _:
                    result.errors.Add("Could not connect to host over ssh!");
                    break;

                case SshOperationTimeoutException _:
                    result.errors.Add("Could not connect to host cause of timeout over ssh!");
                    break;

                case SocketException _:
                    result.errors.Add("Could not connect to host!");
                    break;

                default:
                    throw;
                }

                return(result);
            }

            return(result);
        }
Beispiel #14
0
 public string GetHostname(SshClient sshClient) => sshClient.CreateCommand("hostname").Execute().Replace("\n", "");
Beispiel #15
0
        /// <summary>
        /// constructs the target ip for the mdf
        /// login to ip through ssh and sends commands
        /// </summary>
        void FinishMDF()
        {
            //string ip = "10.146.3.39";
            string ip = "10." + subnet + ".0.1";

            using (var client = new SshClient(ip, userLogin, userPassword))
            {
                client.Connect();
                if (client.IsConnected)
                {
                    Console.WriteLine("connected");
                }

                SshCommand command = client.CreateCommand("config t");
                command.Execute();

                command = client.CreateCommand("int eth");
                command.Execute();

                command = client.CreateCommand("no dual");
                command.Execute();

                command = client.CreateCommand("inline power power-by-class 2");
                command.Execute();

                command = client.CreateCommand("vlan " + 10);
                command.Execute();

                command = client.CreateCommand("tag eth" + slotNum + "/" + portNum);
                command.Execute();

                command = client.CreateCommand("vlan 30");
                command.Execute();

                command = client.CreateCommand("tag eth" + slotNum + "/" + portNum);
                command.Execute();

                command = client.CreateCommand("vlan 40");
                command.Execute();

                command = client.CreateCommand("no tag eth" + slotNum + "/" + portNum);
                command.Execute();

                command = client.CreateCommand("vlan 50");
                command.Execute();

                command = client.CreateCommand("no tag eth" + slotNum + "/" + portNum);
                command.Execute();

                command = client.CreateCommand("int eth" + slotNum + "/" + portNum);
                command.Execute();

                command = client.CreateCommand("Dual 10");
                command.Execute();

                client.Disconnect();
            }
        }
        public void Test_Get_Result_Without_Execution()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                client.Connect();
                var cmd = client.CreateCommand("ls -l");

                Assert.IsTrue(string.IsNullOrEmpty(cmd.Result));
                client.Disconnect();
            }
        }
        public ServerCommandResult ExecuteCommand(ServerCommand serverCommand)
        {
            if (!IsConnected)
            {
                throw new ServerConnectionException("Server connection is not established");
            }
            if (serverCommand == null)
            {
                throw new ArgumentNullException(nameof(serverCommand));
            }
            if (string.IsNullOrEmpty(serverCommand.Text))
            {
                throw new CommandNotSpecifiedException($"Command was not defined");
            }

            using (var command = Client.CreateCommand(serverCommand.Text))
            {
                if (serverCommand.Timeout.HasValue)
                {
                    command.CommandTimeout = serverCommand.Timeout.Value;
                }

                Stopwatch stopwatch = Stopwatch.StartNew();
                var       result    = new ServerCommandResult();
                try
                {
                    command.Execute();
                }
                catch (SshOperationTimeoutException exception)
                {
                    if (serverCommand.ThrowError)
                    {
                        throw new CommandTimeoutException(exception.Message);
                    }
                    else
                    {
                        result.Error = exception.Message;
                    }
                }
                catch (SshConnectionException exception)
                {
                    if (serverCommand.ThrowError)
                    {
                        throw new ServerConnectionException(exception.Message);
                    }
                    else
                    {
                        result.Error = exception.Message;
                    }
                }
                finally
                {
                    if (stopwatch.IsRunning)
                    {
                        stopwatch.Stop();
                    }
                }

                result.Result      = command.Result;
                result.ElapsedTime = stopwatch.Elapsed;
                result.Error       = command.Error;
                result.ExitStatus  = command.ExitStatus;

                if (serverCommand.ThrowError && !string.IsNullOrEmpty(command.Error))
                {
                    if (result.Error.Contains("command not found"))
                    {
                        throw new CommandNotFoundException($"Command {command.CommandText} is not found");
                    }

                    throw new CommandResultException($"Command {command.CommandText} returned the following error: {command.Error}");
                }

                return(result);
            }
        }
Beispiel #18
0
        /// <summary>
        /// constructs the target ip for the mdf
        /// login to ip through ssh and sends commands
        /// </summary>
        void FinishIDF()
        {
            string ip = "10." + subnet + "." + (idfNum * 8).ToString() + ".1";

            using (var client = new SshClient(ip, userLogin, userPassword))
            {
                client.Connect();
                if (client.IsConnected)
                {
                    Console.WriteLine("connected");
                }

                SshCommand command = client.CreateCommand("config t");
                command.Execute();

                command = client.CreateCommand("int eth");
                command.Execute();

                command = client.CreateCommand("no dual");
                command.Execute();

                command = client.CreateCommand("inline power power-by-class 2");
                command.Execute();

                command = client.CreateCommand("vlan " + 10 + idfNum); // <-- switch to closet
                command.Execute();

                command = client.CreateCommand("tag eth" + idf_switchNum + "/" + idf_cableType + "/" + idf_portNum);
                command.Execute();

                command = client.CreateCommand("vlan 30");
                command.Execute();

                command = client.CreateCommand("tag eth" + idf_switchNum + "/" + idf_cableType + "/" + idf_portNum);
                command.Execute();

                command = client.CreateCommand("vlan 40");
                command.Execute();

                command = client.CreateCommand("no tag eth" + idf_switchNum + "/" + idf_cableType + "/" + idf_portNum);
                command.Execute();

                command = client.CreateCommand("vlan 50");
                command.Execute();

                command = client.CreateCommand("no tag eth" + idf_switchNum + "/" + idf_cableType + "/" + idf_portNum);
                command.Execute();

                command = client.CreateCommand("int eth" + idf_switchNum + "/" + idf_cableType + "/" + idf_portNum);
                command.Execute();

                command = client.CreateCommand("Dual 10");
                command.Execute();

                client.Disconnect();
            }
        }
Beispiel #19
0
        public LacunaBot()
        {
            discord = new DiscordClient(x => {
                x.LogLevel   = LogSeverity.Info;
                x.LogHandler = Log;
            });
            discord.UsingCommands(x => {
                x.PrefixChar         = '$';
                x.AllowMentionPrefix = true;
            });
            var commands = discord.GetService <CommandService>();

            commands.CreateCommand("ip")
            .Parameter("ip", ParameterType.Optional)
            .Do(async(e) =>
            {
                if (e.GetArg("ip") == "")
                {
                    await e.Channel.SendMessage("The current IP is:" + Globals.ip);
                }
                else
                {
                    Globals.ip = e.GetArg("ip");
                    await e.Channel.SendMessage(Globals.ip + " is the current IP!");
                }
            });
            commands.CreateCommand("user")
            .Parameter("user", ParameterType.Optional)
            .Do(async(e) =>
            {
                if (e.GetArg("user") == "")
                {
                    await e.Channel.SendMessage("The current User is:" + Globals.ip);
                }
                else
                {
                    Globals.user2 = e.GetArg("user");
                    await e.Channel.SendMessage(Globals.user2 + " is the current user!");
                }
            });
            commands.CreateCommand("password")
            .Parameter("password", ParameterType.Optional)
            .Do(async(e) =>
            {
                Globals.password = e.GetArg("password");
                await e.Channel.SendMessage("Set password.");
            });
            commands.CreateCommand("help")
            .Do(async(e) => {
                await e.Channel.SendMessage("__**Hello I am SSHC!** I can connect to a server! :desktop:__ !\nHere are my commands:```css\n$ip 🔗 Set the IP for server connection(ex. $ip \"localhost\")\n$user 🔗 Set the User for server connection(ex. $user \"root\")\n$password 🔗 Set the Password for server connection(ex. $password \"tux\")\n$command 🔗 Send a command to the IP, User, and password provided via SSH!\n$current 🔗 Check current server Info.```\n\n Created by Static#3512");
            });
            commands.CreateCommand("command")
            .Parameter("commandargs")
            .Do(async(e) => {
                if (Globals.ip == "")
                {
                    await e.Channel.SendMessage("The Server's IP is not set!");
                }
                if (Globals.user2 == "")
                {
                    await e.Channel.SendMessage("The Server's User is not set!");
                }
                if (Globals.password == "")
                {
                    await e.Channel.SendMessage("The Server's Password is not set!");
                }
                using (var client = new SshClient(Globals.ip, Globals.user2, Globals.password))
                {
                    // Dont even connect if user is not administrator!
                    if (e.User.ServerPermissions.Administrator == true)
                    {
                        client.Connect();
                        if (client.IsConnected == true)
                        {
                            var cmd = client.CreateCommand(e.GetArg("commandargs"));
                            await e.Channel.SendMessage("Executing ```css\n" + e.GetArg("commandargs") + "```");
                            cmd.Execute();
                            var result = cmd.Result;
                            await e.Channel.SendMessage(result);
                        }
                        else
                        {
                            await e.Channel.SendMessage("Failed to connect! Make sure your info. is correct.");
                        }
                    }
                    else
                    {
                        await e.Channel.SendMessage(e.User.ToString() + ", you do not have access to command!");
                    }
                }
            });
            commands.CreateCommand("current")
            .Do(async(e) => {
                await e.Channel.SendMessage("**⇩ __Current Server Info__ ⇩**\n\n```" + Globals.ip.ToString() + "\n" + Globals.user2 + "\n" + Globals.password + "```");
            });
            #region Token
            discord.ExecuteAndWait(async() => {
                // ENTER YOUR TOKEN!!! <============
                await discord.Connect("token", TokenType.Bot);
                discord.SetGame("ver. 2.0");
            });
            #endregion
        }
Beispiel #20
0
        static void Main(string[] args)
        {
            string        key      = "";
            string        user     = "******";
            string        password = "";
            string        command  = "";
            bool          keyAuth  = false;
            List <string> hosts    = new List <string>();

            foreach (string arg in args)
            {
                switch (arg.Split(':')[0])
                {
                case "/user":
                    user = arg.Split(':')[1];
                    break;

                case "/key":
                    key     = arg.Split(':')[1];
                    keyAuth = true;
                    break;

                case "/password":
                    password = arg.Split(':')[1];
                    break;

                case "/hosts":
                    hosts = arg.Split(':')[1].Split(',').ToList <string>();
                    break;

                case "/command":
                    command = arg.Split(':')[1];
                    break;

                case "/b64":
                    password = Encoding.ASCII.GetString(Convert.FromBase64String(arg.Split(':')[1]));
                    break;
                }
            }
            try
            {
                ConnectionInfo connectionInfo;
                if (!(String.IsNullOrEmpty(key) && String.IsNullOrEmpty(password)) && hosts.Count > 0 && !String.IsNullOrEmpty(command))
                {
                    if (keyAuth)
                    {
                        foreach (string host in hosts)
                        {
                            try
                            {
                                Console.WriteLine($"Running {command} on {host} with Key");
                                connectionInfo = new ConnectionInfo(host, user, new PrivateKeyAuthenticationMethod(key));
                                SshClient sshclient = new SshClient(connectionInfo);
                                sshclient.Connect();
                                SshCommand sc = sshclient.CreateCommand(command);
                                sc.Execute();
                                if (sc.ExitStatus != 0)
                                {
                                    Console.WriteLine($"Error in Command on Host {host}");
                                    Console.WriteLine("Error: {0}", sc.Error);
                                    Console.WriteLine("Exit Status: {0}", sc.ExitStatus);
                                }
                                else
                                {
                                    Console.WriteLine($"{host}: " + sc.Result);
                                }
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine($"Host: {host}\r\n{e.Message}");
                            }
                        }
                    }
                    else
                    {
                        foreach (string host in hosts)
                        {
                            try
                            {
                                Console.WriteLine($"Running {command} on {host} with password {password}");
                                connectionInfo = new ConnectionInfo(host, user, new PasswordAuthenticationMethod(user, password));
                                SshClient sshclient = new SshClient(connectionInfo);
                                sshclient.Connect();
                                SshCommand sc = sshclient.CreateCommand(command);
                                sc.Execute();
                                if (sc.ExitStatus != 0)
                                {
                                    Console.WriteLine($"Error in Command on Host {host}");
                                    Console.WriteLine("Error: {0}", sc.Error);
                                    Console.WriteLine("Exit Status: {0}", sc.ExitStatus);
                                }
                                else
                                {
                                    Console.WriteLine($"{host}: " + sc.Result);
                                }
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine($"Host: {host}\r\n{e.Message}");
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("usage sshiva.exe /user:root /host:localhost /password:P@ssw0rd /command:\"whoami\"");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Beispiel #21
0
        /// <summary>
        /// Default Constructor
        /// </summary>
        /// <param name="address">IP Address : From CSV File</param>
        /// <param name="community">SNMP Community  : From CSV File</param>
        /// <param name="username">SNMP UserName : From CSV File</param>
        /// <param name="password">SNMP Password : From CSV File</param>
        public IsilonCluster(string address, string community, string username, string password)
        {
            // Get Variable that are used in more than one place)
            string clusterGUID     = SNMP.GetSNMP(SNMP.clusterGUID, address, 161, community)[0].Data.ToString();
            string clusterName     = SNMP.GetSNMP(SNMP.clusterName, address, 161, community)[0].Data.ToString();
            string configuredNodes = SNMP.GetSNMP(SNMP.configuredNodes, address, 161, community)[0].Data.ToString();
            int    nodeCount       = Convert.ToInt32(SNMP.GetSNMP(SNMP.nodeCount, address, 161, community)[0].Data.ToString());

            // Get and Calculate capacity
            Double capacity = Convert.ToDouble(SNMP.GetSNMP(SNMP.ifsTotalBytes, address, 161, community)[0].Data.ToString());

            capacity = Math.Round((capacity / 1024 / 1024 / 1024 / 1024), 2);

            // Get and Calculate Used Capacity
            Double used = Convert.ToDouble(SNMP.GetSNMP(SNMP.ifsUsedBytes, address, 161, community)[0].Data.ToString());

            used = Math.Round((used / 1024 / 1024 / 1024 / 1024), 2);

            // Get and Calculate Available Capacity
            Double available = Convert.ToDouble(SNMP.GetSNMP(SNMP.ifsAvailableBytes, address, 161, community)[0].Data.ToString());

            available = Math.Round((available / 1024 / 1024 / 1024 / 1024), 2);

            // Calculate Percentage Used
            Double percentageUsed = Math.Round(((used / capacity) * 100), 2);

            // Create Root Entity Class & Display Name Prop
            ManagementPackClass    mpc_Entity            = SCOM.GetManagementPackClass("System.Entity");
            ManagementPackProperty mpp_EntityDisplayName = mpc_Entity.PropertyCollection["DisplayName"];

            // Create Cluster Management Pack Class
            ManagementPackClass mpc_Cluster = SCOM.GetManagementPackClass("AP.Isilon.Cluster");

            // Create New Cluster Object
            SCOM_Object = new CreatableEnterpriseManagementObject(SCOM.m_managementGroup, mpc_Cluster);

            // Display Name of Root Entity (KEY Property)
            SCOM_Object[mpp_EntityDisplayName].Value = clusterName;

            // Set Properties of Cluster
            //Starting with name (Key Property of Cluster)
            ManagementPackProperty mpp_ClusterName = mpc_Cluster.PropertyCollection["Name"];

            SCOM_Object[mpp_ClusterName].Value = clusterName;
            // GUID Property
            ManagementPackProperty mpp_ClusterGUID = mpc_Cluster.PropertyCollection["GUID"];

            SCOM_Object[mpp_ClusterGUID].Value = clusterGUID;
            // IPAddress
            ManagementPackProperty mpp_ClusterIP = mpc_Cluster.PropertyCollection["IPAddress"];

            SCOM_Object[mpp_ClusterIP].Value = address;
            // SNMP Community String
            ManagementPackProperty mpp_ClusterCommunity = mpc_Cluster.PropertyCollection["Community"];

            SCOM_Object[mpp_ClusterCommunity].Value = community;
            // NodeCount
            ManagementPackProperty mpp_ClusterNodeCount = mpc_Cluster.PropertyCollection["NodeCount"];

            SCOM_Object[mpp_ClusterNodeCount].Value = nodeCount;
            // Configured Nodes
            ManagementPackProperty mpp_ClusterConfiguredNodes = mpc_Cluster.PropertyCollection["ConfiguredNodes"];

            SCOM_Object[mpp_ClusterConfiguredNodes].Value = configuredNodes;
            // Online Nodes
            ManagementPackProperty mpp_ClusterOnlineNodes = mpc_Cluster.PropertyCollection["OnlineNodes"];

            SCOM_Object[mpp_ClusterOnlineNodes].Value = SNMP.GetSNMP(SNMP.onlineNodes, address, 161, community)[0].Data.ToString();
            // Offline Nodes
            ManagementPackProperty mpp_ClusterOfflineNodes = mpc_Cluster.PropertyCollection["OfflineNodes"];

            SCOM_Object[mpp_ClusterOfflineNodes].Value = SNMP.GetSNMP(SNMP.offlineNodes, address, 161, community)[0].Data.ToString();
            // Location
            ManagementPackProperty mpp_ClusterLocation = mpc_Cluster.PropertyCollection["Location"];

            SCOM_Object[mpp_ClusterLocation].Value = SNMP.GetSNMP(SNMP.sysLocation, address, 161, community)[0].Data.ToString();
            // Contact
            ManagementPackProperty mpp_ClusterContact = mpc_Cluster.PropertyCollection["Contact"];

            SCOM_Object[mpp_ClusterContact].Value = SNMP.GetSNMP(SNMP.sysContact, address, 161, community)[0].Data.ToString();
            // Capacity
            ManagementPackProperty mpp_ClusterCapacity = mpc_Cluster.PropertyCollection["Capacity"];

            SCOM_Object[mpp_ClusterCapacity].Value = capacity;
            // Used Capacity
            ManagementPackProperty mpp_ClusterUsedCapacity = mpc_Cluster.PropertyCollection["Used"];

            SCOM_Object[mpp_ClusterUsedCapacity].Value = used;
            // Available Capacity
            ManagementPackProperty mpp_ClusterAvailableCapacity = mpc_Cluster.PropertyCollection["Available"];

            SCOM_Object[mpp_ClusterAvailableCapacity].Value = available;
            // Used Percentage
            ManagementPackProperty mpp_ClusterUsedPercentage = mpc_Cluster.PropertyCollection["UsedPercentage"];

            SCOM_Object[mpp_ClusterUsedPercentage].Value = percentageUsed;

            // Get Nodes
            try
            {
                // Create SSH Connection to Cluster
                client = new SshClient(address, username, password);
                client.Connect();

                // Loop Though All Nodes
                for (int i = 1; i <= nodeCount; i++)
                {
                    // Get Interfaces for this Node
                    var cmd = client.CreateCommand("isi network interfaces list -v -z -a -n " + i + " --format json");
                    cmd.Execute();
                    // Collect Result (Will be In JSON Format
                    string result = cmd.Result;


                    JavaScriptSerializer     js         = new JavaScriptSerializer();
                    IsilonNetworkInterface[] interfaces = js.Deserialize <IsilonNetworkInterface[]>(result);

                    // Create New Node
                    IsilonNode newNode = new IsilonNode(clusterName, i, interfaces, address, community);

                    // Add Node to NodeList
                    NodeList.Add(newNode);
                }


                // Dispose of Cluster SSH Connection
                client.Disconnect();
                client.Dispose();
            }
            catch (Exception ex)
            {
                if (client.IsConnected)
                {
                    client.Disconnect();
                    client.Dispose();
                }
                Program.log.Error(clusterName + " : " + ex.Message);
            }
        }
        public void Test_Execute_Command_with_ExtendedOutput()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                client.Connect();
                var cmd = client.CreateCommand("echo 12345; echo 654321 >&2");
                cmd.Execute();
                //var extendedData = Encoding.ASCII.GetString(cmd.ExtendedOutputStream.ToArray());
                var extendedData = new StreamReader(cmd.ExtendedOutputStream, Encoding.ASCII).ReadToEnd();
                client.Disconnect();

                Assert.AreEqual("12345\n", cmd.Result);
                Assert.AreEqual("654321\n", extendedData);
            }
        }
Beispiel #23
0
        string ExecuteSyncCommand(SshClient client, string action)
        {
            SshCommand command = client.CreateCommand(String.Format(UNIX_COMMAND_FORMAT, _serviceName, action, username, password));

            return(command.Execute());
        }
        public void Test_Execute_InvalidCommand_Then_Execute_ValidCommand()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                client.Connect();
                var cmd = client.CreateCommand(";");
                cmd.Execute();
                if (string.IsNullOrEmpty(cmd.Error))
                {
                    Assert.Fail("Operation should fail");
                }
                Assert.IsTrue(cmd.ExitStatus > 0);

                var result = ExecuteTestCommand(client);

                client.Disconnect();

                Assert.IsTrue(result);
            }
        }
Beispiel #25
0
 void ExecuteAsyncCommand(SshClient client, string action, AsyncCallback callBack, SshCommand command)
 {
     command = client.CreateCommand(String.Format(UNIX_COMMAND_FORMAT, _serviceName, action), UTF8Encoding.UTF8);
     command.BeginExecute(String.Format(UNIX_COMMAND_FORMAT, _serviceName, action), callBack, null);
 }
Beispiel #26
0
 public static string GetUserland(SshClient sshClient) => sshClient.CreateCommand("sudo freebsd-version -u").Execute();
Beispiel #27
0
    /////////////////////////////////////////////////////////
    //  概要:ssh接続処理
    //  はまみ:2020/02/20
    /////////////////////////////////////////////////////////
    static public Boolean Connect(string strHostName, string strLoginId, string strPassword, ref string strResult)
    {
        Boolean bRet = true;

        try
        {
            // 接続情報
            ConnectionInfo ConnNfo = new ConnectionInfo(strHostName, 22, strLoginId, new PasswordAuthenticationMethod(strLoginId, strPassword));
            // SSHクライアント生成
            m_sshClient = new SshClient(ConnNfo);
            m_sshClient.ConnectionInfo.Timeout = new TimeSpan(0, 0, 5);

            // SSH接続
            m_sshClient.Connect();
            // SSH接続成功
            if (m_sshClient.IsConnected)
            {
                using (var client = new SftpClient(ConnNfo))
                {
                    //接続してアップロードディレクトリに移動
                    client.Connect();
                    client.ChangeDirectory("opensmile");
                    string fileName = (@"C:\Users\kikuc\Desktop\gokon-master-2018\Assets\WAV\result.wav");
                    Debug.Log(fileName);
                    using (var fs = System.IO.File.OpenRead(fileName))
                    {
                        //ファイルのアップロード(trueで上書き)
                        client.UploadFile(fs, "result.wav", true);
                    }

                    //接続してダウンロードディレクトリに移動

                    m_shellStream = m_sshClient.CreateShellStream("", 80, 40, 80, 40, 1024);

                    StreamReader streamReader = new StreamReader(m_shellStream, Encoding.GetEncoding("shift_jis"));
                    StreamWriter streamWriter = new StreamWriter(m_shellStream, Encoding.GetEncoding("shift_jis"));
                    streamWriter.AutoFlush = true;
                    //Thread.Sleep(2000);
                    var cmd = "sh /home/yutaka/opensmile/opensmile.sh";
                    streamWriter.WriteLine(cmd);
                    SshCommand sc = m_sshClient.CreateCommand(cmd);
                    sc.Execute();
                    string answer = sc.Result;
                    f_answer = answer;
                    Debug.Log("1:" + answer);
                    //var result = streamReader.ReadToEnd();
                    ResultData.result = answer;
                    //Debug.Log("2:"+result);
                    client.Disconnect();
                    //client.Connect();
                    //client.ChangeDirectory("opensmile");
                    //using (var fs = System.IO.File.OpenWrite("text.txt"))
                    //{
                    //ファイルのダウンロード
                    //client.DownloadFile(@"C:\Users\kikuc\Desktop\gokon-master-2018\Assets\WAV\text.txt", fs);
                    //}
                    //client.Disconnect();
                }
                // コマンド実行

                m_shellStream.Dispose();
                m_sshClient.Disconnect();
                m_sshClient.Dispose();
                //別手法
            }
        }
        catch (Exception ex)
        {
            bRet      = false;
            strResult = ex.ToString();
        }

        return(bRet);
    }
Beispiel #28
0
        public void lancer()
        {
            try
            {
                localaddrr = IPAddress.Parse("127.0.0.1");
                server     = new TcpListener(localaddrr, port);
                server.Start();
                while (true)
                {
                    Console.WriteLine("waiting for connexion");
                    TcpClient client = server.AcceptTcpClient();
                    Console.WriteLine("connected");
                    /*** opening the stream for sending and receiving data **/
                    String        str    = "";
                    NetworkStream stream = client.GetStream();
                    sr = new StreamReader(stream);
                    sw = new StreamWriter(stream);
                    String address, user, mdp;
                    address = null;
                    user    = null; mdp = null;

                    for (int i = 0; i < 3; i++)
                    {
                        if (i == 0)
                        {
                            address = sr.ReadLine();
                        }
                        else if (i == 1)
                        {
                            user = sr.ReadLine();
                        }
                        else
                        {
                            mdp = sr.ReadLine();
                        }
                    }
                    if (connection(address, user, mdp) == 0)
                    {
                        sw.WriteLine("Welcome your are now Connected ");
                        sw.Flush();



                        do
                        {
                            str = sr.ReadLine();
                            /*** The clientssh is static so it use here to create a ssh Command***/
                            SshCommand cmd = clientssh.CreateCommand(str.ToString());
                            Console.WriteLine(str.ToString());
                            cmd.Execute();


                            if (str.Equals("end", StringComparison.OrdinalIgnoreCase))
                            {
                                str = "End transmission";
                            }
                            else
                            {
                                sw.WriteLine(">" + cmd.Result);
                                sw.Flush();
                            }
                        } while (!str.Equals("End transmission", StringComparison.OrdinalIgnoreCase));
                        clientssh.Disconnect();
                        client.Close();
                    }
                    else
                    {
                        sw.WriteLine("Connexion failure ");
                        sw.Flush();
                    }
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine(e.ToString());
            }
            catch (IOException e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                server.Stop();
            }
        }
        protected void btnEnviar_Command(object sender, CommandEventArgs e)
        {
            try
            {
                LoDevices objLo = new LoDevices();
                EnDevices objEn = new EnDevices();

                DataTable dt = new DataTable();

                int   index  = Convert.ToInt32(e.CommandArgument);
                Label rowid  = (Label)grvListado.Rows[index].FindControl("lblrowid");
                Label lblDip = (Label)grvListado.Rows[index].FindControl("lblDip");



                dt = objLo.DevicesJson_Selecionar(Convert.ToInt32(rowid.Text));


                string ruta = "/files/config.json";



                // Setup Credentials and Server Information
                ConnectionInfo ConnNfo = new ConnectionInfo("104.248.211.185", 22, "root", new AuthenticationMethod[] {
                    // Pasword based Authentication
                    new PasswordAuthenticationMethod("root", "iota2019123"),

                    // Key Based Authentication (using keys in OpenSSH Format)
                    new PrivateKeyAuthenticationMethod("root", new PrivateKeyFile[] {
                        new PrivateKeyFile(@"..\openssh.key", "passphrase")
                    }),
                }
                                                            );

                // Execute a (SHELL) Command - prepare upload directory
                using (var sshclient = new SshClient(ConnNfo))
                {
                    sshclient.Connect();
                    using (var cmd = sshclient.CreateCommand("mkdir -p /tmp/uploadtest && chmod +rw /tmp/uploadtest"))
                    {
                        cmd.Execute();
                        Console.WriteLine("Command>" + cmd.CommandText);
                        Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
                    }
                    sshclient.Disconnect();
                }

                // Upload A File
                using (var sftp1 = new SftpClient(ConnNfo))
                {
                    string uploadfn = "Renci.SshNet.dll";

                    sftp1.Connect();
                    sftp1.ChangeDirectory("/opt/prueba/");
                    using (var uplfileStream = System.IO.File.OpenRead(uploadfn))
                    {
                        sftp1.UploadFile(uplfileStream, uploadfn, true);
                    }
                    sftp1.Disconnect();
                }

                // Execute (SHELL) Commands
                using (var sshclient = new SshClient(ConnNfo))
                {
                    sshclient.Connect();

                    // quick way to use ist, but not best practice - SshCommand is not Disposed, ExitStatus not checked...
                    Console.WriteLine(sshclient.CreateCommand("cd /tmp && ls -lah").Execute());
                    Console.WriteLine(sshclient.CreateCommand("pwd").Execute());
                    Console.WriteLine(sshclient.CreateCommand("cd /tmp/uploadtest && ls -lah").Execute());
                    sshclient.Disconnect();
                }
                Console.ReadKey();



                //using (var client = new SshClient("104.248.211.185", "root", "iota2019123"))
                //{
                //    client.Connect();
                //    //client.RunCommand("etc/init.d/networking restart");

                //   client.RunCommand ChangeDirectory("/opt/prueba/");
                //    using (var uplfileStream = System.IO.File.OpenRead(ruta))
                //    {
                //        client.UploadFile(uplfileStream, ruta, true);
                //    }
                //    client.Disconnect();

                //    client.Disconnect();
                //}



                //  SendFileToServer.Send(ruta);

                return;



                FileInfo Archivo = new FileInfo(HttpContext.Current.Server.MapPath(ruta));
                File.WriteAllText(HttpContext.Current.Server.MapPath(ruta), dt.Rows[0]["DJson"].ToString());

                string destino  = "/opt/prueba/";
                string host     = lblDip.Text.Trim();
                string username = grvListado.DataKeys[index].Values["usuario"].ToString();
                string password = Seguridad.DesEncriptar(grvListado.DataKeys[index].Values["clave"].ToString());



                SFTPHelper sftp = new SFTPHelper(host, username, password);
                sftp.Connect();
                sftp.Get(ruta, destino);
                sftp.Disconnect();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #30
0
        private void BackgroundWorker(DateTime startedTime)
        {
            try
            {
                while (true)
                {
                    using (LocalDbContext dbContext = new LocalDbContext())
                    {
                        foreach (CharacterFind characterFind in names.Where(x => !x.Found))
                        {
                            CharacterInfo user = dbContext.Users
                                                 .Where(first =>
                                                        first.name == characterFind.CharacterName)
                                                 .FirstOrDefault();

                            using (var client = new SshClient("192.168.41.28", 22, "root", "F1reF0x"))
                            {
                                client.Connect();
                                string command = $"/usr/local/bin/docker-compose -f /opt/Seat/docker-compose.yml --project-directory /opt/Seat/ exec -T seat-web su -c 'php artisan esi:job:dispatch \"Seat\\\\Eveapi\\\\Jobs\\\\Location\\\\Character\\\\Online\" --character_id={user.character_id}'";
                                //string command = "echo test";
                                using (var cmd = client.CreateCommand(command))
                                {
                                    cmd.Execute();
                                    if (cmd.ExitStatus != 0)
                                    {
                                        Console.WriteLine("Command>" + cmd.CommandText);
                                        Console.WriteLine("Result>" + cmd.Result);
                                        Console.WriteLine("Error>" + cmd.Error);
                                        Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
                                    }
                                }
                                client.Disconnect();
                            }
                        }
                    }

                    Thread.Sleep(20000);

                    using (LocalDbContext dbContext = new LocalDbContext())
                    {
                        foreach (CharacterFind characterFind in names.Where(x => !x.Found))
                        {
                            CharacterInfo user = dbContext.Users
                                                 .Where(first =>
                                                        first.name == characterFind.CharacterName)
                                                 .FirstOrDefault();

                            CharacterOnline online = dbContext.Online
                                                     .Where(first =>
                                                            first.character_id == user.character_id)
                                                     .FirstOrDefault();

                            if (online.online || online.last_login > startedTime)
                            {
                                CharacterFind result = names.FirstOrDefault(x => characterFind.CharacterName == x.CharacterName);
                                if (result != null)
                                {
                                    result.Found = true;
                                }
                            }
                        }
                    }

                    Thread.Sleep(60000);
                }
            }
            catch (Exception error)
            {
                Console.WriteLine($"Crashy : {error.Message}");

                BackgroundWorker(startedTime);
            }
        }
        public static void MacHostJob(string simulator)
        {
            Program.MainLogger.Info($"Starting connection to host {Config.MacHost.Host}, port {Config.MacHost.Port}, user {Config.MacHost.User}");
            var deviceId = "";

            using (var sshClient = new SshClient(Config.MacHost.Host, Config.MacHost.Port, Config.MacHost.User, Config.MacHost.Password))
            {
                sshClient.ErrorOccurred += SshClientOnErrorOccurred;
                sshClient.Connect();

                //if the selected emulator contains the iOS version in his name,
                //we need a bit of string "magic" to find the right UDID
                if (simulator.Contains(" iOS "))
                {
                    Program.MainLogger.Info("Input contains iOS version, activating advanced seatch for simulators");

                    var versionPosition = simulator.IndexOf(" iOS ", StringComparison.Ordinal);
                    var iosVersion      = simulator.Substring(versionPosition + 5).Replace(".", "-");
                    var simulatorKey    = "com.apple.CoreSimulator.SimRuntime.iOS-" + iosVersion;

                    Program.MainLogger.Info("iOS version extracted: " + iosVersion);
                    Program.MainLogger.Info("Dicitonary key generated: " + simulatorKey);

                    Program.MainLogger.Info("Reading emulator list");

                    var comando = "xcrun simctl list --json";
                    SimCtlResponseModel simCtlResponse;
                    using (var cmd = sshClient.CreateCommand(comando))
                    {
                        cmd.Execute();
                        simCtlResponse = JsonConvert.DeserializeObject <SimCtlResponseModel>(cmd.Result);
                    }

                    if (simCtlResponse?.Devices != null && simCtlResponse.Devices.ContainsKey(simulatorKey))
                    {
                        var deviceName = simulator.Substring(0, versionPosition);
                        var device     = simCtlResponse.Devices[simulatorKey].FirstOrDefault(x => x.IsAvailable && x.Name == deviceName);

                        if (device != null)
                        {
                            deviceId = device.Udid;
                        }
                        else
                        {
                            Program.MainLogger.Warn($"Key found but no corresponding simulator found");
                        }
                    }
                    else
                    {
                        Program.MainLogger.Warn("Unable to find simultors in the specified dictionary key");
                    }
                }
                else
                {
                    //No iOS version = only 1 simulator = bash magic!!!
                    Program.MainLogger.Info("Input device does not contain iOS version, recovering the UUID with a single bash command");
                    var comando = "echo $( xcrun simctl list devices | grep -w '" + simulator +
                                  " ' | grep -v -e 'unavailable' | awk 'match($0, /\\(([-0-9A-F]+)\\)/) { print substr( $0, RSTART + 1, RLENGTH - 2 )}' )";
                    using (var cmd = sshClient.CreateCommand(comando))
                    {
                        cmd.Execute();
                        deviceId = cmd.Result;
                    }
                }

                sshClient.Disconnect();
                sshClient.ErrorOccurred -= SshClientOnErrorOccurred;
            }

            if (!string.IsNullOrEmpty(deviceId))
            {
                Program.MainLogger.Info($"Device UDID found: {deviceId}");
                Program.MainLogger.Info("Starting the Remote Simulator");
                RemoteSimulatorHelper.OpenSimulator(deviceId);
            }
            else
            {
                Program.MainLogger.Warn("Device UDID not found, unable to start the Remote Simulator");
            }
        }
Beispiel #32
0
        /// <summary>
        /// Launch <paramref name="exePath"/> on remote host using credentials stored in EditorSettings.
        /// Before launching all the files requires by <paramref name="exePath"/> are copied over to host
        /// using the location specified in EditorSettings.Location. If <paramref name="isCoreCLR"/> is set
        /// all the Xenko native libraries are copied over to the current directory of the game on the remote
        /// host via the `CoreCLRSetup` script.
        /// </summary>
        /// <param name="logger">Logger to show progress and any issues that may occur.</param>
        /// <param name="exePath">Path on the local machine where the executable was compiled.</param>
        /// <param name="isCoreCLR">Is <paramref name="exePath"/> executed against .NET Core?</param>
        /// <returns>True when launch was successful, false otherwise.</returns>
        internal static bool Launch([NotNull] LoggerResult logger, [NotNull] UFile exePath, bool isCoreCLR)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (exePath == null)
            {
                throw new ArgumentNullException(nameof(exePath));
            }

            var host     = XenkoEditorSettings.Host.GetValue();
            var username = XenkoEditorSettings.Username.GetValue();
            var port     = XenkoEditorSettings.Port.GetValue();
            var password = Decrypt(XenkoEditorSettings.Password.GetValue());
            var location = new UDirectory(XenkoEditorSettings.Location.GetValue());
            var display  = XenkoEditorSettings.Display.GetValue();

            var connectInfo = NewConnectionInfo(host, port, username, password);

            if (SyncTo(connectInfo, exePath.GetFullDirectory(), UPath.Combine(location, new UDirectory(exePath.GetFileNameWithoutExtension())), logger))
            {
                var sshClient = new SshClient(connectInfo);
                try
                {
                    sshClient.Connect();
                    if (sshClient.IsConnected)
                    {
                        string     cmdString;
                        SshCommand cmd;

                        // Due to lack of Dllmap config for CoreCLR, we have to ensure that our native libraries
                        // are copied next to the executable. The CoreCLRSetup script will check the 32-bit vs 64-bit
                        // of the `dotnet` runner and copy the .so files from the proper x86 or x64 directory.
                        if (isCoreCLR)
                        {
                            cmdString = "bash -c 'source /etc/profile ; cd " + location + "/" + exePath.GetFileNameWithoutExtension() + ";" + "sh ./CoreCLRSetup.sh'";
                            cmd       = sshClient.CreateCommand(cmdString);
                            cmd.Execute();
                            var err = cmd.Error;
                            if (!string.IsNullOrEmpty(err))
                            {
                                logger.Error(err);
                                // We don't exit here in case of failure, we just print the error and continue
                                // Users can then try to fix the issue directly on the remote host.
                            }
                            else
                            {
                                err = cmd.Result;
                                if (!string.IsNullOrEmpty(err))
                                {
                                    logger.Info(err);
                                }
                            }
                        }
                        // Try to get the main IP of the machine
                        var ipv4             = GetAllLocalIPv4().FirstOrDefault();
                        var connectionRouter = string.Empty;
                        if (!string.IsNullOrEmpty(ipv4))
                        {
                            connectionRouter = " XenkoConnectionRouterRemoteIP=" + ipv4;
                        }
                        var dotnetEngine = XenkoEditorSettings.UseCoreCLR.GetValue() ? " dotnet " : " mono ";
                        if (!string.IsNullOrEmpty(display))
                        {
                            display = " DISPLAY=" + display;
                        }
                        else
                        {
                            display = " DISPLAY=:0.0";
                        }
                        cmdString = "bash -c 'source /etc/profile ; cd " + location + "/" + exePath.GetFileNameWithoutExtension() + ";" + display + connectionRouter + dotnetEngine + "./" + exePath.GetFileName() + "'";
                        cmd       = sshClient.CreateCommand(cmdString);
                        cmd.BeginExecute((callback) =>
                        {
                            var res = cmd.Error;
                            if (!string.IsNullOrEmpty(res))
                            {
                                logger.Error(res);
                            }
                            else
                            {
                                res = cmd.Result;
                                if (!string.IsNullOrEmpty(res))
                                {
                                    logger.Info(res);
                                }
                            }

                            // Dispose of our resources as soon as we are done.
                            cmd.Dispose();
                            sshClient.Dispose();
                        });
                        return(true);
                    }
                }
                catch (Exception)
                {
                    var message = Tr._p("Message", "Unable to launch {0} on host {1}");
                    logger.Error(string.Format(message, exePath, host));
                }
            }

            return(false);
        }
Beispiel #33
0
        private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            _capturedData = 0;
            var connectionInfo = new ConnectionInfo(textBoxIP.Text,
                                                    textBoxUsername.Text,
                                                    new PasswordAuthenticationMethod(textBoxUsername.Text, textBoxPassword.Text));


            _client = new SshClient(connectionInfo);
            _client.Connect();


            PrintCommand(_client.RunCommand("mkfifo /tmp/remcap"));


            var command = _client.CreateCommand("cat /tmp/remcap");

            command.BeginExecute();
            _stream = command.OutputStream;


            var combine  = Path.Combine(textBoxFolder.Text, textBoxPrefix.Text);
            int filetick = 0;

            while (File.Exists(combine + filetick + ".pcap"))
            {
                filetick++;
            }
            _lastFile = combine + filetick + ".pcap";

            ThreadPool.QueueUserWorkItem(x =>
            {
                var fileStream = new FileStream(_lastFile, FileMode.Create);

                int wait = 0;
                while (_stream.CanRead)
                {
                    var readByte = _stream.ReadByte();
                    if (readByte == -1)
                    {
                        if (wait > 10)
                        {
                            if (_client.IsConnected == false)
                            {
                                break;
                            }
                        }

                        Thread.Sleep(100);
                        wait++;
                    }
                    else
                    {
                        fileStream.WriteByte((byte)readByte);
                        _capturedData++;
                        wait = 0;
                    }

                    //if (_stopCapture)
                    //{
                    //    sshClientPipe.Disconnect();
                    //
                    //}
                }

                Print("Stream can no longer be read");

                fileStream.Flush();
                fileStream.Close();
            });

            Thread.Sleep(500);

            var tcpdumpcommand =
                _client.CreateCommand("tcpdump -s 0 -U -n -w - -i any not port " + textBoxPort.Text + " > /tmp/remcap");

            tcpdumpcommand.BeginExecute();
            PrintCommand(tcpdumpcommand);
            //PrintCommand(sshClientCommand.RunCommand("tcpdump -i any -w /tmp/remcap not port " + textBoxPort.Text + ""));


            //var stream = command.OutputStream;
            //using (var fileStream = new FileStream("c:\\temp\\tryfile", FileMode.Create))
            //{
            //    command.Execute();
            //    while (stream.CanRead)
            //    {
            //        byte[] buffer = new byte[24];
            //        stream.Read(buffer, (int) stream.Position, buffer.Length);
            //        fileStream.Write(buffer, (int) fileStream.Position, buffer.Length);
            //    }
            //}
            while (_client.IsConnected)
            {
                Thread.Sleep(1000);
            }
        }
Beispiel #34
0
        public void Test_Execute_Invalid_Command()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                #region Example SshCommand CreateCommand Error

                client.Connect();

                var cmd = client.CreateCommand(";");
                cmd.Execute();
                if (!string.IsNullOrEmpty(cmd.Error))
                {
                    Console.WriteLine(cmd.Error);
                }

                client.Disconnect();

                #endregion

                Assert.Inconclusive();
            }
        }
Beispiel #35
0
 //UiKit
 internal void Sbreload()
 {
     sshclient.ConnectionInfo.Timeout = TimeSpan.FromSeconds(8);
     if (!sshclient.IsConnected)
     {
         sshclient.Connect();
     }
     sshclient.CreateCommand("sbreload").Execute();
     sshclient.Disconnect();
 }
Beispiel #36
0
        public void Test_Execute_OutputStream()
        {
            var host = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

            using (var client = new SshClient(host, username, password))
            {
                #region Example SshCommand CreateCommand Execute OutputStream
                client.Connect();

                var cmd = client.CreateCommand("ls -l");   //  very long list
                var asynch = cmd.BeginExecute();

                var reader = new StreamReader(cmd.OutputStream);

                while (!asynch.IsCompleted)
                {
                    var result = reader.ReadToEnd();
                    if (string.IsNullOrEmpty(result))
                        continue;
                    Console.Write(result);
                }
                cmd.EndExecute(asynch);

                client.Disconnect();
                #endregion

                Assert.Inconclusive();
            }
        }
Beispiel #37
0
        static int Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console()
                         .CreateLogger();
            var command = new RootCommand()
            {
                new Option <string>(
                    "--version",
                    getDefaultValue: (() => "1.12.2"),
                    description: "Set upload version."),
                new Option <string>(
                    "--host",
                    getDefaultValue: (() => ""),
                    description: "Set the host."),
                new Option <string>(
                    "--name",
                    description: "Set user name."),
                new Option <string>(
                    "--password",
                    description: "Set password.")
            };

            command.Description = "Config of uploader";

            command.Handler = CommandHandler.Create <string, string, string, string>((version, host, name, password) =>
            {
                using var scpClient = new ScpClient(host, 20002, name, password);
                scpClient.Connect();
                if (scpClient.IsConnected)
                {
                    Log.Logger.Information("SCP服务器连接成功");
                }
                else
                {
                    Log.Logger.Error("SCP服务器连接失败");
                    return;
                }

                var md5s = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.md5");
                md5s.ToList().ForEach(_ => { scpClient.Upload(File.OpenRead(_), $"/var/www/html/files/{Path.GetFileName(_)}"); });
                var fs = File.OpenRead($"./Minecraft-Mod-Language-Package-{version}.zip");
                switch (version)
                {
                case "1.12.2":
                    scpClient.Upload(fs, "/var/www/html/files/Minecraft-Mod-Language-Modpack.zip.1");
                    break;

                case "1.16":
                    scpClient.Upload(fs, "/var/www/html/files/Minecraft-Mod-Language-Modpack-1-16.zip.1");
                    break;

                case "1.18":
                    scpClient.Upload(fs, "/var/www/html/files/Minecraft-Mod-Language-Modpack-1-18.zip.1");
                    break;

                default:
                    break;    //不应该
                }
                Log.Logger.Information("上传成功");
                scpClient.Dispose();
                using var sshClient = new SshClient(host, 20002, name, password);
                sshClient.Connect();
                if (sshClient.IsConnected)
                {
                    Log.Logger.Information("SSH服务器连接成功");
                }
                else
                {
                    Log.Logger.Error("SSH服务器连接失败");
                    return;
                }
                switch (version)
                {
                case "1.12.2":
                    var cmd1 = sshClient.CreateCommand("mv /var/www/html/files/Minecraft-Mod-Language-Modpack.zip.1 /var/www/html/files/Minecraft-Mod-Language-Modpack.zip");
                    cmd1.Execute();
                    var err1 = cmd1.Error;
                    Log.Logger.Error(err1);
                    break;

                case "1.16":
                    var cmd2 = sshClient.CreateCommand("mv /var/www/html/files/Minecraft-Mod-Language-Modpack-1-16.zip.1 /var/www/html/files/Minecraft-Mod-Language-Modpack-1-16.zip");
                    cmd2.Execute();
                    var err2 = cmd2.Error;
                    Log.Logger.Error(err2);
                    break;

                case "1.18":
                    var cmd3 = sshClient.CreateCommand("mv /var/www/html/files/Minecraft-Mod-Language-Modpack-1-18.zip.1 /var/www/html/files/Minecraft-Mod-Language-Modpack-1-18.zip");
                    cmd3.Execute();
                    var err3 = cmd3.Error;
                    Log.Logger.Error(err3);
                    break;

                default:
                    break;    //不应该
                }
                sshClient.Dispose();
            });

            return(command.Invoke(args));
        }
 public void Test_Execute_Command_Same_Object_Different_Commands()
 {
     using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         client.Connect();
         var cmd = client.CreateCommand("echo 12345");
         cmd.Execute();
         Assert.AreEqual("12345\n", cmd.Result);
         cmd.Execute("echo 23456");
         Assert.AreEqual("23456\n", cmd.Result);
         client.Disconnect();
     }
 }
Beispiel #39
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, this is a test SSH connection");

            // Setup Credentials and Server Information
            ConnectionInfo ConnNfo = new ConnectionInfo("192.168.0.106", 22, "pi",
                                                        new AuthenticationMethod[] {
                // Pasword based Authentication
                // new PasswordAuthenticationMethod("pi","catanf85"),

                // Key Based Authentication (using keys in OpenSSH Format)
                new PrivateKeyAuthenticationMethod("pi", new PrivateKeyFile[] {
                    new PrivateKeyFile(@"..\test.keys", "")
                }),
            }
                                                        );

            // Execute a (SHELL) Command - prepare upload directory
            using (var sshclient = new SshClient(ConnNfo))
            {
                sshclient.KeepAliveInterval = new TimeSpan(0, 0, 10);
                sshclient.Connect();
                using (var cmd = sshclient.CreateCommand("mkdir -p /tmp/uploadtest && chmod +rw /tmp/uploadtest"))
                {
                    cmd.Execute();
                    Console.WriteLine("Command>" + cmd.CommandText);
                    Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
                }



                if (sshclient.IsConnected)
                {
                    try
                    {
                        // esempio di forwarding locale: dalla 22 del server ssh alla 9091 del pc client
                        var port = new ForwardedPortLocal("127.0.0.1", 9091, "127.0.0.1", 22);
                        sshclient.AddForwardedPort(port);
                        port.Start();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }


                    try
                    {
                        // esempio di forwarding remoto: dalla 5001 del pc client alla 50000 del server ssh
                        var port = new ForwardedPortRemote("127.0.0.1", 50000, "127.0.0.1", 5001);
                        sshclient.AddForwardedPort(port);
                        port.Start();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }

                Console.ReadLine();
                sshclient.Disconnect();
            }
        }
Beispiel #40
0
 public static string GetRunning(SshClient sshClient) => sshClient.CreateCommand("sudo freebsd-version -r").Execute();
        private void RunCommand()
        {
            // check if the windows wallet is installed at %AppData%\Bitradio\\
            //if (!Directory.Exists(@"%AppData%\Bitradio\\"))
            //{
            //    MessageBox.Show("Have you installed the Wallet at /%AppData%/Roaming/Bitradio ?");  //If not
            //    return;
            //}

            //check for existing masternode.conf
            if (!File.Exists(@"%AppData%\Bitradio\\masternode.conf"))
            {
                using (StreamWriter sw = new StreamWriter(Environment.ExpandEnvironmentVariables(@"%AppData%\Bitradio\\masternode.conf"), true))  //if not than create
                {
                }
            }

            //load all variables

            ip             = ip_feld.Text;
            username       = username_feld.Text;
            password       = password_feld.Text;
            port           = port_feld.Text;
            genkey         = genkey_feld.Text;
            output         = output_feld.Text;
            output_after   = after_output_feld.Text;
            masternodename = masternodename_feld.Text;
            string TEMP_PATH = Path.GetTempPath();



            //login and create connection
            using (var client = new SshClient(ip, Convert.ToInt16(port), username, password))
            {
                // check if everything givem
                try
                {
                    client.Connect();
                    //port = null;
                    //masternodename = null;
                    //output_after = null;
                    //genkey = null;
                    //output = null;
                }
                catch
                {
                    if (language_info == "deu")
                    {
                        MessageBox.Show("Bitte fülle die Felder IP, Benutzername, Benutzerpasswort, rcuser und rpcpasswort aus!");
                    }
                    else if (language_info == "rus")
                    {
                        MessageBox.Show("Пожалуйста, укажите IP, пользователя, пароль, ключ (genkey), порт, выход, число после выхода и имя мастерноды!");
                    }
                    else
                    {
                        MessageBox.Show("Please fill out the IP, user, password, genkey, port, output, after_output and masternodename!");  //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_bitradio/");
                var result  = command.BeginExecute();
                command = client.CreateCommand("cd /root/temp_bitradio/");
                result  = command.BeginExecute();

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

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

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

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

            // execute the ./Bitradiod install script (self-made)
            using (var client = new SshClient(ip, Convert.ToInt16(port), username, password))
            {
                client.Connect();

                var command = client.CreateCommand("./Bitradiod getblockcount");
                var result  = command.BeginExecute();
                if (startup_checkbox.Checked)
                {
                    command = client.CreateCommand("sudo wget https://raw.githubusercontent.com/Roalkege/bitradio_masternode_creator/master/Bitradio_MN_tool_cron.sh && bash Bitradio_MN_tool_cron.sh");  //download the script
                    result  = command.BeginExecute();
                }
                else
                {
                    command = client.CreateCommand("sudo wget https://raw.githubusercontent.com/Roalkege/bitradio_masternode_creator/master/Bitradio_MN_tool.sh && bash Bitradio_MN_tool.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);


                command = client.CreateCommand("cd ~");
                result  = command.BeginExecute();
                command = client.CreateCommand("rm Bitradio_MN_tool.sh");  //remove the script
                result  = command.BeginExecute();
                if (language_info == "ger")
                {
                    MessageBox.Show("Masternode wurde installiert, starte jetzt deine Windows Wallet neu und starte den Alias");
                }
                else if (language_info == "rus")
                {
                    MessageBox.Show("Мастернода установлена, теперь перезагрузите кошелек и начните работать в режиме анонимности.");
                }
                else
                {
                    MessageBox.Show("Masternode installed now restart your windows wallet and start the Alias");
                }
                client.Disconnect();
            }


            //edit the lokal masternode.conf
            using (StreamWriter sw = new StreamWriter(Environment.ExpandEnvironmentVariables(TEMP_PATH + @"\masternode.conf"), true))
            {
                sw.Write(masternodename + " " + ip + ":32454 " + genkey + " " + output + " " + output_after + " " + "\r\n");
            }
        }
 public void Test_Execute_Timeout()
 {
     using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         client.Connect();
         var cmd = client.CreateCommand("sleep 10s");
         cmd.CommandTimeout = TimeSpan.FromSeconds(5);
         cmd.Execute();
         client.Disconnect();
     }
 }
Beispiel #43
0
        static void Main(string[] args)
        {
            Console.WriteLine("SSH Monitor.");

            // read the settings by newtonsoft.json

            List <string> additionalCommands = new List <string>()
            {
                //"sudo crontab -r",
                //"service spider start"
            };

            DirectoryInfo baseDir = new DirectoryInfo(AppContext.BaseDirectory);

            var sshFiles = baseDir.GetFiles("*.ssh.json");

            if (sshFiles.Length == 0)
            {
                // create an example setting file
                var example = new List <UbuntuOperation>()
                {
                    new UbuntuOperation()
                    {
                        Name     = "example connection",
                        Host     = "host.com",
                        Username = "******",
                        Password = "******",
                        Commands = new List <BashCommand>()
                        {
                            new BashCommand()
                            {
                                Command = "ls -1 | wc -l",
                                Title   = "Count Files in Root:"
                            }
                        }
                    }
                };

                string exampleFilename = "example.ssh.json";

                File.WriteAllText($"{AppContext.BaseDirectory}/{exampleFilename}", JsonConvert.SerializeObject(example, Formatting.Indented));

                Console.WriteLine($@"An Example Setting is generate to {exampleFilename}");
            }
            else
            {
                foreach (var setting in sshFiles)
                {
                    var json = File.ReadAllText(setting.FullName);
                    var list = JsonConvert.DeserializeObject <List <UbuntuOperation> >(json);

                    // access each of linux server by ssh connection and execute the bash
                    foreach (var operation in list)
                    {
                        ConnectionInfo connectionInfo = new ConnectionInfo(operation.Host, operation.Username, new AuthenticationMethod[] {
                            new PasswordAuthenticationMethod(operation.Username, operation.Password)
                        });

                        SshClient sshClient = new SshClient(connectionInfo);

                        Console.WriteLine($"Connecting to {operation.Name} ({operation.Host}):");

                        sshClient.Connect();

                        if (operation.Commands != null)
                        {
                            foreach (var cmd in operation.Commands)
                            {
                                var result = sshClient.CreateCommand(cmd.Command).Execute();
                                if (cmd.Results == null)
                                {
                                    cmd.Results = new List <BashResult>();
                                }
                                cmd.Results.Add(new BashResult()
                                {
                                    Time   = DateTime.Now,
                                    Result = result
                                });
                                // print the last 3 results:
                                Console.WriteLine($"{cmd.Title}:");
                                for (var i = cmd.Results.Count - 1; i >= 0 && i > cmd.Results.Count - 4; i--)
                                {
                                    Console.WriteLine($"  {cmd.Results[i].Time} : {cmd.Results[i].Result}");
                                }
                            }
                        }

                        foreach (var cmd in additionalCommands)
                        {
                            var result = sshClient.CreateCommand(cmd).Execute();
                        }
                    }

                    File.WriteAllText(setting.FullName, JsonConvert.SerializeObject(list, Formatting.Indented));
                }
            }



            Console.WriteLine("Press Any Key to Exit...");
            Console.ReadKey();
        }
 private static bool ExecuteTestCommand(SshClient s)
 {
     var testValue = Guid.NewGuid().ToString();
     var command = string.Format("echo {0}", testValue);
     var cmd = s.CreateCommand(command);
     var result = cmd.Execute();
     result = result.Substring(0, result.Length - 1);    //  Remove \n character returned by command
     return result.Equals(testValue);
 }
Beispiel #45
0
        public void ConfigurateDevice(StationModel station)
        {
            if (station?.InformationTable == null)
            {
                return;
            }
            UserName = station?.InformationTable?.UserNameDevice;
            Password = station?.InformationTable?.PasswordDevice;
            var ipAddressDevice = station?.InformationTable?.IpDevice;
            var stationId       = station.Id;

            station.InformationTable
            ?.CheckAccessCode();
            var accessCode = station.InformationTable
                             ?.AccessCode;

            using (var ssh = new SshClient(ipAddressDevice, UserName, Password))
            {
                try
                {
                    ssh.Connect();
                }
                catch (Exception ex)
                {
                    var manager = new ContextManager();
                    if (CheckPingDevice(ipAddressDevice))
                    {
                        StationModel newStation = null;
                        if (string.Equals(station.InformationTable.PasswordDevice, "$olnechniKrug2019"))
                        {
                            newStation = manager.ChangePassword(station, "$olnechniKrug");
                        }
                        else
                        {
                            newStation = manager.ChangePassword(station, "$olnechniKrug2019");
                        }
                        ConfigurateDevice(newStation);
                    }
                    Logger.WriteLog($"Произошла ошибка при попытки соеденения {ex.Message}, подробности {ex.StackTrace}", "ConfigurateDevice");
                    return;
                }
                var command = ssh.CreateCommand("ls .config/autostart", Encoding.UTF8);
                command.Execute();
                var answer = command.Result;
                if (answer.Contains("chromium.desktop\n"))
                {
                    command = ssh.CreateCommand("rm -f .config/autostart/chromium.desktop\n");
                    command.Execute();
                }
                using (var sftp = new SftpClient(ipAddressDevice, UserName, Password))
                {
                    try
                    {
                        sftp.Connect();
                    }
                    catch (SshConnectionException ex)
                    {
                        Logger.WriteLog($"Произошла ошибка при попытки соеденения {ex.Message}, подробности {ex.StackTrace}", "ConfigurateDevice");
                        return;
                    }
                    var text = new List <string>();
                    text.Add("[Desktop Entry]");
                    text.Add("Encoding=UTF-8");
                    text.Add("Name=Connect");
                    text.Add("Comment=Checks internet connectivity");
                    text.Add($"Exec=/usr/bin/chromium-browser -incognito --noerrdialogs --kiosk http://92.50.187.210/citystations/Home/DisplayInformationTable?stationId={stationId}&accessCode={accessCode}");
                    try
                    {
                        sftp.AppendAllLines(".config/autostart/chromium.desktop", text);
                    }
                    catch (SftpPermissionDeniedException ex)
                    {
                        Logger.WriteLog($"Произошла ошибка при попытки создания файлов {ex.Message}, подробности {ex.StackTrace}", "ConfigurateDevice");
                        if (!ssh.IsConnected)
                        {
                            ssh.Connect();
                        }
                        command = ssh.CreateCommand("sudo rm -f -r .config/autostart\n");
                        try
                        {
                            command.Execute();
                        }
                        catch (SshException sshex)
                        {
                            Logger.WriteLog($"Произошла ошибка при попытки удаления папки {ex.Message}, подробности {ex.StackTrace}", "ConfigurateDevice");
                            return;
                        }
                        command = ssh.CreateCommand("mkdir .config/autostart\n");
                        try
                        {
                            command.Execute();
                        }
                        catch (SshException sshexep)
                        {
                            Logger.WriteLog($"Произошла ошибка при попытки создания папки {ex.Message}, подробности {ex.StackTrace}", "ConfigurateDevice");
                            return;
                        }
                        try
                        {
                            sftp.AppendAllLines(".config/autostart/chromium.desktop", text);
                        }
                        catch (SftpPermissionDeniedException sftpError)
                        {
                            Logger.WriteLog($"Произошла ошибка при попытки добавления данных в файл {ex.Message}, подробности {ex.StackTrace}", "ConfigurateDevice");
                            return;
                        }
                    }
                }
                if (!ssh.IsConnected)
                {
                    ssh.Connect();
                }
                command = ssh.CreateCommand("sudo reboot now\n", Encoding.UTF8);
                try
                {
                    command.Execute();
                }
                catch (SshConnectionException ex)
                {
                    Logger.WriteLog($"Выполнена перезагрузка устройства {ipAddressDevice}", "ConfigurateDevice");
                    return;
                }
            }
        }
Beispiel #46
0
 public void CreateCommand_CommandTextAndEncoding_NeverConnected()
 {
     using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
     {
         try
         {
             client.CreateCommand("ls", Encoding.UTF8);
             Assert.Fail();
         }
         catch (SshConnectionException ex)
         {
             Assert.IsNull(ex.InnerException);
             Assert.AreEqual("Client not connected.", ex.Message);
         }
     }
 }
Beispiel #47
0
        /// <summary>
        /// Initiate shutdown
        /// </summary>
        private async void InitiateShutdown()
        {
            await Report("SHUTDOWN_INITIATED");

            // Keyboard auth for ESXi server
            var kbAuth = new KeyboardInteractiveAuthenticationMethod(_config.Esxi.Username);

            kbAuth.AuthenticationPrompt += (sender, args) =>
            {
                foreach (var prompt in args.Prompts)
                {
                    if (prompt.Request.IndexOf("Password:"******"Uploading shutdown script to /tmp");
            using (var sftp = new SftpClient(sshInfo))
            {
                sftp.ErrorOccurred += (sender, args) =>
                                      _logger.LogError(args.Exception, "An error occurred when connecting to ESXi server");

                sftp.Connect();
                sftp.ChangeDirectory("/tmp");

                await using (var fileStream =
                                 File.OpenRead(Path.Combine(_hostEnvironment.ContentRootPath, "shutdown.sh")))
                {
                    sftp.UploadFile(fileStream, "shutdown.sh", true);
                    _logger.LogInformation("Upload complete");
                }

                sftp.Disconnect();
            }

            // Execute shutdown script
            _logger.LogInformation("Executing shutdown script");
            using (var sshClient = new SshClient(sshInfo))
            {
                sshClient.Connect();
                if (!sshClient.IsConnected)
                {
                    return;
                }

                using (var cmd = sshClient.CreateCommand("chmod +x /tmp/shutdown.sh && /tmp/shutdown.sh"))
                {
                    cmd.Execute();

                    _logger.LogInformation("SSH command> {0}", cmd.CommandText);
                    _logger.LogInformation("SSH result> '{0}' ({1})", cmd.Result, cmd.ExitStatus);

                    if (cmd.ExitStatus == 0)
                    {
                        await Report("SHUTDOWN_COMPLETED");
                    }
                }

                sshClient.Disconnect();
            }
        }
Beispiel #48
0
        private void SSHCommandThread(IP selectedIP, string command, string commandinresult, string login, string password, bool showWindow = true, bool addToListBoxTask = true)
        {
            Thread runThread = new Thread(new ThreadStart(() =>
            {
                ItemListBoxTask curItemLBT = new ItemListBoxTask()
                {
                    IPOrName = selectedIP.NBNameOrIP(), Description = $"Выполняется {command}", CVZNumber = $"ЦВЗ№{SelectedTT.NumberCVZ.ToString()}", IsIndeterminate = true
                };

                //Dispatcher.Invoke(() =>
                //{

                if (addToListBoxTask)
                {
                    Dispatcher.Invoke(() =>
                    {
                        Bindings.listBoxTaskItemsSource.Add(curItemLBT);
                    });
                }
                try
                {
                    this.Log(string.Format($"Выполнение {command} на {selectedIP.NBNameOrIP()}..."), false, false, string.Empty, true);
                    string nbNameOrIP = selectedIP.NBNameOrIP();
                    string ipaddress  = selectedIP.IPAddress;


                    using (SshClient client = new SshClient(ipaddress, login, password))
                    {
                        client.Connect();
                        StringBuilder commandBuild = new StringBuilder();
                        commandBuild.AppendLine(@"#!/bin/bash");
                        commandBuild.AppendLine($"TempPass={password}");
                        commandBuild.AppendLine(commandinresult);
                        string commandExec    = commandBuild.ToString().Replace("\r\n", "\n");
                        bool uploadFileStoped = false;

                        var runCommand = client.CreateCommand(commandExec);
                        var runClient  = runCommand.BeginExecute((x) =>
                        {
                            var temp = curItemLBT.StopProcess;
                            if (curItemLBT.StopProcess)
                            {
                                if (!uploadFileStoped)
                                {
                                    try
                                    {
                                        uploadFileStoped = true;
                                        showWindow       = false;
                                        client.Disconnect();
                                        //return $"Прервано выполнение {command}";
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }
                            }
                        });

                        string result = runCommand.EndExecute(runClient);

                        client.Disconnect();
                        if (showWindow)
                        {
                            base.Dispatcher.BeginInvoke((Action)(() =>
                            {
                                SSHReportWindow window = new SSHReportWindow(this)
                                {
                                    Owner = this,
                                    Title = string.Format($"Команда SSH {command} на {nbNameOrIP}"),
                                    Text = { Text = result },
                                    SSHStatusBarText = { Text = string.Format($"Команда SSH {command} на {nbNameOrIP} выполнена.") }
                                };
                                this.Log(window.SSHStatusBarText.Text, false, false, "", false);
                                window.Show();
                            }));
                        }
                    }
                }
                catch (ArgumentException exception)
                {
                    Log("Необходимо выбрать логин и пароль", true, true, exception.StackTrace, false);
                }
                catch (Exception exception)
                {
                    this.Log(exception.Message, true, true, exception.StackTrace, false);
                }

                //});
            }));

            runThread.Start();


            //while (!curItemLBT.StopProcess || (runThread.ThreadState != System.Threading.ThreadState.Stopped) || (runThread.ThreadState != System.Threading.ThreadState.Aborted))
            //{

            //    if (!(runThread.ThreadState == System.Threading.ThreadState.Stopped))
            //    {
            //        runThread.Abort();
            //    }
            //}
        }
Beispiel #49
0
        static async Task runAsync(string[] args)
        {
            var config         = System.IO.File.ReadAllLines("client.config");
            var connectionInfo = new ConnectionInfo(config[2],
                                                    config[3],
                                                    new PasswordAuthenticationMethod(config[3], config[4]));
            var sshClient  = new SshClient(connectionInfo);
            var sshCommand = config[5];

            var client = new TelegramClient(int.Parse(config[0]), config[1]);
            await client.ConnectAsync();

            if (!client.IsUserAuthorized())
            {
                Console.WriteLine("Please enter your phone number");
                var number = Console.ReadLine();
                var hash   = await client.SendCodeRequestAsync(number);

                Console.WriteLine("Enter the code you recieved from Telegram");
                var    code = Console.ReadLine();
                TLUser user = null;
                try
                {
                    user = await client.MakeAuthAsync(number, hash, code);
                }
                catch (CloudPasswordNeededException)
                {
                    var password = await client.GetPasswordSetting();

                    Console.WriteLine("Enter your 2FA Password");
                    var password_str = Console.ReadLine();
                    user = await client.MakeAuthWithPasswordAsync(password, password_str);
                }
            }

            var result = await client.GetContactsAsync();

            var userToSendTo = result.Users
                               .Where(x => x.GetType() == typeof(TLUser))
                               .Cast <TLUser>()
                               .FirstOrDefault(x => x.Username == "browny99");

            var logPeer = new TLInputPeerUser()
            {
                UserId = userToSendTo.Id
            };

            await client.SendMessageAsync(logPeer, "Started monitoring");

            string UserNameToSendMessage = "@corgigroupagreebot";
            var    unameResult           = await client.SearchUserAsync(UserNameToSendMessage);

            var userByName = unameResult.Users
                             .Where(x => x.GetType() == typeof(TLUser))
                             .OfType <TLUser>()
                             .FirstOrDefault(x => x.Username == UserNameToSendMessage.TrimStart('@'));

            int retryCounter = 0;

            while (!System.IO.File.Exists("cancel.wjdummy"))
            {
                try
                {
                    TLInputPeerUser botToCheck = new TLInputPeerUser()
                    {
                        UserId = userByName.Id, AccessHash = (long)userByName.AccessHash
                    };
                    await client.SendMessageAsync(botToCheck, "/start");

                    await Task.Delay(TimeSpan.FromSeconds(30));

                    TLAbsMessages history = await client.GetHistoryAsync(botToCheck, limit : 1);

                    TLMessagesSlice slice   = (TLMessagesSlice)history;
                    var             message = ((TLMessage)slice.Messages.ElementAt(0));

                    if (message.Out == false && message.Message.StartsWith("Hey, good to see you again"))
                    {
                        var request = new TLRequestReadHistory();
                        request.Peer = botToCheck;
                        await client.SendRequestAsync <TLAffectedMessages>(request);

                        retryCounter = 0;
                    }
                    else
                    {
                        retryCounter++;
                        await client.SendMessageAsync(logPeer, "30 sec unresponsive");
                    }
                    if (retryCounter > 5)
                    {
                        sshClient.Connect();
                        var res = sshClient.CreateCommand(sshCommand).Execute();
                        sshClient.Disconnect();
                        await client.SendMessageAsync(logPeer, "Restarted server\n\n" + res);

                        await Task.Delay(TimeSpan.FromSeconds(90));

                        retryCounter = 0;
                    }
                } catch (Exception e)
                {
                    try
                    {
                        await client.SendMessageAsync(logPeer, "Error: \n" + e.ToString());
                    } catch (Exception ex)
                    {
                        Console.WriteLine($"ERROR\n\n{e}\n{ex}\n\nENDERROR");
                        return;
                    }
                }
            }
        }