Python2.7 socket error 37 "Operation already in progress" - python

I'm making a script that reads a file full of proxy servers and checks if they are up or down.
import socket
proxyFile = open("proxies.txt","r");
lines = proxyFile.readlines();
class Colors:
none = "\033[0m";
red = "\033[31m";
green = "\033[32m";
yellow = "\033[33m";
blue = "\033[34m";
purple = "\033[35m";
cyan = "\033[36m";
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM);
sock.settimeout(3);
for line in lines:
line = line.replace(":"," : ");
reader = line.split();
ip = reader[reader.index(":") - 1];
port = int(reader[reader.index(":") + 1]);
try:
sock.connect((ip,port));
print Colors.cyan + ip + ":" + str(port) + Colors.none + " is " + Colors.green + "UP";
sock.close();
except socket.timeout:
print Colors.cyan + ip + Colors.yellow + ":" + Colors.cyan + str(port) + Colors.none + " is " + Colors.red + "DOWN";
It seems that the file reads fine and the socket creates, but it only connects to one server then it gives the error.
Proxy File:
1.0.134.56:8080
1.165.192.248:3128
1.172.185.143:53281
1.179.156.233:8080
1.179.164.213:8080
1.179.185.253:8080
1.192.242.191:3128
1.20.169.166:8080
1.20.179.68:8080
1.20.99.163:8080

You can't re-connect a socket. Once it's connected, it's connected. Even if you call close:
all future operations on the socket object will fail.
The right answer is to create a new socket each time through the loop, whether with create_connection or with socket and connect. For example, change your try block to this:
try:
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM);
sock.settimeout(3);
sock.connect((ip,port));
print Colors.cyan + ip + ":" + str(port) + Colors.none + " is " + Colors.green + "UP";
sock.close();
except socket.timeout:
print Colors.cyan + ip + Colors.yellow + ":" + Colors.cyan + str(port) + Colors.none + " is " + Colors.red + "DOWN";

Related

I can't see what is triggering the invalid Syntax error

