예제 #1
2
        public void Test_Connect_Handle_HostKeyReceived()
        {
            var host = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;
            var hostKeyValidated = false;

            #region Example SshClient Connect HostKeyReceived
            using (var client = new SshClient(host, username, password))
            {
                client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                {
                    hostKeyValidated = true;

                    if (e.FingerPrint.SequenceEqual(new byte[] { 0x00, 0x01, 0x02, 0x03 }))
                    {
                        e.CanTrust = true;
                    }
                    else
                    {
                        e.CanTrust = false;
                    }
                };
                client.Connect();
                //  Do something here
                client.Disconnect();
            }
            #endregion

            Assert.IsTrue(hostKeyValidated);
        }
        public void Test_KeyExchange_Rekeying()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, 22, Resources.USERNAME, Resources.PASSWORD);

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                //  TODO:   Add test to test re-keying
                Assert.Inconclusive();
                client.Disconnect();
            }
        }
예제 #3
1
    static void Main(string[] args)
    {
        // Setup Credentials and Server Information
        ConnectionInfo ConnNfo = new ConnectionInfo("10.141.3.110",22,"root",
            new AuthenticationMethod[]{

                // Pasword based Authentication
                new PasswordAuthenticationMethod("root","ismail"),

            }
        );

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

            // quick way to use ist, but not best practice - SshCommand is not Disposed, ExitStatus not checked...
            Console.WriteLine("telnet localhost 6571");
            Console.WriteLine("denemeeeeeee");
            //Console.WriteLine(sshclient.CreateCommand("cd /tmp && ls -lah").Execute());
            //Console.WriteLine(sshclient.CreateCommand("pwd").Execute());
            //Console.WriteLine(sshclient.CreateCommand("cd /tmp/uploadtest && ls -lah").Execute());
            sshclient.Disconnect();
        }
        Console.ReadKey();
    }
        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();
            }
        }
예제 #5
1
        public void BeginExecuteTest()
        {
            string expected = "123\n";
            string result;

            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                #region Example SshCommand CreateCommand BeginExecute IsCompleted EndExecute

                client.Connect();

                var cmd = client.CreateCommand("sleep 15s;echo 123"); // Perform long running task

                var asynch = cmd.BeginExecute();

                while (!asynch.IsCompleted)
                {
                    //  Waiting for command to complete...
                    Thread.Sleep(2000);
                }
                result = cmd.EndExecute(asynch);
                client.Disconnect();

                #endregion

                Assert.IsNotNull(asynch);
                Assert.AreEqual(expected, result);
            }
        }
 public void Test_AddForwardedPort_Remote_Hosts_Are_Null()
 {
     using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         client.Connect();
         var port1 = client.AddForwardedPort<ForwardedPortRemote>(null, 8080, null, 80);
         client.Disconnect();
     }
 }
 public void CleanCurrentFolder()
 {
     using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         client.Connect();
         client.RunCommand("rm -rf *");
         client.Disconnect();
     }
 }
 public void Test_AddForwardedPort_Invalid_PortNumber()
 {
     using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         client.Connect();
         var port1 = client.AddForwardedPort<ForwardedPortRemote>("localhost", IPEndPoint.MaxPort+1, "www.renci.org", IPEndPoint.MaxPort+1);
         client.Disconnect();
     }
 }
 public void Test_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();
     }
 }
예제 #10
1
        public void Test_HostKey_SshDss_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.HostKeyAlgorithms.Clear();
            connectionInfo.HostKeyAlgorithms.Add("ssh-dss", (data) => { return new KeyHostAlgorithm("ssh-dss", new DsaKey(), data); });

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
예제 #11
1
        public void Test_HMac_Sha1_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, 22, Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.HmacAlgorithms.Clear();
            connectionInfo.HmacAlgorithms.Add("hmac-sha1", (key) => { return new HMac<SHA1Hash>(key.Take(20).ToArray()); });

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
        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();
            }
        }
예제 #13
0
 public void Disconnect()
 {
     Task.Run(() =>
     {
         _sshClient?.Disconnect();
     });
 }
 //Dispose implementation & Destructor
 public void Dispose()
 {
     _sftpClient?.Disconnect();
     _sftpClient?.Dispose();
     _sshClient?.Disconnect();
     _sshClient?.Dispose();
 }
예제 #15
0
 public void Dispose()
 {
     _shell?.Dispose();
     _shell?.Close();
     _sshClient?.Disconnect();
     _sshClient?.Dispose();
 }
예제 #16
0
        public void Dispose()
        {
            sshClient?.Disconnect();
            sshClient?.Dispose();

            scpClient?.Disconnect();
            scpClient?.Dispose();
        }
 public void Test_AddForwardedPort_Local_Hosts_Are_Empty()
 {
     using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         client.Connect();
         var port1 = client.AddForwardedPort<ForwardedPortLocal>(string.Empty, 8080, string.Empty, 80);
         client.Disconnect();
     }
 }
예제 #18
0
        public GameResult Disconnect()
        {
            Dispose();
            Client?.Disconnect();
            var result = new GameResult {
                Succes = !Client?.IsConnected ?? true
            };

            return(result);
        }
