Variable is reported to be not defined - python

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

Related

Socket recv() bug in python3.7

Client:
#The program should send two strings and the server should return the interclassed string back
import socket
import time
import sys
HEADERSIZE=10
firstString = input("First string: ")
secondString = input("Second string: ")
host = "127.0.0.1"
port = 8888
firstString = f'{len(firstString):<{HEADERSIZE}}'+firstString
secondString = f'{len(secondString):<{HEADERSIZE}}'+secondString
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(bytes(firstString, 'utf-8'))
s.send(bytes(secondString, 'utf-8'))
fullMsg=''
while 1:
msg = s.recv(8)
if len(msg)<=0:
break
fullMsg += msg.decode('utf-8')
print(fullMsg)
s.close()
Server:
#trebuie trimisa si dimensiunea
import socket
def interclass(firstString , secondString):
i =0
j =0
interString=''
while i < len(firstString) and j < len(secondString):
if firstString[i] < secondString[j]:
interString+=firstString[i]
i=i+1
else:
interString+=secondString[j]
j=j+1
while i < len(firstString):
interString += firstString[i]
i=i+1
while j < len(secondString):
interString+=secondString[j]
j=j+1
return interString
host = "127.0.0.1"
port = 8888;
HEADERSIZE=10
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
while True:
conn, addr = s.accept()
messages=[]
newMsg = True
fullMsg = ''
msgLength = -1
while True:
msg = conn.recv(16)
if len(msg)<=0:
break
msg = msg.decode('utf-8')
fullMsg += msg
if len(fullMsg)>=HEADERSIZE and newMsg == True:
newMsg = False
msgLength = int(fullMsg[:HEADERSIZE-1])
fullMsg = fullMsg[HEADERSIZE:HEADERSIZE+1+msgLength]
if not newMsg and len(fullMsg)>=msgLength:
messages.append(fullMsg[:msgLength])
fullMsg = fullMsg[msgLength:]
newMsg = True
interString = interclass(messages[0], messages[1])
conn.sendall(bytes(interString,'utf-8'))
conn.close()
The application works until I try the part where I try to send data from the server. It all blocks at the recv() command in the client. I searched all the internet for a solution and I tried making it a non-blocked socket and deal with exception... Still not working. I would appreciate some help. Thanks!!

can you solve the problem? Python Sockets

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

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

Chat / Server client Python

I am currently doing a project for university, I have to create a multiple chat client and server in python 3.4.
For some reason it will connect to one client but when a second client tries to connect it does nothing. However when the first client disconnects the other client will connect to it. Does anyone have any ideas, I have been trying to work this out for over 3 hours.
The Client Server
import socket
def Main():
print("Send 'q' to exit\n")
address = str(input("ip:port -> "))
nick = input("nick: ")
try:
if address.index(":") != 0:
host = address[:address.index(":")]
port = int(address[address.index(":")+1:])
except ValueError:
host = address
port = 5000
s = socket.socket()
s.connect((host, port))
message = input("-> ")
while message != "q":
send_message = message + "pPp" + nick
send_message2 = send_message.encode("UTF-8")
s.send(bytes(send_message2))
data = s.recv(1024)
data_decoded = data.decode("UTF-8")
data2 = data_decoded
print(data_decoded)
messageServer = str(data_decoded[:data_decoded.index("pPp")])
nickServer = str(data_decoded[data_decoded.index("pPp")+3:])
if not data_decoded == data2:
print(nickServer + ": " + messageServer)
message = input("-> ")
s.close()
if __name__ == "__main__":
Main()
The server side:
import socket
import time
import os
from threading import Thread
folderPath = "Chat Logs"
filePath = folderPath + "/" + str(time.strftime("%H-%M-%S_%d-%m-%Y")) + ".txt"
def clientHandler(c):
while True:
data = c.recv(1024)
if not data:
break
data_decoded = data.decode("UTF-8")
message = str(data_decoded[:data_decoded.index("pPp")])
nick = str(data_decoded[data_decoded.index("pPp")+3:])
print(nick + "$" + message)
saveChat(nick, message)
print(" Sending: " + data_decoded)
c.send(bytes(data_decoded.encode("UTF-8")))
c.close()
def saveChat(nick, message):
if not os.path.exists(folderPath):
os.makedirs(folderPath)
if not os.path.exists(filePath):
f = open(filePath, "a")
f.close()
f = open(filePath, "a")
f.write(nick + ": " + message + "\n")
f.close()
def Main():
host = str(socket.gethostbyname(socket.gethostname()))
port = 5000
print(host + ":" + str(port) + "\n")
Clients = int(input("Clients: "))
s = socket.socket()
s.bind((host, port))
s.listen(Clients)
while True:
c, addr = s.accept()
print("Connection from: " + str(addr))
Thread(target=clientHandler(c)).start()
s.close()
if __name__ == "__main__":
Main()
You are initializing the Thread object correctly. Try one of these:
Thread(target=clientHandler, args=(c,)).start()
or
Thread(target=lambda c=c: clientHandler(c)).start()
Thread takes a callable as the target argument. Instead of passing in a callable, your code invokes the clientHandler, and passes its return value to Thread.__init__.
the changed code for server.py works for me.
what if we accept the connections in the thread handler and pass the socket object as an argument when we call the handler.
def clientHandler(s):
while True:
c, addr = s.accept()
print("Connection from: " + str(addr))
data = c.recv(1024)
if not data:
break
data_decoded = data.decode("UTF-8")
message = str(data_decoded[:data_decoded.index("pPp")])
nick = str(data_decoded[data_decoded.index("pPp")+3:])
print(nick + "$" + message)
#saveChat(nick, message)
print(" Sending: " + data_decoded)
c.send(bytes(data_decoded.encode("UTF-8")))
c.close()
In main function, I changed the following lines.
while True:
#c, addr = s.accept()
#print("Connection from: " + str(addr))
Thread(target=clientHandler(s)).start()
Here is the connection result:
>>>
10.212.245.81:5000
Clients: 3
Connection from: ('10.212.245.81', 60945)
c1$hi
Sending: hipPpc1
Connection from: ('10.212.245.81', 60976)
c2$hi
Sending: hipPpc2
Connection from: ('10.212.245.81', 61096)
c3$hi
Sending: hipPpc3
P.S I didn't try to check the code by exceeding the number of client connect requests.