I am currently trying to replicate a packet sniffer in python that can parse udp, tcp, and ICPM packets.
As it is now no other compiler errors show except an invalid syntax error.
#packet sniffer for linux in python
import socket, sys
from struct import*
#A function that converts a string of 6 characters of ethernet address into dash seperated hex string
def ethernet_address (string):
new_String = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(string(0)), ord(string(1)), ord(string(2)), ord(string(3)), ord(string(4)), ord(string(5)))
return new_String
#Section that creates the socket
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.ntohs(0x0003))
except socket.error as msg:
print ("Socket could not be created, Error : ")
print (msg)
sys.exit()
#recieve a packet
while True:
packet = sock.recvfrom(60000)
#packet string from tuple
packet = packet[0]
#parse ethernet header
ether_length = 14
ether_Header = packet[:ether_length]
ether = unpack('!6s6sh', ether_Header)
ether_protocol = socket.ntohs(ether[2])
print ("Destination MAC: " + ethernet_address(packet[0:6]) + "Source MAC: " + ethernet_address(packet[6:12]) + " Protocol: " + str(ether_protocol))
#This section handles parsing IP packets
if ether_protocol == 8:
#Parse the IP header
#take the first 20 character from the header
ip_header = packet[ether_length:20 + ether_length]
#now unpack
iph = unpack('!BBHHHBBH4s4s', ip_header)
version_ihl = iph[0]
version = version_ihl >> 4
ihl = version_ihl & 0xf
iph_length = ihl * 4
ttl = iph[5]
protocol = iph[6]
source_address = socket.inet_ntoa( iph[8] )
destination_address = socket.inet_ntoa( iph[9] )
print("Version: " + str(version) + " IP header length: " + str(ihl) + " TTL: " + str(ttl) + " Protocol: " + str(protocol + " Source Address: " + str(source_address) + " Destination Address: " + str(destination_address) )
#This section handles parsing TCP packets
if protocol == 6 : #This is the line with the error******************************************
num = iph_length + ether_length
tcp_header = packet[ num:num+20]
#unpack
tcph = unpack('!HHLLBBHHH', tcp_header)
source_port = tcph[0]
destination_port = tcph[1]
sequence = tcph[2]
acknowledgment = tcph[3]
doff_reserve = tcph[4]
tcph_length = doff_reserve >> 4
print("Source Port: " + str(source_port) + " Destination Port: " + destination_port + " Sequence: " + sequence + " Acknowledgment: " + str(acknowledgment) + " TCP header length: " + str(tcph_length))
h_size = ether_length + iph_length + tcph_length * 4
data_size = len(packet) - h_size
#get data
data = packet[h_size:]
print ("Data: "+ data)
#This section Handles parsing ICMP packets
elif protocol == 1:
u = iph_length + ether_length
icmph_length = 4
icmp_header = packet[u:u+20]
#unpack
icmph = unpack('!BBH', icmp_header)
icmp_type = icmph[0]
code = icmph[1]
checksum = icmph[2]
print("Type: " + str(icmp_type) + " Code: " + str(code) + " Checksum: " + str(checksum))
h_size = ether_length + iph_length + icmph_length
data_size = len(packet) - h_size
#retrive data
data = packet[h_size]
print("Data: " + data)
#This section handles parsing UDP
elif protocol == 17:
u = iph_length +ether_length
udph_length = 8
udp_header = packet[u:u+8]
#now unpack them
udph = unpack('!HHHH', udp_header)
src_port = udph[0]
dest_port = udph[1]
length = udph[2]
checksum = udph[3]
print("Source Port: " + str(src_port) + " Destination Port: " + str(dest_port) + " Length: " + str(length) + " Checksum: " + str(checksum) )
h_size = ether_length + iph_length + udph_length
data_size = len(packet) - h_size
#get data
data = packet[h_size]
print("Data: " + data)
else:
print("Protocol is something other than UDP, ICMP, or TCP")
print
The error is caused by the line:
if protocol == 6 :
Visual Studio says that this is a syntax error, but I'm of how because it is written just like every other if statement and they don't have a syntax error warning. What is the error if there is one?
I believe you are missing a bracket. print("Version: " + str(version) + " IP header length: " + str(ihl) + " TTL: " + str(ttl) + " Protocol: " + str(protocol + " Source Address: " + str(source_address) + " Destination Address: " + str(destination_address) )) should work.
Note: I added a bracket at the end but that might not be where it should be added for your code to function as intended despite removing the error. It seems print("Version: " + str(version) + " IP header length: " + str(ihl) + " TTL: " + str(ttl) + " Protocol: " + str(protocol) + " Source Address: " + str(source_address) + " Destination Address: " + str(destination_address) ) is likely what you want.
The error is found in the line above:
print("Version: " + str(version) + " IP header length: " + str(ihl) + " TTL: " + str(ttl) + " Protocol: " + str(protocol + " Source Address: " + str(source_address) + " Destination Address: " + str(destination_address) )
Specifically, the error comes from ... str(protocol + ..., which should be ... str(protocol) + ....
You have an unmatched parenthesis on the previous line:
print("Version: " +
str(version) +
" IP header length: " +
str(ihl) +
" TTL: " +
str(ttl) +
" Protocol: " +
str(protocol +
" Source Address: " +
str(source_address) +
" Destination Address: " +
str(destination_address)
)
You probably want something like this:
print("Version: " +
str(version) +
" IP header length: " +
str(ihl) +
" TTL: " +
str(ttl) +
" Protocol: " +
str(protocol) +
" Source Address: " +
str(source_address) +
" Destination Address: " +
str(destination_address)
)
Also, consider using " ".join(iterable) to join strS with spaces. Concatenation is inefficient (not an issue here) and difficult to read (definitely an issue here).

Detecting Change In Ip addresses status

I have this code that displays the ip addresses that are on my network as well as the mac address and the status. I have it running in this loop so it always updates. How could i have it so when it updates and the ip address that was offline goes online it will instead say New instead of online for that one cycle and then show online at the next cycle if its still active.
import os
from getmac import get_mac_address
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
minr = int(input("Starting Ip: "))
maxr = int(input("Ending Ip: "))
while True:
for num in range(minr, maxr + 1): #plus one is to include the last digit entered
ip = "192.168.2." + str(num)
from getmac import getmac
exit_code = os.system("ping -n 1 -w 1 " + ip + " > nul") # Windows
#exit_code = os.system("ping -c 1 -W 1 " + ip + " > /dev/null") # Linux
getmac.PORT = 44444 # Default: 55555
if exit_code == 0:
print(ip, bcolors.OKGREEN + "ONLINE " + bcolors.ENDC + bcolors.OKBLUE + get_mac_address(ip=ip, network_request=True) + bcolors.ENDC)
elif (ip == '192.168.2.' + str(maxr + 1) and exit_code == 0):
print('192.168.2.' + str(maxr), bcolors.OKGREEN + "ONLINE " + bcolors.ENDC + bcolors.OKBLUE + get_mac_address(ip=ip, network_request=True) + bcolors.ENDC)
print("")
print(bcolors.HEADER + "Beginning" + bcolors.ENDC)
print("")
elif (ip == '192.168.2.' + str(maxr)):
print('192.168.2.' + str(maxr), bcolors.FAIL + "OFFLINE" + bcolors.ENDC)
print("")
print(bcolors.HEADER + "Refreshed" + bcolors.ENDC)
print("")
else:
print(ip, bcolors.FAIL + "OFFLINE" + bcolors.ENDC)
What should happen is if the ip goes online it will show new and at the next cycle show online.

TypeError: Can't convert 'bytes' object to str implicitly despite adding .encode() to string

I am trying to write some code that connects to an IRC channel and allows the user to chat through the channel. I have been getting an error in my script that connects to the server:
TypeError: Can't convert 'bytes' object to str implicitly
The error is apparently in line 18, which is the code that sends the nickname to the server:
irc.send("USER " + nick.encode() + " " + nick.encode() + " " + nick.encode() + " : Test\n")
Source Code:
import sys
import socket
server = "chat.freenode.net"
channel = "#randomchannel123456789"
port = 7070
print("IRC Connecter")
print("-----------------------------")
nick = input("Input Nickname: ")
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("connecting to " + server)
irc.connect((server, port))
print("connected")
irc.send("USER " + nick.encode() + " " + nick.encode() + " " + nick.encode() + " : Test\n")
print("sent user")
irc.send ("NICK " + nick + "\n")
print("sent nick")
while 1:
text = irc.recv(2040)
print(text)
if text.find("PING") != -1:
irc.send("PONG " + text.split() [1] + "\r\n")
I'm pretty new to socket programming, so any help would be much appreciated.
The problem is that in that line:
"USER " + nick.encode() + " " + nick.encode() + " " + nick.encode() + " : Test\n"
The "USER ", " " and " : Test\n" are str but nick.encode is a bytes object. And the exception is telling you, that you can't add bytes and strs:
>>> b'a' + 'a'
TypeError: can't concat bytes to str
>>> 'a' + b'a'
TypeError: Can't convert 'bytes' object to str implicitly
You could convert the string literals to bytes, for example using the bytes literal (b""):
b"USER " + nick.encode() + b" " + nick.encode() + b" " + nick.encode() + b" : Test\n"

How to end a server socket listen

So what i'm trying to do is to make a multi-threaded server that creates threads for each client that connects to it, and replies back the string sent from the client.
It sort of works, but my server doesn't actually end properly. My KerboardInterrupt catch doesn't seem to work in windows command prompt, only thing that lets me exit the process would be ctrl + pause/break. Can anyone help me think of a way to get the server to end gracefully?
Server Code:
import socket
import threading
import time
import datetime
import sys
def getTime():
ts = time.time()
timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m- %d_%H:%M:%S')
return timeStamp
def ThreadFunction(clientsocket, clientaddr):
global ReceivedData
global SentData
while True:
#Receive data from client
data = clientsocket.recv(bufferSize)
#Get client IP and port
clientIP, clientSocket = clientsocket.getpeername()
#Add to total amount of data transfered
ReceiveDataSize = len(data)
ReceivedData += ReceiveDataSize
#LOg the received data
text_file.write(str(getTime()) + "__ Size of data received (" + clientIP + ":" + str(clientSocket) + ") = " + str(ReceiveDataSize) + '\n')
#Send data
clientsocket.send(data)
SentDataSize = len(data)
SentData += SentDataSize
#Log the sent data
text_file.write(str(getTime()) + "__ Size of data sent (" + clientIP + ":" + str(clientSocket) + ") = " + str(SentDataSize) + '\n')
def Close(counter, ReceivedData, SentData):
print ("Shutting down Server...")
serversocket.close()
text_file.write("\n\nTotal # of connections: " + str(counter))
text_file.write("\nTotal data received: " + str(ReceivedData))
text_file.write("\nTotal data sent: " + str(SentData))
text_file.close()
sys.exit()
if __name__ == '__main__':
serverIP = raw_input('Enter your server IP \n')
port = int(raw_input('What port would you like to use?\n'))
# Maintain how many connections
connections = []
counter = 0
# Maintain amount of data sent to and from server
ReceivedData = 0
SentData = 0
bufferSize = 1024
# Create and initialize the text file with the date in the filename in the logfiles directory
text_file = open("MultiThreadedServerLog.txt", "w")
address = (serverIP, port)
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind server to port
serversocket.bind(address)
# The listen backlog queue size
serversocket.listen(50)
print ("Server is listening for connections\n")
try:
while 1:
# Accept client connections, increment number of connections
clientsocket, clientaddr = serversocket.accept()
counter += 1
# Log client information
print (str(clientaddr) + " : " + " Just Connected. \n Currently connected clients: " + str(counter) + "\n")
text_file.write(str(getTime()) + " - " + str(clientaddr) + " : " + " Just Connected. \n Currently connected clients: " + str(counter) + "\n")
clientThread = threading.Thread(target=ThreadFunction, args=(clientsocket, clientaddr))
clientThread.start()
except KeyboardInterrupt:
print ("Keyboard interrupt occurred.")
Close(counter, ReceivedData, SentData)
Client Code:
from socket import *
import threading
import time
import random
import sys
import datetime
serverIP = ""
port = 8005
message = ""
msgMultiple = 1
def getTime():
ts = time.time()
timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d_%H:%M:%S')
return timeStamp
def run(clientNumber):
buffer = 1024
global totalTime
s = socket(AF_INET, SOCK_STREAM)
s.connect((serverIP, port))
threadRTT = 0
while 1:
for _ in range(msgMultiple):
cData = message + " From: Client " + str(clientNumber)
# Start timer and send data
start = time.time()
s.send(cData.encode('utf-8'))
print "Sent: " + cData
# Stop timer when data is received
sData = s.recv(buffer)
end = time.time()
# Keep track of RTT and update total time
response_time = end - start
threadRTT += end - start
totalTime += response_time
print "Received: " + cData + '\n'
t = random.randint(0, 9)
time.sleep(t)
# Log information of Client
text_file.write(
"\nClient " + str(clientNumber) + " RTT time taken for " + str(msgMultiple) + " messages was: " + str(
threadRTT) + " seconds.")
threadRTT = 0
break
if __name__ == '__main__':
serverIP = raw_input('Enter the server IP: ')
port = int(input('Enter the port: '))
clients = int(input('Enter number of clients: '))
message = raw_input('Enter a message to send: ')
msgMultiple = int(input('Enter the number of times you would like to send the message: '))
# Initialize Log file
text_file = open("ClientLog.txt", "w")
# Used to maintain list of all running threads
threads = []
totalTime = 0
# Create a seperate thread for each client
for x in range(clients):
thread = threading.Thread(target=run, args=[x])
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
# Calculations for log data
bytes = sys.getsizeof(message)
totalRequests = clients * msgMultiple
totalBytes = totalRequests * bytes
averageRTT = totalTime / totalRequests
# Output data
print("Bytes sent in message was : " + str(bytes))
print("Total Data sent was : " + str(totalBytes) + " Bytes.")
print("Average RTT was : " + str(averageRTT) + " seconds.")
print("Requests was : " + str(totalRequests))
# Write data to log file
text_file.write("\n\n Bytes sent in message was : " + str(bytes))
text_file.write("\nTotal Data sent was : " + str(totalBytes) + " Bytes.")
text_file.write("\nAverage RTT was : " + str(averageRTT) + " seconds.")
text_file.write("\nRequests was : " + str(totalRequests))
Also if anyone else has any general improvements they would add to this code, let me know. I'm still pretty new at python, and still rough at it.
Here is the normal intended input i'm getting from my server.
But when it gets to the last client that connects, it starts to drag on for some reason.
The last picture, the inputs go on for the majority of the text file, for a very long time. Seems like something isn't ending properly.
Solved by adding an if statement that checks for a byte < 0 , if it is, end the socket.

print the result of a scapy function in tkinter

a=lb + "(IP(src='" + SrcIP + "', dst='" + DestIP + "')/TCP(sport=" + SrcPort + ", dport=" + DestPort + ",flags='"+P+""+S+""+A+""+U+""+F+""+R+"'), timeout=" + Timeout + ")"
p=eval(a)
p.show()
tkMessageBox.showinfo(title = "the configuration and results", message = "The configuration is:\nFlags:"+psh+"\n"+syn+"\n"+ack+"\n"+urg+"\n"+fin+"\n"+rst+"\nSource IP:"+SrcIP + "\nDestination IP: " + DestIP + "\nSource Port: " +SrcPort+ "\nDestination port: " + DestPort + "\nTimeout: " +Timeout+"\nSend/Received method: "+lb+"\t")
How can i put the result of p.show() in tkMessageBox.showinfo?
I don't think you can, as the .show() method only uses print statements.

Categories