can you solve the problem? Python Sockets - python

i have 2 python programs which speak with sockets.
The First one i have called "King.py":
import os
import time
import sys
import socket
i = 0
s = socket.socket()
host = socket.gethostname()
print("hostname: " + host)
port = 8080
s.bind((host,port))
print("")
print("Auf Verbindungen warten.")
print("")
s.listen(1)
conn, addr = s.accept()
print("")
print(addr, " - Ist dem Server beigetreten.")
print("")
while i < 1:
command = input(str("Command : "))
conn.send(command.encode())
print("Der Befehl wurde gesendet, warte auf Akzeptierung")
print("")
result = s.recv(1024)
result = result.decode()
if result:
print(result)
and the second one i have called "noobie.py":
import time
import sys
import socket
import os
import subprocess
i = 0
s = socket.socket()
host = "realMxrlxn-PC"
port = 8080
s.connect((host, port))
print("")
print(" Connected to server ")
while i < 1:
command = s.recv(1024)
command = command.decode()
if not command == "dir":
os.system(command)
else:
result = subprocess.check_output(command, shell=True)
conn.send(result.encode())
So now i want you to ask why im getting the "WinError 10057" in king.py, because it says i have no socket? (result = s.recv(1024))

Related

Variable is reported to be not defined

this is the strangest error i ever had (i write this because most of my post is code!!
can you help me?
i have a new error :/
line 43: conn.send = command.encode()
NameError: name 'conn' is not defined here's the code:
import os
import socket
import sys
from _thread import *
mm = 0
owncmds = ["dir", "erase"]
def clientthread(conn):
buffer = ""
data = conn.recv(8192)
buffer += data
print(buffer)
# conn.sendall(reply)
def main():
try:
host = socket.gethostname()
port = 6666
tot_socket = input("Wie viele Clients sind zugelassen?: ")
list_sock = []
for i in range(int(tot_socket)):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port + i))
s.listen(2)
list_sock.append(s)
print("[*] Server listening on %s %d" % (host, (port + i)))
for j in range(len(list_sock)):
conn, addr = list_sock[j].accept()
print('[*] Connected with ' + addr[0] + ':' + str(addr[1]))
start_new_thread(clientthread, (conn,))
finally:
s.close()
main()
while mm < 1:
command = input(str("Command: "))
if command not in owncmds:
conn.send(command.encode())
else:
if command == "dir":
result = conn.recv(1024)
result = result.decode()
print(result)
if command == "erase":
command = command + "/F /Q "
FileErase = input(str("Filename: "))
command = command + FileErase
conn.send(command.encode())
print("Der Befehl wurde gesendet, warte auf Akzeptierung")
print("")

How would I take a screenshot on a remote Windows machine and send it back?

