Exemplo n.º 1
0
        private TelnetConnection LoginToJames()
        {
            TelnetConnection telnet = new TelnetConnection("localhost", 4555);

            System.Console.Out.WriteLine(telnet.Read());
            telnet.WriteLine("root");
            System.Console.Out.WriteLine(telnet.Read());
            telnet.WriteLine("root");
            System.Console.Out.WriteLine(telnet.Read());
            return(telnet);
        }
Exemplo n.º 2
0
        public void Add(AccountData account)
        {
            if (Verify(account))
            {
                return;
            }
            TelnetConnection telnet = LoginToJames();

            telnet.WriteLine("adduser " + account.Name + "" + account.Password);
            System.Console.Out.WriteLine(telnet.Read());
        }
Exemplo n.º 3
0
        public void Delete(AccountData account)
        {
            if (!Verify(account))
            {
                return;
            }
            TelnetConnection telnet = LoginToJames();

            telnet.WriteLine("deluser " + account.Name);
            System.Console.Out.WriteLine(telnet.Read());
        }
Exemplo n.º 4
0
 public CommandThread(
     ThreadSupervisor InSupervisor, TelnetConnection InConn,
     TelnetCommandRoute InCommandRoute,
     RunLogListBox InRunLog)
 {
     mShutdownFlag = new ExtendedManualResetEvent(false);
     mConn         = InConn;
     mCommandRoute = InCommandRoute;
     mRunLog       = InRunLog;
     Supervisor    = InSupervisor;
 }
Exemplo n.º 5
0
        public TelnetConnection Login(AccountData account)
        {
            TelnetConnection telnet = new TelnetConnection("localhost", 4555);

            System.Console.Out.WriteLine(telnet.Read());
            telnet.WriteLine("root");
            System.Console.Out.WriteLine(telnet.Read());
            telnet.WriteLine("root");
            System.Console.Out.WriteLine(telnet.Read());
            return(telnet);
        }
Exemplo n.º 6
0
        public void AddAccount(AccountData account)
        {
            if (IsAccountExists(account))
            {
                return;
            }

            TelnetConnection telnet = LoginToJames();

            telnet.WriteLine("adduser " + account.Username + " " + account.Password);
            Console.Out.WriteLine(telnet.Read());
        }
Exemplo n.º 7
0
        public void DeleteAccount(AccountData account)
        {
            if (!IsAccountExists(account))
            {
                return;
            }

            TelnetConnection telnet = LoginToJames();

            telnet.WriteLine("deluser " + account.Username);
            Console.Out.WriteLine(telnet.Read());
        }
Exemplo n.º 8
0
        public void Delete(AccountData account)
        {
            if (!Verify(account))
            {
                return;
            }
            TelnetConnection telnet = new TelnetConnection("localhost", 4555);

            LoginJames(telnet);
            telnet.WriteLine("deluser " + account.Name + " " + account.Password);
            System.Console.Out.WriteLine(telnet.Read());
        }
Exemplo n.º 9
0
        /// <summary>
        /// Creates and starts task
        /// </summary>
        void start_task()
        {
            _telnet_connection             = new TelnetConnection(Properties.Settings.Default.Ember_Interface_IP_Address, 4900);
            labelSensorMaxMinDetected.Text = "Telnet started @ " + Properties.Settings.Default.Ember_Interface_IP_Address;

            _cancel       = new CancellationTokenSource();
            _monitor_task = new Task(monitor_run, _cancel.Token);
            _monitor_task.ContinueWith(monitor_completed, TaskContinuationOptions.OnlyOnRanToCompletion);
            _monitor_task.ContinueWith(monitor_error, TaskContinuationOptions.OnlyOnFaulted);

            _monitor_task.Start();
        }
Exemplo n.º 10
0
        public void DisableLocalEchoForPlayer()
        {
            _mockTokenFactory.Setup(factory => factory.Command(Command.Do, Option.SuppressLocalEcho))
            .Returns(_mockToken.Object);
            _mockTokenStream.Setup(stream => stream.Write(_mockToken.Object));
            var telnetConnection = new TelnetConnection(_mockTokenStream.Object,
                                                        TelnetHandlerSet.Default(_mockTokenStream.Object));

            telnetConnection.SetRemote(Option.SuppressLocalEcho, true);

            _mockTokenStream.Verify(stream => stream.Write(_mockToken.Object), Times.Once());
        }
