commit 9cd88e2e1dac7f8fcc5a3b325aa0f4d0a738e276
parent b88cb2137469c33d39c9d5520142e3a7d6b6393a
Author: abdulrahim2002 <89011337+abdulrahim2002@users.noreply.github.com>
Date: Wed, 5 Jul 2023 17:52:23 +0530
initial commit
Diffstat:
8 files changed, 547 insertions(+), 0 deletions(-)
diff --git a/_client.bat b/_client.bat
@@ -0,0 +1,3 @@
+@echo on
+cmd /C "python client.py"
+pause
diff --git a/_telnetServer.bat b/_telnetServer.bat
@@ -0,0 +1,3 @@
+@echo on
+cmd /C "python telnetServer.py"
+pause
diff --git a/client.py b/client.py
@@ -0,0 +1,99 @@
+import socket
+import threading
+import time
+import utility
+# http://172.20.10.4:5000
+IP = utility.get_ip_address() # temperory, for same network, both client and server
+# IP = '172.20.10.4'
+# IP = '172.20.10.3'
+
+c_obj = threading.Condition()
+PORT = 5566
+ADDR = (IP, PORT)
+SIZE = 1024
+FORMATmsg = "utf-8"
+USERNAME = None
+PIN = None
+client = None
+S_PORT = None
+
+
+def send_message():
+ # c_obj.acquire()
+ while True:
+ msg = input("")
+ globals()['client'].send(msg.encode(FORMATmsg))
+
+
+def recieve_messsage():
+ # c_obj.acquire()
+ while True:
+
+ msg = globals()['client'].recv(SIZE).decode(FORMATmsg)
+
+ print(f"[SERVER] {msg}")
+ pass
+
+
+def startClient():
+ print(f"[CONNECTING] Client connecting to server at {IP}:{PORT}")
+ globals()['client'] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ globals()['client'].connect(ADDR)
+ print(f"[CONNECTED] Client connected to server at {IP}:{PORT}")
+
+
+def main():
+ utility.printUI()
+
+ while True:
+ startClient()
+
+ # [TAB] for inputting, sending and verifyin username
+ if globals()['USERNAME'] == None or globals()['USERNAME'] == "!NOTACCEPTED":
+ while True:
+ globals()['USERNAME'] = input("[LOGIN] INPUT USERNAME: ")
+
+ globals()['client'].send(
+ globals()['USERNAME'].encode(FORMATmsg))
+ temp_msg = globals()['client'].recv(SIZE).decode(FORMATmsg)
+ if (temp_msg == globals()['USERNAME']):
+ print(f"[SERVER] Username accepted")
+ break
+ else:
+ print("[NAME ERROR] Try another username")
+ continue
+
+ if globals()['PIN'] == None:
+ globals()['PIN'] = input("[LOGIN] Input PIN: ")
+ globals()['client'].send(globals()['PIN'].encode(FORMATmsg))
+
+ temp_msg = globals()['client'].recv(SIZE).decode(FORMATmsg)
+ print(f"[SERVER] {temp_msg}")
+ if temp_msg == "try again":
+ print(
+ '[SERVER]: PIN not accepted:(\n[SERVER]: Connection failed:(\nTerminating:(\n')
+ globals()['client'].close()
+ exit()
+
+ print(
+ f"[AUTHENTICATED] credentials are verified by server at {IP}:{PORT}")
+
+ print(f"[Waiting] Waiting for port number from {IP}:{PORT}")
+ globals()['client'].send("PORT".encode(FORMATmsg))
+ temp_msg = globals()['client'].recv(SIZE).decode(FORMATmsg)
+ globals()['S_PORT'] = int(temp_msg)
+ print(f"[SERVER] Your port number is {globals()['S_PORT']}")
+ # input("end")
+ break
+
+ thread_recv = threading.Thread(target=recieve_messsage, args=())
+ thread_recv.start()
+ time.sleep(0.1)
+ thread_send = threading.Thread(target=send_message, args=())
+ thread_send.start()
+
+ pass
+
+
+if __name__ == "__main__":
+ main()
diff --git a/streamVideo.bat b/streamVideo.bat
@@ -0,0 +1,3 @@
+@echo on
+cmd /K "python streamVideo.py"
+pause
diff --git a/streamVideo.py b/streamVideo.py
@@ -0,0 +1,103 @@
+from flask import Flask, Response
+import cv2
+import numpy as np
+import pyautogui
+import time
+import utility
+
+FRAME_RATE = 15
+IP = utility.get_ip_address()
+
+app = Flask(__name__)
+
+SCREEN_SIZE = (1280,720)
+# SCREEN_SIZE = (1920,1080)
+
+def gen_frames():
+ while True:
+ start_time = time.time() # Record the start time
+
+ # Capture the screen
+ img = cv2.cvtColor(np.array(pyautogui.screenshot()), cv2.COLOR_RGB2BGR)
+
+ # Resize the screenshot to the desired resolution
+ img = cv2.resize(img, SCREEN_SIZE)
+
+ # Convert the frame to a JPEG image
+ ret, buffer = cv2.imencode('.jpg', img)
+
+ # Yield the image data as bytes
+ yield (b'--frame\r\n'
+ b'Content-Type: image/jpeg\r\n\r\n' + buffer.tobytes() + b'\r\n')
+
+ # Calculate the time elapsed since the start of the loop
+ elapsed_time = time.time() - start_time
+
+ # If the elapsed time is less than the desired time per frame, delay the loop
+ if elapsed_time < 1 / FRAME_RATE:
+ time.sleep(1 / FRAME_RATE - elapsed_time)
+
+@app.route('/')
+def video():
+ return Response(gen_frames(),
+ mimetype='multipart/x-mixed-replace; boundary=frame')
+
+if __name__ == '__main__':
+ print(f'Path: http://{IP}:5000')
+ app.run(host=IP)
+
+
+
+
+# # using threading
+# import threading
+# from flask import Flask, Response
+# import cv2
+# import numpy as np
+# import pyautogui
+# import time
+
+# FRAME_RATE = 15
+# IP = '192.168.1.9'
+
+# app = Flask(__name__)
+
+# SCREEN_SIZE = (1280,720)
+
+# def gen_frames():
+# while True:
+# start_time = time.time()
+
+# img = cv2.cvtColor(np.array(pyautogui.screenshot()), cv2.COLOR_RGB2BGR)
+
+# img = cv2.resize(img, SCREEN_SIZE)
+
+# ret, buffer = cv2.imencode('.jpg', img)
+
+# yield (b'--frame\r\n'
+# b'Content-Type: image/jpeg\r\n\r\n' + buffer.tobytes() + b'\r\n')
+
+# elapsed_time = time.time() - start_time
+
+# if elapsed_time < 1 / FRAME_RATE:
+# time.sleep(1 / FRAME_RATE - elapsed_time)
+
+# @app.route('/')
+# def video():
+# return Response(gen_frames(),
+# mimetype='multipart/x-mixed-replace; boundary=frame')
+
+# def start_flask_app():
+# print(f'Path: http://{IP}')
+# app.run(host=IP)
+
+# if __name__ == '__main__':
+# flask_thread = threading.Thread(target=start_flask_app)
+# flask_thread.start()
+# flask_thread.join()
+
+
+
+
+
+
diff --git a/telnetServer copy.py b/telnetServer copy.py
@@ -0,0 +1,139 @@
+import socket
+import threading
+import random
+import os
+import utility
+import subprocess
+
+parentDir = utility.getpath()
+
+# get server IP
+IP = utility.get_ip_address()
+PORT = 5566
+ADDR = (IP, PORT)
+SIZE = 1024
+FORMATmsg = "utf-8"
+
+u_name = [] # list of usernames
+u_addr = [] # list of ip addresses
+u_conn = [] # list of connections
+u_pin = [] # list of pins
+u_port = [] # list of ports
+
+
+# server functions
+def start():
+ global server
+
+ print(f"SERVER IP = {IP}\n")
+ print("[STARTING] Server is starting...")
+ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ server.bind(ADDR)
+ server.listen()
+ print(f"[LISTENING] Server is listening on {IP}:{PORT}")
+
+# broadcast connection list
+def broadcast(message):
+ if message == 'LIST':
+ for addr in u_conn:
+ msg = str(u_name)
+ msg = "[LIST] CONNECTION LIST: " + msg
+ addr.send(msg.encode(FORMATmsg))
+ msg = str(u_port)
+ msg = "[LIST] CONNECTION LIST: " + msg
+ addr.send(msg.encode(FORMATmsg))
+ else:
+ for addr in u_conn:
+ addr.send(message.encode(FORMATmsg))
+
+# handle client connection
+def handle_client(conn, addr, u_name):
+ print(f"[SERVER] [NEW CONNECTION] {u_name}:{addr} connected.")
+
+ connected = True
+ while connected:
+ msg = conn.recv(SIZE).decode(FORMATmsg)
+
+ print('[Incoming request]: ')
+ print(f"[{u_name}:{addr}] {msg}") # print msg in server console
+
+ print('Executing command...')
+
+ result = executeCommand(msg)
+
+ print(f'Output: {result}')
+ broadcast(result)
+
+ conn.close()
+
+# execute command and return output
+def executeCommand(command):
+ result = os.popen(command).read()
+ return result
+
+def startVideoStream():
+ print('\nStarting video stream...')
+
+ process = subprocess.Popen(['cmd', '/C', 'streamVideo.bat'], creationflags= subprocess.CREATE_NEW_CONSOLE)
+ # exit_code = process.wait()
+
+ print(f'Video Stream: Path: http://{IP}:5000')
+
+def main():
+ utility.printUI()
+ start()
+ startVideoStream()
+
+ temp_port = PORT+1
+ while True:
+ conn, addr = server.accept()
+ while True:
+ temp_name = conn.recv(SIZE).decode(FORMATmsg)
+ print(f"[CLIENT] Username: {temp_name}")
+ if temp_name in u_name:
+ print("[SERVER] Username not accepted")
+ conn.send("NOTACCEPTED!".encode(FORMATmsg))
+ else:
+ print("[SERVER] Username accepted")
+ conn.send(temp_name.encode(FORMATmsg))
+ break
+
+ temp_pin = str(random.randint(1000, 9999))
+ print(f"[AUTHENTICATING] Current Pin: {temp_pin}")
+ msg_pin = conn.recv(SIZE).decode(FORMATmsg)
+
+ if msg_pin != temp_pin:
+ print("[SERVER] PIN not accepted")
+ conn.send("try again".encode(FORMATmsg))
+ continue
+ else:
+ print("[SERVER] PIN accepted")
+ conn.send("!ACCEPTED".encode(FORMATmsg))
+
+
+ conn.recv(SIZE).decode(FORMATmsg)
+ conn.send(str(temp_port).encode(FORMATmsg))
+
+ print(f"[SERVER] {temp_name} added to network")
+
+
+ clientThread = threading.Thread(target=handle_client, args=(conn, addr, temp_name))
+ clientThread.start()
+
+
+ u_pin.append(temp_pin)
+ u_name.append(temp_name)
+ u_addr.append(addr)
+ u_conn.append(conn)
+ u_port.append(temp_port)
+ temp_port += 1
+
+ # broadcast connection list
+ broadcast('LIST')
+
+ print(f"\n[SERVER][ACTIVE CONNECTIONS] {threading.active_count() - 2}")
+ pass
+
+
+if __name__ == "__main__":
+ main()
+\ No newline at end of file
diff --git a/telnetServer.py b/telnetServer.py
@@ -0,0 +1,167 @@
+import socket
+import threading
+import random
+import os
+import utility
+import subprocess
+import pyautogui
+
+
+
+parentDir = utility.getpath()
+
+# get server IP
+IP = utility.get_ip_address()
+PORT = 5566
+ADDR = (IP, PORT)
+SIZE = 1024
+FORMATmsg = "utf-8"
+
+u_name = [] # list of usernames
+u_addr = [] # list of ip addresses
+u_conn = [] # list of connections
+u_pin = [] # list of pins
+u_port = [] # list of ports
+
+
+# server functions
+def start():
+ global server
+
+ print(f"SERVER IP = {IP}\n")
+ print("[STARTING] Server is starting...")
+ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ server.bind(ADDR)
+ server.listen()
+ print(f"[LISTENING] Server is listening on {IP}:{PORT}")
+
+# broadcast connection list
+def broadcast(message):
+ if message == 'LIST':
+ for addr in u_conn:
+ msg = str(u_name)
+ msg = "[LIST] CONNECTION LIST: " + msg
+ addr.send(msg.encode(FORMATmsg))
+ msg = str(u_port)
+ msg = "[LIST] CONNECTION LIST: " + msg
+ addr.send(msg.encode(FORMATmsg))
+ else:
+ for addr in u_conn:
+ addr.send(message.encode(FORMATmsg))
+
+def exec_cmd(msg):
+ result = executeCommand(msg)
+ print(f'Output: {result}')
+ broadcast(result)
+
+# handle client connection
+def handle_client(conn, addr, u_name):
+ print(f"[SERVER] [NEW CONNECTION] {u_name}:{addr} connected.")
+
+ connected = True
+ while connected:
+ msg = conn.recv(SIZE).decode(FORMATmsg)
+
+ print('[Incoming request]: ')
+ print(f"[{u_name}:{addr}] {msg}") # print msg in server console
+
+ print('Executing command...')
+ # str = input()
+ # print(str)
+ str = msg
+ # if str == "exit()":
+ # exit()
+ if str[0]=="!" and str[1]!="!":
+ pyautogui.write(str[1:], interval = 0.05)
+ continue
+ if str[0]== '!' and str[1 == '!']:
+ spl = str[2:].split('~')
+ if len(spl)==1:
+ pyautogui.hotkey(spl[0])
+ continue
+ if len(spl)==2:
+ pyautogui.hotkey(spl[0], spl[1])
+ continue
+
+
+ # result = executeCommand(msg)
+ Thr = threading.Thread(target=exec_cmd, args=(msg,))
+ Thr.start()
+
+ # time.sleep(0.5)
+ # print(f'Output: {result}')
+ # broadcast(result)
+
+ conn.close()
+
+# execute command and return output
+def executeCommand(command):
+ result = os.popen(command).read()
+ return result
+
+def startVideoStream():
+ print('\nStarting video stream...')
+
+ process = subprocess.Popen(['cmd', '/C', 'streamVideo.bat'], creationflags= subprocess.CREATE_NEW_CONSOLE)
+ # exit_code = process.wait()
+
+ print(f'Video Stream: Path: http://{IP}:5000')
+
+def main():
+ utility.printUI()
+ start()
+ startVideoStream()
+
+ temp_port = PORT+1
+ while True:
+ conn, addr = server.accept()
+ while True:
+ temp_name = conn.recv(SIZE).decode(FORMATmsg)
+ print(f"[CLIENT] Username: {temp_name}")
+ if temp_name in u_name:
+ print("[SERVER] Username not accepted")
+ conn.send("NOTACCEPTED!".encode(FORMATmsg))
+ else:
+ print("[SERVER] Username accepted")
+ conn.send(temp_name.encode(FORMATmsg))
+ break
+
+ temp_pin = str(random.randint(1000, 9999))
+ print(f"[AUTHENTICATING] Current Pin: {temp_pin}")
+ msg_pin = conn.recv(SIZE).decode(FORMATmsg)
+
+ if msg_pin != temp_pin:
+ print("[SERVER] PIN not accepted")
+ conn.send("try again".encode(FORMATmsg))
+ continue
+ else:
+ print("[SERVER] PIN accepted")
+ conn.send("!ACCEPTED".encode(FORMATmsg))
+
+
+ conn.recv(SIZE).decode(FORMATmsg)
+ conn.send(str(temp_port).encode(FORMATmsg))
+
+ print(f"[SERVER] {temp_name} added to network")
+
+
+ clientThread = threading.Thread(target=handle_client, args=(conn, addr, temp_name))
+ clientThread.start()
+
+
+ u_pin.append(temp_pin)
+ u_name.append(temp_name)
+ u_addr.append(addr)
+ u_conn.append(conn)
+ u_port.append(temp_port)
+ temp_port += 1
+
+ # broadcast connection list
+ broadcast('LIST')
+
+ print(f"\n[SERVER][ACTIVE CONNECTIONS] {threading.active_count() - 2}")
+ pass
+
+
+if __name__ == "__main__":
+ main()
+\ No newline at end of file
diff --git a/utility.py b/utility.py
@@ -0,0 +1,28 @@
+import psutil
+from urllib.parse import urlparse
+import os
+
+def getpath():
+ '''get path of current directory'''
+ return os.path.dirname(os.path.abspath(__file__))
+
+def printUI():
+ print('\nThis is telnet implementation.\n'
+ 'You can execute commands remotely.\n')
+ print("\n")
+
+# get a list of all commands available on the system
+def getCommands():
+ '''get a list of all commands available on the system'''
+ return os.popen("help").read().split("\n")
+
+'''server functions'''
+# returns ip address assigned by router
+def get_ip_address():
+ addrs = psutil.net_if_addrs()
+ if "Wi-Fi" in addrs:
+ wifi_info = addrs["Wi-Fi"]
+ for info in wifi_info:
+ if info.family == 2: # 2 is the address family for IPv4
+ return info.address
+ return None