예제 #19
0
        public void Test_Cipher_Aes256CBC_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, 22, Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.Encryptions.Clear();
            connectionInfo.Encryptions.Add("aes256-cbc", new CipherInfo(256, (key, iv) => { return new AesCipher(key, new CbcCipherMode(iv), null); }));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
예제 #20
0
파일: HMacTest.cs 프로젝트: sshnet/SSH.NET
        public void Test_HMac_Sha256_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.HmacAlgorithms.Clear();
            connectionInfo.HmacAlgorithms.Add("hmac-sha2-256", new HashInfo(32 * 8, CryptoAbstraction.CreateHMACSHA256));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
예제 #21
0
        public void Test_HMac_Sha1_96_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.HmacAlgorithms.Clear();
            connectionInfo.HmacAlgorithms.Add("hmac-sha1", new HashInfo(20 * 8, key => HashAlgorithmFactory.CreateHMACSHA1(key, 96)));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
        public void Test_KeyExchange_GroupExchange_Sha256_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, 22, Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.KeyExchangeAlgorithms.Clear();
            connectionInfo.KeyExchangeAlgorithms.Add("diffie-hellman-group-exchange-sha256", typeof(KeyExchangeDiffieHellmanGroupExchangeSha256));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
예제 #23
0
        public void Test_HMac_MD5_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.HmacAlgorithms.Clear();
            connectionInfo.HmacAlgorithms.Add("hmac-md5", new HashInfo(16 * 8, HashAlgorithmFactory.CreateHMACMD5));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
예제 #24
0
        public void Test_Cipher_Cast128CBC_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.Encryptions.Clear();
            connectionInfo.Encryptions.Add("cast128-cbc", new CipherInfo(128, (key, iv) => { return new CastCipher(key, new CbcCipherMode(iv), null); }));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
예제 #25
0
        public void Test_Connect_Using_Correct_Password()
        {
            var host = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

            #region Example SshClient(host, username) Connect
            using (var client = new SshClient(host, username, password))
            {
                client.Connect();
                //  Do something here
                client.Disconnect();
            }
            #endregion
        }
예제 #26
0
        /// <summary>
        /// Disconnects.
        /// </summary>
        /// <returns></returns>
        public override async Task Disconnect()
        {
            if (SshClient == null)
            {
                return;
            }
            this.WriteLog("Disconnecting...");
            var ports = ForwardedPorts?.ToList();

            if (ports?.Count > 0)
            {
                foreach (var pf in ports)
                {
                    try
                    {
                        await pf.Disconnect();
                    }
                    catch (Exception ex)
                    {
                        MyLogger.Log("Failed to close a forwarded port.", ex);
                    }
                }
                ports.ForEach(x => Children.Remove(x));
                this.WriteLog("Closed All Forwarded Ports.");
            }
            if (SshClient != null)
            {
                try
                {
                    await Task.Run(() =>
                    {
                        SshClient?.Disconnect();
                        SshClient?.Dispose();
                        SshClient = null;
                    });

                    this.WriteLog("Disconnected.");
                }
                catch (Exception ex)
                {
                    this.WriteLog("Failed to disconnect or dispose.", ex);
                }
            }
            await DisconnectRequiredConnection();

            IsConnecting.Value = false;
            IsConnected.Value  = false;
        }
예제 #27
0
        private void Disconnect()
        {
            lock (_lock)
            {
                if (Connected)
                {
                    _shellStream?.Close();
                    _shellStream = null;

                    _sshClient?.Disconnect();
                    _sshClient = null;
                }

                _connectionValid = false;
            }
        }
        //[TestMethod]
        public void Test_MultipleThread_10000_MultipleSessions()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                client.Connect();
                System.Threading.Tasks.Parallel.For(0, 10000,
                    (counter) =>
                    {
                        var result = ExecuteTestCommand(client);
                        Debug.WriteLine(string.Format("TestMultipleThreadMultipleConnections #{0}", counter));
                        Assert.IsTrue(result);
                    }
                );

                client.Disconnect();
            }
        }
        protected void Arrange()
        {
            _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));

            _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict);
            _sessionMock = new Mock<ISession>(MockBehavior.Strict);

            var sequence = new MockSequence();
            _serviceFactoryMock.InSequence(sequence).Setup(p => p.CreateSession(_connectionInfo)).Returns(_sessionMock.Object);
            _sessionMock.InSequence(sequence).Setup(p => p.Connect());
            _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting());
            _sessionMock.InSequence(sequence).Setup(p => p.Dispose());

            _sshClient = new SshClient(_connectionInfo, false, _serviceFactoryMock.Object);
            _sshClient.Connect();
            _sshClient.Disconnect();
        }