Exemplo n.º 11
0
        public void PollConnectionForDataAvailable()
        {
            TokenFactory.Instance = new TokenFactory();
            _mockSocket.Setup(socket => socket.Read())
            .Returns("test string\n".ToBytes());
            var tokenStream = new TokenStream(_mockSocket.Object);
            var connection  = new TelnetConnection(tokenStream, TelnetHandlerSet.Default(tokenStream));

            var data = string.Join("", connection.ReadLines(Encoding.ASCII));

            Assert.AreEqual("test string", data);
        }
Exemplo n.º 12
0
 /// <summary>
 /// Sets the state of the relay
 /// </summary>
 /// <param name="telnet_connection"></param>
 /// <param name="value"></param>
 public static void Set_Relay_State(TelnetConnection telnet_connection, bool value)
 {
     if (value)
     {
         Wait_For_Prompt(telnet_connection);
         telnet_connection.WriteLine("write 1 6 0 1 0x10 {01}");
         Wait_For_Prompt(telnet_connection);
     }
     else
     {
         telnet_connection.WriteLine("write 1 6 0 1 0x10 {00}");
     }
 }
Exemplo n.º 13
0
 static void Main(string[] args)
 {
     telnetCon = new TelnetConnection(args[0], int.Parse(args[1]));
     telnetCon.Connect();
     Thread.Sleep(2000);
     for (int i = 0; i < 20; i++)
     {
         Console.WriteLine("*** Attempt number " + i + " ***");
         printTelnetSetReaction(i);
         printTelnetGetReaction(i);
         Console.WriteLine();
     }
     Console.Read();
 }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            TelnetConnection tc       = new TelnetConnection("192.168.4.1", 80);
            bool             openDoor = false;

            string message = openDoor == true ? "del" : "led";

            if (tc.IsConnected)
            {
                Console.Write(tc.Read());
                tc.WriteLine(message);
                Console.Write(tc.Read());
            }
        }
Exemplo n.º 15
0
        public void DoorManagement(bool openDoor)
        {
            TelnetConnection tc = new TelnetConnection("192.168.4.1", 80);


            string message = openDoor == true ? "del" : "";

            if (tc.IsConnected)
            {
                Console.Write(tc.Read());
                tc.WriteLine(message);
                Console.Write(tc.Read());
            }
        }
Exemplo n.º 16
0
        public void Connect(ToolStripStatusLabel toolStatus, ToolStripProgressBar toolProgress)
        {
            TelnetConnection tc = new TelnetConnection(settings.Address, 23);
            string           s  = tc.Login(settings.Username, settings.Password, 100);

            Console.Write(s);

            tc.WriteLine("/etc/enigma2/AutoRecorder/reconf /etc/enigma2/AutoRecorder/SearchProfiles/Automaatti.prof >/etc/enigma2/AutoRecorder/SearchProfiles/AutomaattiOut.py");

            ftp ftpClient = new ftp(@"ftp://" + settings.Address, settings.Username, settings.Password);

            toolProgress.Value = 65;
            toolStatus.Text    = "Downloading...";
            ftpClient.download("/etc/enigma2/AutoRecorder/SearchProfiles/AutomaattiOut.py", @".\AutomaattiOut.py");
        }
Exemplo n.º 17
0
        /// <summary>
        /// Start autosys session with default Telnet settings
        /// </summary>
        /// <param name="hostname"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public AutosysSession(string hostname, string username, string password)
        {
            Telnet = new TelnetConnection(hostname, 23);
            //login to autosys
            string serverOutput = Telnet.Login(username, password, 300);
            string prompt       = serverOutput.TrimEnd();

            prompt = prompt.Substring(prompt.Length - 1, 1);
            if (prompt != "$" && prompt != ">")
            {
                throw new Exception("Connection failed");
            }
            //default to timeout of 1 second
            CommandTimeoutMs = 1000;
        }
Exemplo n.º 18
0
        private void VisualTelNet_AfterLoad(object sender, EventArgs e)
        {
            //TelnetConnection tc = new TelnetConnection("128.0.0.5", 23);
            TelnetConnection tc = new TelnetConnection("187.9.214.58", 23);

            string a;

            a = tc.Read();

            tc.WriteLine("irko");

            comando = tc.Read();

            Redesenhar();
        }
Exemplo n.º 19
0
        public void AssureReceiveThread(
            TelnetConnection InConn, RunLogListBox InRunLog)
        {
            if (RunningReceiveThread == null)
            {
                AutoResetEvent startReceivingEvent;

                // start the receive from telnet server thread.
                ThreadCommon.StartReceiveFromTelnetServerThread(
                    //          out receiveQueue,
                    out startReceivingEvent, InConn,
                    this,
                    mBackThreadEndFlag, InRunLog);
            }
        }