How can I have multiple clients on a TCP Python Chat Server?

Any help on how I can get this to accept more than one client, and why it isn't at the moment? Thanks!
Also, is there anything I'm doing wrong with this code? I've been following mostly Python 2 tutorials because I can't find any for Python 3.4
Here is my Server code:
import socket
import time
import os
from threading import Thread
folderPath = "Chat Logs"
filePath = folderPath + "/" + str(time.strftime("%H-%M-%S_%d-%m-%Y")) + ".txt"
def clientHandler(c):
while True:
data = c.recv(1024)
if not data:
break
data = data.decode("UTF-8")
message = str(data[:data.index("§")])
nick = str(data[data.index("§")+1:])
print(nick + ": " + message)
saveChat(nick, message)
print(" Sending: " + data)
c.send(bytes(data, "UTF-8"))
c.close()
def saveChat(nick, message):
if not os.path.exists(folderPath):
os.makedirs(folderPath)
if not os.path.exists(filePath):
f = open(filePath, "a")
f.close()
f = open(filePath, "a")
f.write(nick + ": " + message + "\n")
f.close()
def Main():
host = str(socket.gethostbyname(socket.gethostname()))
port = 5000
print(host + ":" + str(port) + "\n")
Clients = int(input("Clients: "))
s = socket.socket()
s.bind((host, port))
s.listen(Clients)
for i in range(Clients):
c, addr = s.accept()
print("Connection from: " + str(addr))
Thread(target=clientHandler(c)).start()
s.close()
if __name__ == "__main__":
Main()
And here is my Client code:
import socket
def Main():
print("Send 'q' to exit\n")
address = str(input("ip:port -> "))
nick = input("nick: ")
try:
if address.index(":") != 0:
host = address[:address.index(":")]
port = int(address[address.index(":")+1:])
except ValueError:
host = address
port = 5000
s = socket.socket()
s.connect((host, port))
message = input("-> ")
while message != "q":
s.send(bytes(message + "ยง" + nick, "UTF-8"))
data = s.recv(1024)
data = data.decode("UTF-8")
data2 = data
messageServer = str(data[:data.index("ยง")])
nickServer = str(data[data.index("ยง")+1:])
if not data == data2:
print(nickServer + ": " + messageServer)
message = input("-> ")
s.close()
if __name__ == "__main__":
Main()
First of all, I found these tutorials very helpful: BinaryTides
Here is an example of a simple tcp server that accepts multiple clients. All this one does receive data from the client and return "OK .. " + the_data. However, you could easily modify it to have a function that broadcasts the data(chat msg) to all clients connected. This example uses threading. You should google for the select module. With regards to your threads, are you sure you are a) using the right module/method for the job and b) that you are calling it in the right way?
import socket
import sys
from thread import start_new_thread
HOST = '' # all availabe interfaces
PORT = 9999 # arbitrary non privileged port
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print("Could not create socket. Error Code: ", str(msg[0]), "Error: ", msg[1])
sys.exit(0)
print("[-] Socket Created")
# bind socket
try:
s.bind((HOST, PORT))
print("[-] Socket Bound to port " + str(PORT))
except socket.error, msg:
print("Bind Failed. Error Code: {} Error: {}".format(str(msg[0]), msg[1]))
sys.exit()
s.listen(10)
print("Listening...")
# The code below is what you're looking for ############
def client_thread(conn):
conn.send("Welcome to the Server. Type messages and press enter to send.\n")
while True:
data = conn.recv(1024)
if not data:
break
reply = "OK . . " + data
conn.sendall(reply)
conn.close()
while True:
# blocking call, waits to accept a connection
conn, addr = s.accept()
print("[-] Connected to " + addr[0] + ":" + str(addr[1]))
start_new_thread(client_thread, (conn,))
s.close()

Categories