예제 #30
0
 protected void RebootButton_Click(object sender, EventArgs e)
 {
     try
     {
         using (var client = new SshClient("ra-jetson.duckdns.org", "ubuntu", "savingL1v3s"))
         {
             client.Connect();
             client.RunCommand("sudo /home/ubuntu/Desktop/bandhan/SQL-Scripts/./RightAlertRemoteRebootIssued-SQL"); // SSH Command Here
             client.RunCommand("sudo reboot"); // SSH Command Here
             client.Disconnect();
         }
     }
     catch (Exception ex)
     {
         Response.Redirect("Down.html");
     }
 }
        public void Test_PrivateKeyConnectionInfo()
        {
            var host = Resources.HOST;
            var username = Resources.USERNAME;
            MemoryStream keyFileStream = new MemoryStream(Encoding.ASCII.GetBytes(Resources.RSA_KEY_WITHOUT_PASS));

            #region Example PrivateKeyConnectionInfo PrivateKeyFile
            var connectionInfo = new PrivateKeyConnectionInfo(host, username, new PrivateKeyFile(keyFileStream));
            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
            #endregion

            Assert.AreEqual(connectionInfo.Host, Resources.HOST);
            Assert.AreEqual(connectionInfo.Username, Resources.USERNAME);
        }
        public void Test_Execute_Command_Asynchronously()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                client.Connect();

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

                cmd.EndExecute(asyncResult);

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

                client.Disconnect();
            }
        }
예제 #33
0
        private void Connect()
        {
            lock (_lock)
            {
                if (Connected)
                {
                    Disconnect();
                }

                try
                {
                    using (var authMethod = new PasswordAuthenticationMethod(_username, _password))
                    {
                        var connectionInfo = new ConnectionInfo(_host, _port, _username, authMethod);

                        _sshClient = new SshClient(connectionInfo);
                        _sshClient.Connect();
                        _shellStream = _sshClient.CreateShellStream("xterm", 80, 24, 800, 600, 1024);

                        // This will pull the initial login prompt off the stream
                        _shellStream.Expect(new Regex(_terminalPrompt));
                    }

                    _connectionValid = true;
                }
                catch (Exception)
                {
                    _connectionValid = false;

                    _shellStream?.Close();
                    _shellStream = null;

                    _sshClient?.Disconnect();
                    _sshClient = null;

                    throw;
                }
            }
        }
예제 #34
0
        public void Test_Run_SingleCommand()
        {
            var host = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

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

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

                client.Disconnect();
                #endregion

                Assert.IsTrue(result.Equals(testValue));
            }
        }
예제 #35
0
        public void Test_PasswordConnectionInfo_PasswordExpired()
        {
            var host = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

            #region Example PasswordConnectionInfo PasswordExpired
            var connectionInfo = new PasswordConnectionInfo("host", "username", "password");
            var encoding = new Renci.SshNet.Common.ASCIIEncoding();
            connectionInfo.PasswordExpired += delegate(object sender, AuthenticationPasswordChangeEventArgs e)
            {
                e.NewPassword = encoding.GetBytes("123456");
            };

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

                client.Disconnect();
            }
            #endregion

            Assert.Inconclusive();
        }
예제 #36
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);
    }
예제 #37
0
파일: Form1.cs 프로젝트: Neophear/MassSSH
        private void WrkrRunScript_DoWork(object sender, DoWorkEventArgs e)
        {
            Action actnEnableDisableButtons = () => btnRun.Enabled = !(btnStop.Enabled = true);

            btnRun.Invoke(actnEnableDisableButtons);
            MinListe <Script> scripts = new MinListe <Script>();

            if (e.Argument != null)
            {
                scripts.Add((Script)e.Argument);
            }
            else
            {
                scripts = scol.Scripts;
            }

            foreach (Script script in scripts)
            {
                WriteOutput($"---Running script: {script.Name}");

                foreach (Host host in script.Hosts)
                {
                    if (wrkrRunScript.CancellationPending)
                    {
                        break;
                    }
                    WriteOutput($"Connecting to {host.Name}... ");

                    //if (host.ConType == null)
                    //    WriteOutput("Connection-mode has not been set!", false);
                    //else
                    //{
                    try
                    {
                        //if (host.ConType == connectionType.SSH)
                        //{
                        using (SshClient client = new SshClient(host.Address, txtUsername.Text, txtPassword.Text))
                        {
                            if (wrkrRunScript.CancellationPending)
                            {
                                break;
                            }
                            client.Connect();

                            if (client.IsConnected)
                            {
                                if (wrkrRunScript.CancellationPending)
                                {
                                    break;
                                }
                                WriteOutput("Connected!", false);

                                using (ShellStream ss = client.CreateShellStream("dumb", 80, 24, 800, 600, 1024))
                                {
                                    WriteOutput(scom.ReadToEnd(ss, 300), false);
                                    foreach (string c in script.Commands)
                                    {
                                        if (wrkrRunScript.CancellationPending)
                                        {
                                            break;
                                        }
                                        //WriteOutput(scom.SendCommandCR(c, ss, 300), false);
                                        WriteOutput(scom.SendCommandLF(c, ss, 300), false);
                                    }
                                }

                                client.Disconnect();
                                WriteOutput("Disconnected!", false);
                            }
                            else
                            {
                                WriteOutput("Connection failed!", false);
                            }
                        }
                        //}
                        //else
                        //{
                        //    if (wrkrRunScript.CancellationPending) break;
                        //    WriteOutput("Connecting to {0}...", host.Name);
                        //    TelnetCOM tc = new TelnetCOM(host.Address, 23);
                        //    string s = tc.Login(txtPassword.Text, 1000);
                        //    string prompt = s.TrimEnd();
                        //    prompt = s.Substring(prompt.Length - 1, 1);
                        //    if (prompt != "$" && prompt != ">")
                        //        WriteOutput("Connection failed!", false);
                        //    else
                        //    {
                        //        foreach (string c in script.Commands)
                        //        {
                        //            if (wrkrRunScript.CancellationPending) break;
                        //            tc.WriteLine(c);
                        //            WriteOutput(tc.Read());
                        //        }
                        //    }
                        //    WriteOutput("Disconnected!");
                        //}
                    }
                    catch (Renci.SshNet.Common.SshAuthenticationException)
                    {
                        WriteOutput("Authentication failed!", false);
                    }
                    catch (ArgumentException ex)
                    {
                        if (ex.Message == "username")
                        {
                            WriteOutput("Username missing!", false);
                        }
                        else
                        {
                            WriteOutput("CAUGHT: " + ex.ToString());
                        }
                    }
                    catch (System.Net.Sockets.SocketException se)
                    {
                        switch (se.ErrorCode)
                        {
                        case 10060:
                            WriteOutput("Connection timed out!", false);
                            break;

                        case 11001:
                            WriteOutput("Could not find host!", false);
                            break;

                        default:
                            WriteOutput("CAUGHT: " + se.ToString());
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        WriteOutput("CAUGHT: " + ex.ToString());
                    }
                    //}
                }

                WriteOutput($"---Finished script: {script.Name}{Environment.NewLine}");
            }
        }
예제 #38
0
        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;
            }
        }