Exemplo n.º 20
0
        static int Main(string[] args)
        {
            int rc = 0;

            Stream outResultsFile = File.Create("output.txt");
            var    textListener   = new TextWriterTraceListener(outResultsFile);

            Trace.Listeners.Add(textListener);
            string datafile_name = "power_data.txt";

            try
            {
                if (File.Exists(datafile_name))
                {
                    File.Delete(datafile_name);
                }

                kill_em3xx_load();

                openEmberISAChannels();

                TelnetConnection telnet_connection = new TelnetConnection("localhost", 4900);

                CS_Current_Voltage cv  = ember_parse_pinfo_registers(telnet_connection);
                string             msg = string.Format("Cirrus I = {0:F8}, V = {1:F8}, P = {2:F8}", cv.Current, cv.Voltage, cv.Current * cv.Voltage);
                traceLog(msg);

                msg = string.Format("{0:F8},{1:F8},{2:F8}", cv.Voltage, cv.Current, cv.Current * cv.Voltage);
                Console.WriteLine(msg);

                System.IO.StreamWriter file = new System.IO.StreamWriter(datafile_name);
                file.Write(msg);
                file.Close();

                closeEmberISAChannels();
            }
            catch (Exception ex)
            {
                rc = -1;
                traceLog(ex.Message);
                Console.WriteLine(ex.Message);
            }

            Trace.Flush();
            Trace.Close();

            return(rc);
        }
        private TelnetConnection GetTelNetCredentialsByPath(string serverPath)
        {
            ConsolePrint($"Loading credentials to telnet for {serverPath}");
            var path = serverPath.Substring(0, serverPath.LastIndexOf("\\"));

            path = path + "\\serverconfig.xml";
            string port = "0", password;

            if (!System.IO.File.Exists(path))
            {
                MessageBox.Show($"Cant find the configuration file at [{path}]");
                ConsolePrint($"Cant find the configuration file at [{path}]");
                return(null);
            }
            XmlDocument doc = new XmlDocument();

            doc.Load(path);
            foreach (XmlNode property in doc.DocumentElement.ChildNodes)
            {
                if (property.Attributes == null)
                {
                    continue;
                }

                if (property.Attributes["name"].Value == "TelnetPort")
                {
                    port = property.Attributes["value"].Value;
                }
                else if (property.Attributes["name"].Value == "TelnetPassword")
                {
                    password = property.Attributes["value"].Value;
                }
                //TelnetPort
                //TelnetPassword
            }
            var client = new TelnetConnection(serverIp.Text, int.Parse(port));

            if (client.IsConnected)
            {
                client.WriteLine("MesopotamiaTestosterona2");//password
                ConsolePrint($"Telnet Console Connected for {serverPath}");
            }
            else
            {
                ConsolePrint($"FAILED Telnet Console connection for {serverPath}");
            }
            return(client);
        }
Exemplo n.º 22
0
        public bool OpenSession(string host, string username, string password)
        {
            try
            {
                // New connection
                _tc = new TelnetConnection(host, 23);

                // Login
                var usernamePrompt = _tc.Read(2000);
                if (usernamePrompt.Contains("login:"******"Password:"******"admin @ home"))
                {
                    _host     = host;
                    _username = username;
                    _password = password;

                    // Exec 'shell' command
                    _tc.WriteLine("shell");
                    _tc.Read(500);
                    return(true);
                }

                return(false);
            }
            catch
            {
                return(false);
            }
        }
Exemplo n.º 23
0
        // ----------------------------- RunCommand ------------------------------------
        public static void RunCommand(
            ThreadSupervisor InSupervisor,
            TelnetConnection InConn, TelnetCommandRoute InCommandRoute,
            RunLogListBox InRunLog,
            string InCmdText)
        {
            {
                RunLogListBox runLog = new RunLogListBox(InRunLog, "RunCommand");
                CommandThread ct     = new CommandThread(
                    InSupervisor, InConn, InCommandRoute, InRunLog);
                ct.CommandText = InCmdText;

                // run the logout thread.
                CommandThread.ThreadStart(ct);
            }
        }