I'm trying to take a screenshot on a remote Windows machine. For example, when you input the command "screenshot" on the server, it takes a screenshot on the client machine, saves it to a directory, and sends it back to the server. I already figured out the first part, but can't figure out how to send the saved file back.
Server:
import socket
import sys
import subprocess
host = '192.168.1.25'
port = 4444
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
sendCommands(conn)
def sendCommands(conn):
cmd = input('console > ')
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
clientResponse = str(conn.recv(1024), "utf-8")
print('\n' + clientResponse, end="")
Client:
import os
import sys
import subprocess
import socket
import autopy
def socketCreate():
global host
global port
global s
host = '192.168.1.25'
port = 4444
s = socket.socket()
def socketConnect():
global host
global port
global s
s.connect((host, port))
def recieveCommands():
global s
while True:
data = s.recv(1024)
if data[:].decode("utf-8") == 'screenshot':
path = r'C:\Windows\Temp\LocalCustom\ssh\new\custom'
screenshot = r'\screenshot.png'
if not os.path.exists(path):
os.makedirs(path)
try:
bitmap = autopy.bitmap.capture_screen()
bitmap.save(path + screenshot)
tookScreenShot = ('\n' + '[*] Succesfuly took screenshot at ' + path + '\n')
s.send(str.encode(tookScreenShot))
except:
screenshotFailed = ('\n' + "[!] Couldn't take screenshot " + '\n')
str(screenshotFailed)
s.send(str.encode(screenshotFailed))
else:
if len(data) > 0:
cmd = subprocess.Popen(data[:].decode('utf-8'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
output_bytes = cmd.stdout.read() + cmd.stderr.read()
output_str = str(output_bytes, "utf-8")
s.send(str.encode("utf-8"))
s.close()
def main():
socketCreate()
socketConnect()
recieveCommands()
main()
You should send the as following from the client
f = open('tosend.jpg','rb')
print 'Sending the file'
file = f.read(1024)
while (file):
print 'Sending...'
s.send(file)
file = f.read(1024)
f.close()
print "Done Sending"
s.shutdown(socket.SHUT_WR)
print s.recv(1024)
s.close()
on server
while True:
file = open('C:/received.jpg','w')
l = s.recv(1024)
while l:
print "Receiving..."
file.write(l)
l = s.recv(1024)
file.close()
print "Done Receiving"
s.close()

My socket program doesn't print the output

Just getting started with socket programming, I have created the below code and expecting to print some byte data, but it isn't doing that.
import socket
def create_socket():
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohl(3))
while True:
rdata, address = s.recvfrom(65535)
print(rdata)
It just sits and does nothing.
any directions would be appreciated.
You should have a server where the requests can be sent by the client to print the data
Below is a sample program where you can send message from client and receive the output that was modified by the server
SERVER.PY
from socket import *
serverPort = 12048
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', serverPort))
print 'The server is ready to receive'
while 1:
message,clientAddress = serverSocket.recvfrom(2048)
modifiedMessage = message.upper()
serverSocket.sendto(modifiedMessage, clientAddress)
CLIENT.PY
from socket import *
serverName = '127.0.0.1'
serverPort = 12048
clientSocket = socket(AF_INET,SOCK_DGRAM)
message = raw_input('Input lowercase sentence:')
clientSocket.sendto(message,(serverName, serverPort))
modifiedMessage, serverAddress =clientSocket.recvfrom(2048)
print modifiedMessage
OUTPUT
SIVABALANs-MBP:Desktop siva$ python client.py
Input lowercase sentence:siva
SIVA
SIVABALANs-MBP:Desktop siva$
EDIT:
Maybe you can try this code
import socket
import struct
import binascii
rawSocket = socket.socket(socket.AF_PACKET,
socket.SOCK_RAW,
socket.htons(0x0003))
while True:
packet = rawSocket.recvfrom(2048)
ethhdr = packet[0][0:14]
eth = struct.unpack("!6s6s2s", ethhdr)
arphdr = packet[0][14:42]
arp = struct.unpack("2s2s1s1s2s6s4s6s4s", arphdr)
# skip non-ARP packets
ethtype = eth[2]
if ethtype != '\x08\x06': continue
print "---------------- ETHERNET_FRAME ----------------"
print "Dest MAC: ", binascii.hexlify(eth[0])
print "Source MAC: ", binascii.hexlify(eth[1])
print "Type: ", binascii.hexlify(ethtype)
print "----------------- ARP_HEADER -------------------"
print "Hardware type: ", binascii.hexlify(arp[0])
print "Protocol type: ", binascii.hexlify(arp[1])
print "Hardware size: ", binascii.hexlify(arp[2])
print "Protocol size: ", binascii.hexlify(arp[3])
print "Opcode: ", binascii.hexlify(arp[4])
print "Source MAC: ", binascii.hexlify(arp[5])
print "Source IP: ", socket.inet_ntoa(arp[6])
print "Dest MAC: ", binascii.hexlify(arp[7])
print "Dest IP: ", socket.inet_ntoa(arp[8])
print "------------------------------------------------\n"
I could not test the code in my system as AF_PACKET does not work in mac. Try and let me know if in case it works.

Real time output whilst running Python

I'm making a basic chatroom and I want the received messages to show up when I'm also typing a message. I've looked it up, but from what I can tell it only works with a GUI, and I would prefer not to write a GUI.
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
str_return = ("")
str_send = ("blep")
old = ("blep")
port = input("Enter Port ")
try:
s.connect(("localhost", int(port)))
print("Connecting")
while True:
str_send = input("Enter message: ")
if str_send == ("exit"):
break
s.send(bytes(str_send, 'utf-8'))
str_recv = s.recv(1024)
print(str_recv.decode('utf-8'))
s.close()
except:
print("setting up server")
s.bind(('localhost', int(port)))
s.listen(5)
connect, addr = s.accept()
connect.sendto(bytes(str_return, 'utf-8'), addr)
print("Connection Address:" + str(addr))
while True:
str_send = input("Enter message: ")
if str_send == ("exit"):
break
connect.sendto(bytes(str_send, 'utf-8'), addr)
str_recv, temp = connect.recvfrom(1024)
print(str_recv.decode('utf-8'))
print("bye")
How can I make this work?

Python Networking responding wtih 'b'

I've just started python networking, and after looking at a few internet tutorials, I gave it a go... only problem is, whenever I get a response from the sever, it prints as in:
Recieved from: (Host & Port)b'Hey' - where I haven't put the b anywhere.
Here is the server code:
import socket
import tkinter
import time
import sys
def Main():
top = tkinter.Tk()
top.configure(background='black')
host = '10.0.0.2'
port = 5000
s = socket.socket()
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
while True:
con = tkinter.Label(top, text="Connection from: " + str(addr), bg='red', fg='white').pack()
data = c.recv(1024)
if not data:
break
conn = tkinter.Label(top, text="Recieved from: " + str(addr) + str(data), bg='black', fg='white').pack()
top.mainloop()
c.close()
Main()
And my client:
import socket
def Main():
host = '10.0.0.2'
port = 5000
s = socket.socket()
s.connect((host, port))
message = input("> ")
while message != 'quit':
s.send(message.encode('ascii'))
message = input(">")
s.close()
Main()
Thanks for any input - I'm not really good at this yet! (My hosts aren't my computer so that's not the issue)
When you call socket.recv() in Python 3 it returns a bytes object, not a normal string. You can convert it to a normal string as follows:
data.decode('utf-8')

Categories