예제 #39
0
        private static void RunEx(ClientConfiguration.SshOptions config)
        {
            BondManager.CurrentPorts.Clear();

            try
            {
                _log.Info(
                    $"Starting SSH client with {config.KeepAliveIntervalInSeconds}s keep-alive to {config.Host}:{config.Port} as {config.Username}...");

                using (var client = new SshClient(config.Host, config.Port, config.Username, config.Password))
                {
                    try
                    {
                        client.Connect();
                        client.KeepAliveInterval = TimeSpan.FromSeconds(config.KeepAliveIntervalInSeconds);

                        client.ErrorOccurred   += delegate(object sender, ExceptionEventArgs e) { _log.Trace(e); };
                        client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                        {
                            _log.Trace($"Host key received: {e.HostKey}:{e.HostKeyName}");
                        };

                        foreach (var forwardedPort in config.SshPorts)
                        {
                            //define port and add it to client
                            var port = new ForwardedPortRemote(forwardedPort.Server, forwardedPort.ServerPort, forwardedPort.Guest,
                                                               forwardedPort.GuestPort);
                            client.AddForwardedPort(port);

                            //add delegates to handle port exceptions and requests received
                            port.Exception       += delegate(object sender, ExceptionEventArgs e) { _log.Info(e.Exception.ToString()); };
                            port.RequestReceived += delegate(object sender, PortForwardEventArgs e)
                            {
                                _log.Info($"{e.OriginatorHost}:{e.OriginatorPort}—{sender}");
                            };

                            //start the port, which will give us connection information back from server
                            port.Start();
                            //get that bound port from server
                            _log.Info($"Bound port: {port.BoundPort} - Is started?: {port.IsStarted}");

                            forwardedPort.ServerPort = port.BoundPort;

                            if (!BondManager.CurrentPorts.Contains(forwardedPort))
                            {
                                BondManager.CurrentPorts.Add(forwardedPort);
                            }
                        }

                        var result = client.RunCommand("uptime");
                        _log.Info(result.Result);

                        while (client.IsConnected)
                        {
                            // ... hold the port open ... //
                            Thread.Sleep(1000);
                        }
                    }
                    catch (SocketException se)
                    {
                        _log.Error(se);
                    }
                    catch (Exception e)
                    {
                        _log.Error(e);
                    }
                    finally
                    {
                        try
                        {
                            foreach (var port in client.ForwardedPorts)
                            {
                                port.Stop();
                                client.RemoveForwardedPort(port);
                                _log.Info($"Bound port stopped and removed: {port}");
                            }
                        }
                        catch (Exception e)
                        {
                            _log.Error(e);
                        }

                        client.Disconnect();
                        _log.Info($"Client disconnected...");
                    }
                }
            }
            catch (SocketException se)
            {
                _log.Error(se);
            }
            catch (Exception e)
            {
                _log.Error(e);
            }
        }
예제 #40
0
 private void closeConnection()
 {
     sshclient.Disconnect();
     sshclient.Dispose();
     sshclient = null;
 }
예제 #41
0
        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");
            }
        }
예제 #42
0
 public override void Disconnect()
 {
     UnixClient.Disconnect();
 }
예제 #43
0
        public void Test_Cipher_Arcfour256_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.Encryptions.Clear();
            connectionInfo.Encryptions.Add("arcfour256", new CipherInfo(256, (key, iv) => { return new Arc4Cipher(key, true); }));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