Exemplo n.º 24
0
        public ReceiveThread(
            TelnetConnection InConn,
            AutoResetEvent InStartReceivingEvent,
            ThreadSupervisor InSupervisor,
            ExtendedManualResetEvent InShutdownFlag,
            RunLogListBox InRunLog)
        {
            mConn = InConn;

            mSupervisor = InSupervisor;
            mSupervisor.AssignRunningReceiveThread(this);

            mStartReceivingEvent = InStartReceivingEvent;
            mRunLog       = new RunLogListBox(InRunLog, "ReceiveThread");
            mShutdownFlag = InShutdownFlag;
        }
Exemplo n.º 25
0
        // ------------------------------ ReadUntilEmpty --------------------------------
        public static string[] ReadUntilEmpty(TelnetConnection InConn)
        {
            List <string> respLines = new List <string>();

            while (true)
            {
                string respLine = InConn.Read(500);
                if ((respLine == null) || (respLine == ""))
                {
                    break;
                }
                respLines.Add(respLine);
            }

            return(respLines.ToArray());
        }
Exemplo n.º 26
0
        public virtual void Connect(TargetInfo target)
        {
            var connectionPort = target.GetPort(ConnectionType.Telnet);

            this.TelnetConnection = new TelnetConnection(target.GetAddress(), connectionPort);
            this.TelnetConnection.TimeOutLoginMs = 1000;
            this.TelnetConnection.TimeOutReadMs  = 30000;
            this.TelnetConnection.CiscoLogin(target.credentials.GetUserName(), target.credentials.GetPassword());

            string adminPass = target.credentials.GetAdminPassword();

            if (!String.IsNullOrEmpty(adminPass))
            {
                this.TelnetConnection.CiscoEnable(adminPass);
            }
        }
Exemplo n.º 27
0
        public void FindMac(string macAddress)
        {
            this.macAddress = macAddress;

            //telnetThread = new Thread(new ThreadStart(HandleComm));
            //telnetThread.Start();

            //login with user "root",password "rootpassword", using a timeout of 100ms, and show server output
            tc = new TelnetConnection(IPAddress, 23);
            string s = tc.Login("clrscr", 1000);

            // server output should end with "$" or ">", otherwise the connection failed
            string prompt = s.TrimEnd();

            prompt = s.Substring(prompt.Length - 1, 1);
            if (prompt != "$" && prompt != ">")
            {
                throw new ConnectionFailedException();
            }

            tc.WriteLine("en");
            tc.WriteLine("clrscr");
            tc.WriteLine(string.Format("show mac address-table address {0} | incl Gi|Fa", macAddress));
            prompt = "";

            Match macFoundOnInterface = Regex.Match(tc.Read(), "(fa|gi)(\\d/|\\d)+", RegexOptions.IgnoreCase);

            if (!macFoundOnInterface.Success)
            {
                throw new MacNotFoundException();
            }
            outgoingPort = macFoundOnInterface.Value;

            SendCommand(string.Format("sho cdp neigh {0} deta | incl IP", outgoingPort));

            string lastLine = tc.Read();

            if (Regex.IsMatch(lastLine, "IP address: ", RegexOptions.IgnoreCase))
            {
                Match IPResult = Regex.Match(lastLine, "\\d+.\\d+.\\d+.\\d+");
                NotifyMacFound(IPResult.Value);
            }
            else
            {
                NotifyMacFound("localhost");
            }
        }
Exemplo n.º 28
0
        public bool Verify(AccountData account)
        {
            TelnetConnection telnet = new TelnetConnection("localhost", 4555);

            LoginJames(telnet);
            telnet.WriteLine("verify " + account.Name + " " + account.Password);
            String s = telnet.Read();

            System.Console.Out.WriteLine(s);
            return(!s.Contains("does not exist"));

            //TelnetConnection telnet = LoginJames();
            //telnet.WriteLine("verify " + account.Name);
            //String s = (telnet.Read());
            //System.Console.Out.WriteLine(s);
            //return ! s.Contains("does not exist");
        }
Exemplo n.º 29
0
        public void OnReceivingCommandCallsCommandReceiveOfHandlerSet()
        {
            var mockHandlerSet = new Mock <TelnetHandlerSet>(_mockTokenStream.Object,
                                                             new Func <Option, TelnetHandler>(option => null),
                                                             new TelnetHandler[0]);
            var mockToken = new Mock <Token>();

            mockToken.Setup(token => token.Handle(It.IsAny <TelnetConnection>()))
            .Returns(true);
            _mockTokenStream.Setup(stream => stream.Read())
            .Returns(new[] { mockToken.Object });
            var telnetConnection = new TelnetConnection(_mockTokenStream.Object, mockHandlerSet.Object);

            var lines = string.Join("", telnetConnection.ReadLines(Encoding.ASCII));

            mockToken.Verify(token => token.Handle(It.IsAny <TelnetConnection>()), Times.Once());
        }
