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

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

Related

How to add attachments from Flask to win32com?

Hi I am having trouble attaching flask uploads to Outlook,
I need to attach uploads from flask to outlook.
Thanks
''' f = rq.files['filesattach']
msg.HTMLBody = str("<br> <br>Hi, the follow data are attached to this email <br>").title() + "\n \n" + "<br> Date Request Sent to Permit Coordinator: " + dateReq + "\n" + "<br>WO #: "+ wo+ " \n" + "<br>Date Needed: " + dateNeed + "\n" +"<br>SR: "+ sr + "\n" + "<br>TCF: " +tcf + "\n" + "<br>Munplicity: "+ mun + "\n" + "<br>Political Sub: " + polSub + "\n" + '<br>Address: '+ address + "\n" + '<br>Cross Street: ' + cross + "\n" + '<br>Description: '+ desc + "\n" + "<br>Permit Type: " + permitType
msg.Subject = "WO " + wo +" "+ permitType+" "+"Permit Form"
msg.Display()
shell.AppActivate("Outlook")
shell.SendKeys("%s", 0)
saved = f.save(secure_filename(f.filename))
return "Message sent"
else:
return render_template(permitForm)'''
uploaded_files = rq.files.getlist("filesattach")
for i in uploaded_files:
file = os.path.realpath(str(i.filename))
msg.attachments.Add(file)

using a variable from a json.load in another function

I am using an API for receiving TTN data from a device. i have created a function "def on_message(mqttc, obj, msg):", using a json.loads(msg.payload.decode('utf-8')) to receive mqtt data.
I want to pick the variable "node_data" and use in def devdata(). but it seems that i do not get anything but None.
import paho.mqtt.client as mqtt
import json
import pybase64
import binascii
APPEUI = "0018B24441524632"
APPID = "adeunis_fieldtester"
PSW = "ttn-account-v2.vuQczD1bmPoghhaKjlIHR-iHovHIbYMpfWSKosPAGaU"
# Call back functions
# gives connection message
def on_connect(mqttc, mosq, obj, rc):
print("Connected with result code:" + str(rc))
# subscribe for all devices of user
mqttc.subscribe('+/devices/+/up')
# gives message from device
def on_message(mqttc, obj, msg):
try:
x = json.loads(msg.payload.decode('utf-8'))
# metadata
app = x["app_id"]
device = x["dev_id"]
deveui = x["hardware_serial"]
port = x["port"]
confirmed = x["confirmed"]
counter = x["counter"]
payload_fields = x["payload_raw"]
datetime = x["metadata"]["time"]
gateways = x["metadata"]["gateways"]
frequency = x["metadata"]["frequency"]
modulation = x["metadata"]["modulation"]
data_rate = x["metadata"]["data_rate"]
air_time = x["metadata"]["airtime"]
coding_rate = x["metadata"]["coding_rate"]
for gw in gateways:
gateway_id = gw["gtw_id"]
timestamp = gw["timestamp"]
time = gw["time"]
channel = gw["channel"]
gwrssi = gw["rssi"]
gwsnr = gw["snr"]
# decoding the payload_field
payload_r = (pybase64.b64decode(payload_fields + "="))
# decoding the Payload_r to Byte-Ascii string
payload_h = binascii.hexlify(payload_r)
# Byte to tekst
node_data = (payload_h.decode("utf-8)")) #this is the variable i would like to use in devdata()
# Printing data, + str(payload_fields) + ", "
print(str(app) + ", " + str(device) + ", " + str(deveui) + ", " + str(port) + ", " + str(counter) + ", "
+ str(node_data) + ", " + str(modulation) + ", " + str(datetime) + ", " + str(frequency) + ", "
+ str(confirmed) + ", " + str(data_rate) + ", " + str(air_time) + ", " + str(coding_rate) + ", "
+ str(gateway_id) + ", " + str(timestamp) + ", " + str(time) + "," + str(channel) + ", "
+ str(gwrssi) + ", " + str(gwsnr))
return node_data #return data for use in devdata()
except Exception as e:
print(e)
pass
def devdata():
node_data = on_message() # trying to use this as the Variable
temperatur = int(node_data[2:4], 16)
print("temperatur =", temperatur)
`

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

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";

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"

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