예제 #44
0
 //UiKit
 internal void Sbreload()
 {
     sshclient.ConnectionInfo.Timeout = TimeSpan.FromSeconds(8);
     if (!sshclient.IsConnected)
     {
         sshclient.Connect();
     }
     sshclient.CreateCommand("sbreload").Execute();
     sshclient.Disconnect();
 }
        public static async Task <IActionResult> RunSshCommand([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "actions/run_ssh_command")] HttpRequest req, ILogger log, ExecutionContext context)
        {
            try
            {
                // Make sure the request was send from the IFTTT service
                if (req.Headers["IFTTT-Service-Key"] != GetIFTTTServiceKey(context))
                {
                    return(CreateErrorResponse("Unable to validate IFTTT Service Key", StatusCodes.Status401Unauthorized));
                }

                //
                // Parse the request
                //
                string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                JObject jObject     = JObject.Parse(requestBody);

                IActionResult errorActionResult = null;

                //
                // Load all the parameters
                //
                if (!TryLoadActionField(jObject, "hostname", out string hostname, out errorActionResult))
                {
                    return(errorActionResult);
                }

                if (!TryLoadActionField(jObject, "port", out string stringPort, out errorActionResult))
                {
                    return(errorActionResult);
                }
                if (!int.TryParse(stringPort, out int port))
                {
                    return(CreateErrorResponse($"Unable to parse action field port value '{stringPort}' as an integer", StatusCodes.Status400BadRequest));
                }

                if (!TryLoadActionField(jObject, "username", out string username, out errorActionResult))
                {
                    return(errorActionResult);
                }

                if (!TryLoadActionField(jObject, "password", out string password, out errorActionResult))
                {
                    return(errorActionResult);
                }

                if (!TryLoadActionField(jObject, "command", out string command, out errorActionResult))
                {
                    return(errorActionResult);
                }

                //
                // Connect the SSH Client, and send the request
                //
                if (!IsTestRequest(hostname))
                {
                    using (var client = new SshClient(hostname, port, username, password))
                    {
                        client.Connect();
                        SshCommand sshCommand = client.RunCommand(command);
                        string     execResult = sshCommand.Result;
                        client.Disconnect();

                        log.LogInformation($"Command executed with result {execResult}");
                    }
                }

                //
                // Create the response, and send it
                //
                dynamic result = new JObject();
                result.data = new JArray();
                (result.data as JArray).Add(new JObject());
                result.data[0].id = "1";

                return(new OkObjectResult(result));
            }
            catch (Exception ex)
            {
                return(CreateErrorResponse($"Exception: {ex.Message}", StatusCodes.Status500InternalServerError));
            }
        }
예제 #46
0
파일: Run.cs 프로젝트: thurday/puttystorm
        /// <summary>
        /// Handling of Bash script execution
        /// </summary>
        public void ExecuteBashScript(DataGridView dataGridView1, string text, string _hostname, string _username,
                                      string _password, string _PrivateKey, string _pk_pwd)
        {
            WriteDataGridViewOutput(dataGridView1, _hostname, null, "Running...");

            ConnectionInfo con = null;

            // Use KeyboardInteractiveAuthentication or PasswordAuthenticationMethod
            if (_password != null && _password != "" && !Regex.IsMatch(_password, @"\s+") && _PrivateKey == null)
            {
                Console.WriteLine("## Kotarak using password for login");

                this.password = _password;

                KeyboardInteractiveAuthenticationMethod keybAuth = new KeyboardInteractiveAuthenticationMethod(_username);
                keybAuth.AuthenticationPrompt += new EventHandler <AuthenticationPromptEventArgs>(HandleKeyEvent);

                con = new ConnectionInfo(_hostname, 22, _username, new AuthenticationMethod[]
                {
                    new PasswordAuthenticationMethod(_username, _password),
                    keybAuth
                });
            }
            // Otherwise we have setup PrivateKeyAuthenticationMethod
            else if (_password == null && _PrivateKey != null)
            {
                Console.WriteLine("## Kotarak using private key for login");

                PrivateKeyFile keyFile;
                if (_pk_pwd == null)
                {
                    Console.WriteLine("## OpenSSH private key is not encrypted");
                    keyFile = new PrivateKeyFile(_PrivateKey);
                }
                else
                {
                    Console.WriteLine("## OpenSSH private key IS encrypted!");
                    keyFile = new PrivateKeyFile(_PrivateKey, _pk_pwd);
                }

                var keyFiles = new[] { keyFile };
                con = new ConnectionInfo(_hostname, 22, _username, new PrivateKeyAuthenticationMethod(_username, keyFiles));
            }

            try
            {
                // Connect and execute command
                using (var client = new SshClient(con))
                {
                    client.Connect();

                    // Default params if no command is provided
                    SshCommand terminal = null;
                    string     output   = "Nothing to be executed!";
                    int        exitCode = 999;
                    string     command  = "echo $'" + text.Replace("'", "\\'").Replace("\r", string.Empty) +
                                          "'" + " > PuTTY_STORM_TMP.sh; chmod +x PuTTY_STORM_TMP.sh; OUTPUT=\"$(./PuTTY_STORM_TMP.sh 2>&1)\"; echo $OUTPUT; rm PuTTY_STORM_TMP.sh";

                    if (command != null)
                    {
                        terminal = client.RunCommand(command);
                        Console.WriteLine("Command: " + command + " executed");
                        output   = terminal.Result.TrimEnd('\r', '\n');
                        exitCode = terminal.ExitStatus;
                    }

                    WriteDataGridViewOutput(dataGridView1, _hostname, exitCode, output);

                    client.Disconnect();
                }
            } catch (Exception ex)
            {
                WriteDataGridViewOutput(dataGridView1, _hostname, 999, ex.Message);
            }
        }
