Post Pacific  

Go Back   Post Pacific > PC Garage > Programming

Notices

 
 
Thread Tools Search this Thread Display Modes
Prev Previous Post   Next Post Next
Old 21.07.2007, 18:31   #3
humordwarf
Архивный участник
 
Join Date: Feb 2006
Posts: 453
Default

{eng}
these few lines of code = full multithreaded 100% working telnet server %)
implemented login/password with delays thing, and command handler

for now server understands only one command "BYE", but u can easily implenent any thing u want to do remotely. e.g. reboot, kill/restart processes, cpu load, etc, etc..
{/eng}

{rus}
эти несколько строк кода = полный многопоточный 100% рабочий телнет сервер %)
сделан запрос логин/пароль с задержками и обработчик команд

пока сервер понимает только одну команду "BYE", но вы можете с легкостью добавить любые новые штуки, которые вы хотели бы осуществлять удаленно... как то рестарты, работа с процессами, статистика процессора/системы и т.д. и т.п.
{/rus}

compile.bat
Code:
csmc TelnetApp.csp
TelnetServer.csp
Code:
#pragma include TelnetServer.cs

using System;
using HD;

class TelnetApp
{
	const int TelnetPort = 23;

	static void Main(string[] args)
	{
		Console.WriteLine("Sample Telnet Server by HD");
		TelnetServer s = new TelnetServer(TelnetPort);
		s.Start();
	}
}
TelnetServer.cs
Code:
#pragma library System.dll

using System;
using System.IO;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace HD
{
	public class TelnetServerGlobals
	{
		public const string allowedLogin = "admin";
		public const string allowedPassword = "12345";

		public const int maxClients = 2;
		public static int numClients = 0;
	}
	public class TelnetServerThread
	{
		private TcpClient cli;
		private StreamReader sr;
		private StreamWriter sw;
		private string login;
		private string password;
		private bool loginok;

		public bool CommandHandler(string cmd)
		{

			if (cmd=="BYE")
			{
				sw.Write("Bye!");
				sw.Flush();
				return false; //close socket
			}

			sw.WriteLine(cmd+" -> Unknown Command!");
			sw.Flush();

			return true; //continue
		}

		public TelnetServerThread(TcpClient _cli, StreamReader _sr, StreamWriter _sw)
		{
			cli = _cli;
			sr = _sr;
			sw = _sw;
		}

		public void Run()
		{
			Interlocked.Increment(ref TelnetServerGlobals.numClients);
			Console.WriteLine("Client Connected");
			login = "";
			password = "";
			loginok = false;

			try
			{
				sw.WriteLine("Welcome to Pentagon security gateway.");
				sw.Flush();

				while (cli.Connected)
				{      	
					string cmd;

					if (!loginok)
					{

						if (login == "")
						{
							sw.Write("Login: ");
							sw.Flush();
							login = sr.ReadLine();
							Thread.Sleep(1000);
							continue;
						}
		
						if (password == "")
						{
							sw.Write("Password: ");
							sw.Flush();
							password = sr.ReadLine();
							Thread.Sleep(2000);
							continue;
						}
					
						if (login != TelnetServerGlobals.allowedLogin || password != TelnetServerGlobals.allowedPassword)
						{

							sw.WriteLine("cya, hacker");
							sw.Flush();
							break;
						}
						else
						{
							loginok = true;
							sw.WriteLine("Access Granted");
							sw.Flush();
							continue;
						}

					}

					sw.Write(">");
					sw.Flush();
					cmd = sr.ReadLine();
					cmd = cmd.Trim().ToUpper();


					if (CommandHandler(cmd)==false) break;
				}

			cli.Close();
			}
			catch(Exception)
			{
				//catch "Disconnects"
				//Console.WriteLine(e.Message);
			}

			Console.WriteLine("Client Disconnected");
			Interlocked.Decrement(ref TelnetServerGlobals.numClients);
		}

	}

	public class TelnetServer
	{
		private int port;

		private void RunThread(TcpClient cli, StreamReader sr, StreamWriter sw)
		{
			TelnetServerThread c = new TelnetServerThread(cli,sr,sw);
			Thread t = new Thread(new ThreadStart(c.Run));
			t.Start();
		}

		public TelnetServer(int _port)
		{
			port = _port;
		}

		public void Start()
		{
	        	TcpListener server = new TcpListener(IPAddress.Any,port);
            		server.Start();
            		Console.WriteLine("Server Started");
            		while (true)
            		{
            			TcpClient client = server.AcceptTcpClient(); 
            			NetworkStream stream = client.GetStream();
				StreamReader _sr = new StreamReader(stream);
				StreamWriter _sw = new StreamWriter(stream);
				if (TelnetServerGlobals.numClients>=TelnetServerGlobals.maxClients)
				{
					_sw.WriteLine("Too many clients. Try again later.");
					_sw.Flush();
					client.Close();
				}
				else
				{
					RunThread(client,_sr,_sw);
				}
            		}
		}

	}
}
humordwarf is offline  
 

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT. The time now is 04:56.