Exemplo n.º 30
0
        public void SetRemoteCallsHandlerSet()
        {
            var mockHandlerSet = new Mock <TelnetHandlerSet>(_mockTokenStream.Object,
                                                             new Func <Option, TelnetHandler>(option => null),
                                                             new TelnetHandler[0]);

            mockHandlerSet.Setup(set => set.SetRemote(Option.SuppressLocalEcho,
                                                      true,
                                                      _mockTokenStream.Object));
            var telnetConnection = new TelnetConnection(_mockTokenStream.Object, mockHandlerSet.Object);

            telnetConnection.SetRemote(Option.SuppressLocalEcho, true);

            mockHandlerSet.Verify(set => set.SetRemote(Option.SuppressLocalEcho,
                                                       true,
                                                       _mockTokenStream.Object));
        }
        public void TelnetConnectionDoesAsStateMachineSays()
        {
            var mocks = new MockRepository();

            var socketConnection = mocks.StrictMock<ISocketConnection>();
            socketConnection.Expect(s => s.Send(new byte[] { 1, 2 }));
            socketConnection
                .Expect( c=> c.ServerDisconnected += null )
                .IgnoreArguments();
            socketConnection
                .Expect(c => c.ConnectionSucceeded += null)
                .IgnoreArguments();
            socketConnection
                .Expect(c => c.ErrorOccurred += null)
                .IgnoreArguments();
            socketConnection
                .Expect(c => c.DataReceived+= null)
                .IgnoreArguments();

            byte[] sendBack1;
            bool isRealData1;
            var telnetStateMachine = mocks.StrictMock<ITelnetStateMachine>();
            telnetStateMachine
                    .Expect(ts => ts.HandleIncomingByte(30, out sendBack1, out isRealData1))
                    .OutRef(new byte[] { 1, 2 }, false);

            byte[] sendBack2;
            bool isRealData2;
            telnetStateMachine
                    .Expect(ts => ts.HandleIncomingByte(40, out sendBack2, out isRealData2))
                    .OutRef(new byte[] {}, true);

            mocks.ReplayAll();
            var connection = new TelnetConnection(socketConnection, telnetStateMachine);
            byte[] realData = connection.ConvertFromInternalFormat(new byte []{30, 40});
            mocks.VerifyAll();

            CollectionAssert.AreEqual(new byte[] { 40 }, realData);
        }
        private static void AssertCommandResult(
            byte[] expectedSendBack,
            byte[] expectedRealData,
            byte[] command
            )
        {
            TelnetStateMachine machine = new TelnetStateMachine();
            TelnetConnection connection = new TelnetConnection(
                    null,
                    machine
                );

            List<byte> actualSendBack;
            List<byte> actualRealData;
            connection.Process(
                    command,
                    out actualSendBack,
                    out actualRealData
                );

            CollectionAssert.AreEqual(expectedSendBack, actualSendBack);
            CollectionAssert.AreEqual(expectedRealData, actualRealData);
        }
Exemplo n.º 33
0
        /// <summary>
        /// Tries to find and Telnet-connect to the (first) running Android Emulator (AVD)
        /// And tries to set up port forwarding on it, so that the ProtoPad Http (command) and Udp (discovery) servers are accessible from your host machine.
        /// </summary>
        /// <returns>Whether the port forwarding setup was succesful (might fail if already set up or ports busy)</returns>
        private static bool? SetupPortForwardingOnAndroidEmulator(int port = 5554)
        {
            var udpCommandResponse = "";
            var tcpCommandResponse = "";
            try
            {
                using (var tc = new TelnetConnection("localhost", port))
                {
                    var connectResponse = tc.Read();
                    if (!connectResponse.Contains("Android Console")) return null;

                    tc.WriteLine(String.Format("redir add udp:{0}:{1}", MulticastForwardedHostPort, UdpDiscoveryServer.UdpServerPort));
                    udpCommandResponse = tc.Read();
                    tc.WriteLine(String.Format("redir add tcp:{0}:{1}", HttpForwardedHostPort, 8080));
                    tcpCommandResponse = tc.Read();
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Unexpected error during Android Emulator Telnet session: {0}", e.Message);
                return null;
            }

            // response in case already set up:
            // "KO: host port already active, use 'redir del' to remove first"

            return udpCommandResponse.Contains("OK") && tcpCommandResponse.Contains("OK");
        }