예제 #47
0
        public SocketResponse Disconnect()
        {
            string totalResponse = "";

            switch (EquipmentConnectionSetting.ConnectionType)
            {
            case ConnectionType.TcpIp:

                //Add logout sequence here
                if (EquipmentConnectionSetting.LogoutSequences != null && EquipmentConnectionSetting.LogoutSequences.Any())
                {
                    foreach (var sequence in EquipmentConnectionSetting.LogoutSequences.OrderBy(p => p.SequenceNumber))
                    {
                        if (!string.IsNullOrEmpty(sequence.ExpectedResponse))
                        {
                            var response = SendCommandAndWaitForResponse(sequence.Command.Unescape(), new List <string> {
                                sequence.ExpectedResponse
                            }, new TimeSpan(0, 0, 0, sequence.Timeout));
                            totalResponse += response + Environment.NewLine;
                            if (response.TimeoutOccurred)
                            {
                                throw new Exception("Unable to logout." + totalResponse);
                            }
                        }
                        else
                        {
                            SendCommand(sequence.Command);
                        }
                    }
                }

                _socketClient.Close();
                break;

            case ConnectionType.Ssh:

                //Add logout sequence here
                if (EquipmentConnectionSetting.LogoutSequences != null && EquipmentConnectionSetting.LogoutSequences.Any())
                {
                    foreach (var sequence in EquipmentConnectionSetting.LogoutSequences.OrderBy(p => p.SequenceNumber))
                    {
                        if (!string.IsNullOrEmpty(sequence.ExpectedResponse))
                        {
                            var response = SendCommandAndWaitForResponse(sequence.Command.Unescape(), new List <string> {
                                sequence.ExpectedResponse
                            }, new TimeSpan(0, 0, 0, sequence.Timeout));
                            totalResponse += response.Data + Environment.NewLine;
                            if (response.TimeoutOccurred)
                            {
                                throw new Exception("Unable to logout." + totalResponse);
                            }
                        }
                        else
                        {
                            SendCommand(sequence.Command);
                        }
                    }
                }

                _shellStream.Close();
                _sshClient.Disconnect();
                //_sshClient.Dispose();
                break;

            case ConnectionType.Telnet:

                //Add logout sequence here
                if (EquipmentConnectionSetting.LogoutSequences != null && EquipmentConnectionSetting.LogoutSequences.Any())
                {
                    foreach (var sequence in EquipmentConnectionSetting.LogoutSequences.OrderBy(p => p.SequenceNumber))
                    {
                        if (!string.IsNullOrEmpty(sequence.ExpectedResponse))
                        {
                            var response = SendCommandAndWaitForResponse(sequence.Command.Unescape(), new List <string> {
                                sequence.ExpectedResponse
                            }, new TimeSpan(0, 0, 0, sequence.Timeout));
                            totalResponse += response.Data + Environment.NewLine;
                            if (response.TimeoutOccurred)
                            {
                                throw new Exception("Unable to logout." + totalResponse);
                            }
                        }
                        else
                        {
                            SendCommand(sequence.Command);
                        }
                    }
                }

                _socketClient.Close();
                break;

            default:
                throw new NotImplementedException();
            }

            return(new SocketResponse
            {
                Data = totalResponse,
                TimeoutOccurred = false
            });
        }
예제 #48
0
 private void MainFormClosing(object sender, FormClosingEventArgs e)
 {
     sshClient.Disconnect();
     sshClient.Dispose();
 }
        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");
            }
        }
예제 #50
0
 public static bool DisConnect()
 {
     ssh.Disconnect();
     sftp.Disconnect();
     return(true);
 }
예제 #51
0
 public void CloseSession()
 {
     _client.Disconnect();
 }
예제 #52
0
        private static void Connect()
        {
            if (Command.Length <= 8)
            {
                Help("connect");
                return;
            }
            if (!Command.EndsWith("-p"))
            {
                if (!File.Exists(Keys))
                {
                    Console.Write("SWSH private key file not found. (I)mport or (G)enerate?: ");
                    switch (Console.ReadKey().Key)
                    {
                    case ConsoleKey.I:
                        ImportKey();
                        break;

                    case ConsoleKey.G:
                        Keygen();
                        break;

                    default:
                        Console.WriteLine(" <= Invalid option.");
                        return;
                    }
                    return;
                }
                if (string.IsNullOrEmpty(ReadKeys()[1]))
                {
                    Color("WARNING: No public key detected.\n", ConsoleColor.Yellow);
                }
            }

            var ccinfo = CreateConnection(Command.Remove(0, 8));

            if (ccinfo == null)
            {
                return;
            }
            Console.Write($"Waiting for response from {ccinfo.Username}@{ccinfo.Host}...\n");
            using (var ssh = new SshClient(ccinfo)) {
                ssh.Connect();
                Color($"Connected to {ccinfo.Username}@{ccinfo.Host}...\n", ConsoleColor.Green);
                var actual = ssh.CreateShellStream(
                    "xterm-256color",
                    (uint)Console.BufferWidth,
                    (uint)Console.BufferHeight,
                    (uint)Console.BufferWidth,
                    (uint)Console.BufferHeight,
                    Console.BufferHeight, null);
                //Read Thread
                var read = new Thread(() => {
                    if (!actual.CanRead)
                    {
                        return;
                    }
                    while (true)
                    {
                        Console.WriteLine(actual.ReadLine());
                    }
                });
                //Write Thread
                new Thread(() => {
                    if (!actual.CanWrite)
                    {
                        return;
                    }
                    while (true)
                    {
                        try {
                            actual.WriteLine("");
                            var input = Console.ReadLine();
                            Console.Write("\b\r\b\r");
                            actual.WriteLine(input);
                            if (input != "exit")
                            {
                                continue;
                            }
                            actual.Dispose();
                            read.Abort();
                            throw new Exception();
                        } catch (Exception) {
                            Color($"Connection to {ccinfo.Username}@{ccinfo.Host}, closed.\n",
                                  ConsoleColor.Yellow);
                            Color("(E)xit SWSH - Any other key to reload SWSH: ", ConsoleColor.Blue);
                            var key = Console.ReadKey();
                            if (key.Key != ConsoleKey.E)
                            {
                                Process.Start(Assembly.GetExecutingAssembly().Location);
                            }
                            ssh.Disconnect();
                            Environment.Exit(0);
                        }
                    }
                }).Start();
                read.Start();
                while (true)
                {
                }
            }
        }
예제 #53
0
        private void Read()
        {
            PasswordAuthenticationMethod authenticationMethod = null;
            SshClient ssh    = null;
            String    oldKey = null;
            String    key    = null;

            while (IsReading)
            {
                // 如何取消掉该任务
                if (Ct.IsCancellationRequested)
                {
                    // another thread decided to cancel
                    Console.WriteLine("latency page monitor task canceled");
                    ssh.Disconnect();
                    break;
                }

                Thread.Sleep(1000);
                var now = DateTime.Now;
                key = Config.Ip + Config.User + Config.Port.ToString() + Config.Password;

                // 如果config有变动,更新config配置 或者首次连接
                if (Config.Ip != null && Config.User != null && Config.Port != 0 && Config.Password != null && oldKey != key)
                {
                    oldKey = Config.Ip + Config.User + Config.Port.ToString() + Config.Password;
                    authenticationMethod =
                        new PasswordAuthenticationMethod(Config.User, Config.Password);
                    ssh = new SshClient(new ConnectionInfo(
                                            Config.Ip,
                                            Config.Port,
                                            Config.User,
                                            authenticationMethod));
                    ssh.Connect();
                }

                // cpu 监控结果
                string result = "0";
                if (ssh != null)
                {
                    try
                    {
                        var shellCommand = "osqueryi --json 'SELECT * FROM system_info;'";
                        var command      = ssh.CreateCommand(shellCommand, System.Text.Encoding.UTF8);
                        result = command.Execute();
                        var data = JsonConvert.DeserializeObject <List <JObject> >(result);
                        HostName = data[0]["computer_name"].ToString();
                        CpuBrand = data[0]["cpu_brand"].ToString();
                        CoreNum  = data[0]["cpu_physical_cores"].ToString();
                        var memCount = data[0]["physical_memory"].ToString();
                        MemCount = (int.Parse(memCount) / (1024 * 1024)).ToString();

                        RaisePropertyChanged("HostName");
                        RaisePropertyChanged("CpuBrand");
                        RaisePropertyChanged("CoreNum");
                        RaisePropertyChanged("MemCount");

                        shellCommand  = "osqueryi --json 'select version from kernel_info;'";
                        command       = ssh.CreateCommand(shellCommand, System.Text.Encoding.UTF8);
                        result        = command.Execute();
                        data          = JsonConvert.DeserializeObject <List <JObject> >(result);
                        KernelVersion = data[0]["version"].ToString();
                        RaisePropertyChanged("KernelVersion");

                        shellCommand = "osqueryi --json 'select * from os_version;'";
                        command      = ssh.CreateCommand(shellCommand, System.Text.Encoding.UTF8);
                        result       = command.Execute();
                        data         = JsonConvert.DeserializeObject <List <JObject> >(result);
                        OSName       = data[0]["name"].ToString() + " " + data[0]["version"].ToString();
                        RaisePropertyChanged("OSName");

                        shellCommand = "osqueryi --json 'select * from uptime'";
                        command      = ssh.CreateCommand(shellCommand, System.Text.Encoding.UTF8);
                        result       = command.Execute();
                        data         = JsonConvert.DeserializeObject <List <JObject> >(result);
                        UpDays       = "运行" + data[0]["hours"].ToString() + "天,";
                        RaisePropertyChanged("UpDays");

                        shellCommand = "osqueryi --json ' select count(*) as total from processes'";
                        command      = ssh.CreateCommand(shellCommand, System.Text.Encoding.UTF8);
                        result       = command.Execute();
                        data         = JsonConvert.DeserializeObject <List <JObject> >(result);
                        CountProcess = "进程" + data[0]["total"].ToString() + "个,";
                        RaisePropertyChanged("CountProcess");

                        shellCommand = "osqueryi --json \"select count(*) as logged_session from logged_in_users where tty like 'pts%' and type = 'user';\"";
                        command      = ssh.CreateCommand(shellCommand, System.Text.Encoding.UTF8);
                        result       = command.Execute();
                        data         = JsonConvert.DeserializeObject <List <JObject> >(result);
                        LoggedSesion = "SSH登录" + data[0]["logged_session"].ToString() + "个";
                        RaisePropertyChanged("LoggedSesion");

                        shellCommand = "osqueryi --json \" select * from interface_addresses where interface like 'eth%' or interface like 'ens%';\"";
                        command      = ssh.CreateCommand(shellCommand, System.Text.Encoding.UTF8);
                        result       = command.Execute();
                        data         = JsonConvert.DeserializeObject <List <JObject> >(result);
                        Ips          = "";
                        foreach (JObject o in data)
                        {
                            Ips += o["interface"].ToString() + " | " + o["address"].ToString() + "\n";
                        }
                        RaisePropertyChanged("Ips");
                    }
                    catch (Exception e)
                    {
                        // TODO 处理异常
                    }
                }
                // end
            }

            // 断开ssh 连接
            if (ssh != null)
            {
                ssh.Disconnect();
            }
        }
 protected void Act()
 {
     _sshClient.Disconnect();
 }
예제 #55
0
 private static void RemoveAllFiles()
 {
     using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         client.Connect();
         client.RunCommand("rm -rf *");
         client.Disconnect();
     }
 }
예제 #56
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();
            //    }
            //}
        }
예제 #57
0
        public void Test_HMac_RIPEMD160_OPENSSH_Connection()
        {
            var connectionInfo = new PasswordConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD);
            connectionInfo.HmacAlgorithms.Clear();
            connectionInfo.HmacAlgorithms.Add("*****@*****.**", new HashInfo(160, HashAlgorithmFactory.CreateHMACRIPEMD160));

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                client.Disconnect();
            }
        }
예제 #58
0
파일: Run.cs 프로젝트: thurday/puttystorm
        /// <summary>
        /// Handling of Shell command execution.
        /// </summary>
        public void ExecuteCommand(DataGridView dataGridView1, string text, string _hostname, string _username,
                                   string _password, string _PrivateKey, string _pk_pwd)
        {
            WriteDataGridViewOutput(dataGridView1, _hostname, null, "Running...");

            ConnectionInfo con = null;

            // Use KeyboardInteractiveAuthentication or PasswordAuthenticationMethod
            if (_password != null && _password != "" && !Regex.IsMatch(_password, @"\s+") && _PrivateKey == null)
            {
                Console.WriteLine("## Kotarak using password for login");

                this.password = _password;

                KeyboardInteractiveAuthenticationMethod keybAuth = new KeyboardInteractiveAuthenticationMethod(_username);
                keybAuth.AuthenticationPrompt += new EventHandler <AuthenticationPromptEventArgs>(HandleKeyEvent);

                con = new ConnectionInfo(_hostname, 22, _username, new AuthenticationMethod[]
                {
                    new PasswordAuthenticationMethod(_username, _password),
                    keybAuth
                });
            }
            // Otherwise we have setup PrivateKeyAuthenticationMethod
            else if (_password == null && _PrivateKey != null)
            {
                Console.WriteLine("## Kotarak using OpenSSH private key for login");

                PrivateKeyFile keyFile;
                if (_pk_pwd == null)
                {
                    Console.WriteLine("## OpenSSH private key is not encrypted");
                    keyFile = new PrivateKeyFile(_PrivateKey);
                }
                else
                {
                    Console.WriteLine("## OpenSSH private key IS encrypted!");
                    keyFile = new PrivateKeyFile(_PrivateKey, _pk_pwd);
                }

                var keyFiles = new[] { keyFile };
                con = new ConnectionInfo(_hostname, 22, _username, new PrivateKeyAuthenticationMethod(_username, keyFiles));
            }

            string[]        lines    = null;
            MatchCollection commands = null;
            string          command  = null;

            try
            {
                // Parse command from Editor textbox
                if (text.Length > 0)
                {
                    lines = text.Split('\n');

                    foreach (var line in lines)
                    {
                        string match_command = "^\".+?\"$";
                        commands = Regex.Matches(line, match_command);
                    }

                    foreach (Match m in commands)
                    {
                        command = m.Value.Substring(1, m.Value.Length - 2);
                    }
                }
            } catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            try
            {
                // Connect and execute command
                using (var client = new SshClient(con))
                {
                    client.Connect();

                    // Default params if no command is provided
                    SshCommand terminal = null;
                    string     output   = "Nothing to be executed!";
                    int        exitCode = 999;

                    if (command != null)
                    {
                        terminal = client.RunCommand(command);
                        Console.WriteLine("Command: " + command + " executed");
                        Console.WriteLine(terminal.Result);
                        output   = ReplaceTabsWithSpaces(terminal.Result, 4).TrimEnd('\r', '\n');
                        exitCode = terminal.ExitStatus;

                        if (exitCode != 0)
                        {
                            output = terminal.Error.TrimEnd('\r', '\n');
                        }
                    }

                    WriteDataGridViewOutput(dataGridView1, _hostname, exitCode, output);

                    client.Disconnect();
                }
            } catch (Exception ex)
            {
                WriteDataGridViewOutput(dataGridView1, _hostname, 999, ex.Message);
            }
        }
예제 #59
0
 public void Disconnect()
 {
     _sshClient.Disconnect();
 }
예제 #60
0
 private void ButtonStop_Click(object sender, EventArgs e)
 {
     _client.Disconnect();
 }