Inserting new ips into a list - python

I have this program that list ip addresses on my network and if they are online or offline along with the mac address. i want the offline ips to be in a list so that i can check if that ip is not in the list it will it will display NEW.
idk what to do
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: "))
ofip = ["192.168.2.0"]
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
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 exit_code != 0:
print(ip, bcolors.FAIL + "OFFLINE" + bcolors.ENDC)
ip = ofip
elif exit_code != 0 and ip != ofip:
print(ip, bcolors.OKGREEN + "NEW " + bcolors.ENDC + bcolors.OKBLUE + get_mac_address(ip=ip, network_request=True) + bcolors.ENDC)
else:
print(ip, bcolors.FAIL + "OFFLINE" + bcolors.ENDC)
i should see offline ip address that goes online print new

This line will not do what you are intending. You need to make a few changes.
elif exit_code != 0 and ip != ofip:
ofip is a list (at least it is at first) and ip is a string, != will not work here. You should be using the in operator.
elif exit_code != 0 and ip not in ofip:
Second issue is addressing that ip is a string and ofip is a list (when you first assign it, later you set it to a string).
Instead of doing,
ip = ofip
try appending to the list
ofip.append(ip)
Last thing is that is that because of how your if/elif statements flow, the second elif will never run.
If the exit code is not 0 then it will always hit the first elif and will never hit the second one. Switch these. Put your more specific conditionals before your less specific ones.
Tip: you can use a set instead of a list for faster lookups.
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: "))
ofip = ["192.168.2.0"]
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
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 exit_code != 0:
if ip not in ofip:
ofip.append(ip)
print(ip, bcolors.OKGREEN + "NEW " + bcolors.ENDC + bcolors.OKBLUE + get_mac_address(ip=ip, network_request=True) + bcolors.ENDC)
else:
print(ip, bcolors.FAIL + "OFFLINE" + bcolors.ENDC)

MY problem has been solved and here is the code:
import os
from getmac import get_mac_address
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
YELLOW = "\033[29m"
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: "))
ofip = []
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
getmac.PORT = 44444 # Default: 55555
if exit_code == 0:
if ip in ofip:
print(ip, bcolors.HEADER + "NEW " + bcolors.ENDC + bcolors.OKBLUE + get_mac_address(ip=ip, network_request=True) + bcolors.ENDC)
ofip.remove(ip)
print(ip, bcolors.OKGREEN + "ONLINE " + bcolors.ENDC + bcolors.OKBLUE + get_mac_address(ip=ip, network_request=True) + bcolors.ENDC)
elif exit_code != 0:
print(ip, bcolors.FAIL + "OFFLINE" + bcolors.ENDC)
ofip.append(ip)

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

A multi-input PySimpleGUI for a working python script

I'm using a working script built in python 3 that reads an excel file. Using the input, it figures out which VIP (Virtual IP) subnet I should use and which F5 load balancer the VIP should be matched with, and then spits out the cli commands needed to configure on the load balancer as another file. I want to know if it's possible to add a basic GUI to this using the code I have below. Based on that, it will create a file on my desktop with the commands I need to configure taken from the excel file and input given. If the information is blank within excel it will prompt and ask you. An edited example of a simple working script that runs is shown below:
import pandas as pd
import datetime
from netaddr import IPNetwork, IPAddress, IPSet
import os
import glob
import shutil
def createfolder(directory):
try:
if not os.path.exists(directory):
os.makedirs(directory)
except OSError:
print('Error: Creating directory. ' + directory)
global options
global member
global lb_mode
global pool_member1
global pool_member2
global pool_member3
global pool_member4
global cert
global iRule1
global iRule2
global rules
global one_connect
global http_profile
global primary_persist
global fallback_persist
global snat
global rule_member_1
global rule_member_2
global rule_member_3
global irules
global profiles
global loadbalancer
global subnet
global ssl_profile_name
global ssl_config
x = datetime.datetime.now()
change_order = input("What is the change order for this VIP? ")
lbarf_file = str(input("Enter the full path of the LBARF form. ").strip('\"'))
description = "description " + change_order
df = pd.read_excel(lbarf_file)
# Info pulled from the LBARF
service_port_input = str(df.iloc[13, 2])
http_profile_input = df.iloc[33, 2]
primary_persist_input = df.iloc[34, 2]
fallback_persist_input = df.iloc[35, 2]
iRule1_input = df.iloc[42, 2]
iRule2_input = df.iloc[43, 2]
snat_input = df.iloc[47, 2]
one_connect_input = df.iloc[48, 2]
fqdn = str(df.iloc[12, 2]).lower()
member1 = str(df.iloc[19, 2])
member2 = str(df.iloc[20, 2])
member3 = str(df.iloc[21, 2])
member4 = str(df.iloc[22, 2])
pool_port1 = str(df.iloc[19, 4])
pool_port2 = str(df.iloc[20, 4])
pool_port3 = str(df.iloc[21, 4])
pool_port4 = str(df.iloc[22, 4])
lb_mode_input = df.iloc[32, 2]
pool_name = str(fqdn + "-" + pool_port1)
monitor_input = df.iloc[36, 2]
# Pool builder
if member1 == "nan":
pool_member1 = ""
elif member1 != "nan":
pool_member1 = member1 + ":" + pool_port1 + " "
else:
pass
if member2 == "nan":
pool_member2 = ""
elif member2 != "nan":
pool_member2 = member2 + ":" + pool_port2 + " "
else:
pass
if member3 == "nan":
pool_member3 = ""
elif member3 != "nan":
pool_member3 = member3 + ":" + pool_port3 + " "
else:
pass
if member4 == "nan":
pool_member4 = ""
elif member4 != "nan":
pool_member4 = member4 + ":" + pool_port4 + " "
else:
pass
if lb_mode_input == "Round Robin":
lb_mode = "load-balancing-mode round-robin "
elif lb_mode_input == "Least connections":
lb_mode = "load-balancing-mode least-connections-node "
elif lb_mode_input == "Observed":
lb_mode = "load-balancing-mode observed-node "
else:
pass
if monitor_input == "TCP":
monitor = "monitor tcp "
elif monitor_input == "TCP 30 seconds":
monitor = "monitor tcp-30 "
elif monitor_input == "Self-Service":
monitor = "monitor self-service "
elif monitor_input == "None":
monitor = ""
else:
monitor = " monitor " + input("Please enter the health monitor name: ") + " "
member = IPAddress(member1)
# Lists for each LB pair containing the node subnets.
loadbalancer1_node_IPs = IPSet([IPNetwork('1.1.1.0/22'), IPNetwork('2.2.2.0/22'), IPNetwork('3.3.3.0/22')])
loadbalancer2_node_IPs = IPSet([IPNetwork('4.4.4.0/23'), IPNetwork('2.2.2.0/23'), IPNetwork('3.3.3.0/23')])
# Provides the LB the VIP is to be built on based on node IP address.
if IPAddress(member) in loadbalancer1_node_IPs:
loadbalancer = "The LB pair you need to build this VIP on is loadbalancer1_node_IPs"
subnet = "You need a VIP ip from subnet 1.1.1.0/22, 2.2.2.0/22, or 3.3.3.0/22"
elif IPAddress(member) in loadbalancer2_node_IPs:
loadbalancer = "The LB pair you need to build this VIP on is loadbalancer2_node_IPs"
subnet = "You need a VIP ip from subnet 4.4.4.0/23, 2.2.2.0/23, or 3.3.3.0/23"
else:
pass
print(loadbalancer)
print(fqdn)
print(subnet)
vip_ip_input = IPAddress(input("Which VIP IP did you choose? "))
vip_ip = str(vip_ip_input) + str(":") + str(service_port_input)
ip = str(vip_ip_input)
if iRule1_input == "_sys_https_redirect":
iRule1 = "_sys_https_redirect "
elif iRule1_input == "x-Forwarding":
iRule1 = "x-forwarding "
else:
iRule1 = ""
if iRule2_input == "_sys_https_redirect":
iRule2 = "_sys_https_redirect "
elif iRule2_input == "x-Forwarding":
iRule2 = "x-forwarding "
else:
iRule2 = ""
if snat_input == "Auto Map":
snat = "snat automap "
else:
snat = ""
if one_connect_input == "oneconnect":
one_connect = "oneconnect "
else:
one_connect = ""
if http_profile_input == "http":
http_profile = "http "
else:
http_profile = ""
if primary_persist_input == "Source Addr":
primary_persist = " persist replace-all-with { source_addr } "
elif primary_persist_input == "Dest Addr":
primary_persist = " persist replace-all-with { dest_addr } "
elif primary_persist_input == "Cookie":
primary_persist = " persist replace-all-with { cookie } "
else:
primary_persist = ""
if fallback_persist_input == "Source Addr":
fallback_persist = " fallback-persistence source_addr "
elif fallback_persist_input == "Dest Addr":
fallback_persist = " fallback-persistence dest_addr "
elif fallback_persist_input == "Cookie":
fallback_persist = " fallback-persistence cookie "
else:
fallback_persist = ""
folder = r'C:\Users\username\Desktop\LBARF script' + str(change_order)
createfolder(folder)
fh = open(folder + "/" + str(change_order) + ".txt", "w")
fh.write("This program is a test. I assume no responsibility." + "\r" +
"Please verify everything looks correct." + "\r" + "\r" + "This script was run on " +
x.strftime("%x") + " # " + x.strftime("%I") + ":" + x.strftime("%M") + " " + x.strftime("%p") +
" for change order " + change_order + "\r" + "\r" + fqdn + "\r" + ip + "\r" + loadbalancer + "\r" + "\r")
fh.write("create ltm pool " + pool_name + " members add { " + pool_member1 + pool_member2 + pool_member3 +
pool_member4 + " } " + monitor + lb_mode + description + "\r" + "\r")
if service_port_input == "80 and 443":
service_port_input = "80"
else:
pass
if service_port_input == "80":
if iRule1_input == "_sys_https_redirect":
port_80_redirect_vip = ("create ltm virtual " + fqdn + "-80 destination " + ip +
":80 profiles add { http } snat automap rules { _sys_https_redirect } "
+ description + "\r" + "\r")
fh.write(port_80_redirect_vip)
print("Port 80 VIP is complete, We will now move on to the 443 VIP")
service_port_input = "443"
irules = "rules { " + iRule2 + " } "
elif iRule2_input == "_sys_https_redirect":
port_80_redirect_vip = ("create ltm virtual " + fqdn + "-80 destination " + ip +
":80 profiles add { http } snat automap rules { _sys_https_redirect } "
+ description + "\r" + "\r")
fh.write(port_80_redirect_vip)
print("Port 80 VIP is complete, We will now move on to the 443 VIP")
service_port_input = "443"
irules = "rules { " + iRule2 + " } "
else:
vip_build = ("create ltm virtual " + fqdn + "-" + service_port_input + " destination " + ip + ":" +
service_port_input + " pool " + pool_name + " profiles add { " + http_profile + " } " +
primary_persist + fallback_persist + description + "\r" + "\r")
fh.write(vip_build)
service_port_input = "443"
else:
pass
if iRule1.__contains__("sys"):
rules = "rules { " + iRule2 + " } "
elif iRule2.__contains__("sys"):
rules = "rules { " + iRule1 + " } "
else:
rules = "rules { " + iRule1 + iRule2 + " } "
if service_port_input == "443":
ssl_profile_input = input("Will you be applying an SSL profile? y or n: ").lower()
if ssl_profile_input.__contains__("y"):
cert = input("Installing a cert? y or n: ").lower()
if cert.__contains__("y"):
ssl_profile_name = fqdn + "-clientssl"
upload_name = fqdn + "-" + x.strftime("%Y")
print("**** SSL PROFILE CONFIG *****")
print("**** Upload Cert/Key to " + loadbalancer + " with the name of " + upload_name)
ssl_cert = fqdn + "-" + x.strftime("%Y") + ".crt "
ssl_key = fqdn + "-" + x.strftime("%Y") + ".key "
chain_input = input("Will a chain be applied? y or n: ").lower()
if chain_input.__contains__("y"):
chain = " chain " + input("What is the name of the chain? ")
else:
chain = ""
ciphers_input = input("Will ciphers be applied? ").lower()
if ciphers_input.__contains__("y"):
ciphers = "ciphers " + input("Enter Ciphers here: ")
else:
ciphers = ""
ssl_config = ("create ltm profile client-ssl " + ssl_profile_name + " cert " + ssl_cert + " key " +
ssl_key + ciphers + " " + chain + description + "\r" + "\r")
else:
ssl_profile_name = input("What is the SSL profile name? ")
else:
ssl_profile_name = ""
cert = ""
key = ""
chain = ""
ciphers = ""
ssl_config = ""
else:
ssl_profile_name = ""
cert = ""
key = ""
chain = ""
ciphers = ""
ssl_config = ""
profile = "profiles add { " + one_connect + http_profile + ssl_profile_name + " } "
if profile == "profiles add { } ":
profiles = ""
else:
profiles = ("profiles add { " + one_connect + http_profile + ssl_profile_name + " } ")
options = (profiles + snat + primary_persist + fallback_persist + rules + description)
if cert.__contains__("y"):
fh.write(ssl_config)
else:
pass
fh.write("create ltm virtual " + fqdn + "-" + service_port_input + " destination " + ip + ":" + service_port_input +
" pool " + pool_name + " " + options + "\r" + "\r")
fh.close()
key_files = 'C:/Users/username/Downloads/*.key'
crt_files = 'C:/Users/username/Downloads/*.crt'
cer_files = 'C:/Users/username/Downloads/*.cer'
pem_files = 'C:/Users/username/Downloads/*.pem'
pfx_files = 'C:/Users/username/Downloads/*.pfx'
filelist = glob.glob(key_files)
for single_file in filelist:
shutil.move(single_file, folder)
filelist = glob.glob(crt_files)
for single_file in filelist:
shutil.move(single_file, folder)
filelist = glob.glob(cer_files)
for single_file in filelist:
shutil.move(single_file, folder)
filelist = glob.glob(pem_files)
for single_file in filelist:
shutil.move(single_file, folder)
filelist = glob.glob(pfx_files)
for single_file in filelist:
shutil.move(single_file, folder)
# os.rename(lbarf_file, 'C:/Users/username/Downloads/' + change_order + ".xlsx")
shutil.move(lbarf_file, folder)
print("The CLI commands for this VIP are located at " + folder)
exit(input("Press Enter to exit."))
It was suggested to me to put the script as a function and import it to the code for the GUI which I did and named it vipTest. Next I imported it to PySimpleGUI I am using to create a simple form with here:
import vipTest
import PySimpleGUI as sg
# Very basic form. Return values as a list
form = sg.FlexForm('VIP Builder') # begin with a blank form
layout = [
[sg.Text('Please enter the information below')],
[sg.Text('What is the change order for this VIP?: ', size=(30, 1)), sg.InputText('change #')],
[sg.Text('Enter the full path of the LBARF form: ', size=(30, 1)), sg.InputText('location path')],
[sg.Text('Which VIP IP did you choose?: ', size=(30, 1)), sg.InputText('ip address of vip')],
[sg.Submit(), sg.Cancel()]
]
lbarf_file, folder = vipTest.createfolder(directory)
button, values = form.Layout(layout).Read()
I am having trouble getting an output from the GUI of the results. When I run this program in PyCharm the GUI does not open and script runs in the console. Even if I can get the GUI to work with a specific example, I am concerned I might need to have the GUI add a text field each time the information in the excel file is blank. I would like to ultimately like to display the config commands from the gui but am not getting anywhere with it as is. Any assistance on this is greatly appreciated. Thank you.

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.

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

why there is a "SyntaxError: invalid syntax"

Error message:
runfile('//rschfs1x/userrs/xd73_RS/Documents/Python Scripts/test_515.py', wdir='//rschfs1x/userrs/xd73_RS/Documents/Python Scripts')
File "//rschfs1x/userrs/xd73_RS/Documents/Python Scripts/test_515.py", line 120
if __name__ == "__main__":
^
SyntaxError: invalid syntax
Really not sure why thre is this problem
def sendemail(alertmessage):
msg = MIMEText(alertmessage)
msg['Subject'] = 'Patent Data Error Message'
msg['From'] = "patentcornell#gmail.com"
msg['To'] = "patentcornell#gmail.com"
# Credentials (if needed)
username = 'patentcornell#gmail.com'
password = ''
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail("hello", "xd73#cornell.edu", alertmessage)
server.sendmail("hello", "jq58#cornell.edu", alertmessage)
#server.sendmail("hello", "sl2448#cornell.edu", alertmessage)
server.sendmail("hello", "patentcornell#gmail.com", alertmessage)
'''
Shanjun Li <sl2448#cornell.edu>,
Panle Barwick <pjb298#cornell.edu>,
Jing Qian <jq58#cornell.edu>
'''
server.quit()
def main(year = 1985, starting_page = 2, filepath = ""):
time1 = time.time()
print "start timing: " + str(time1)
driver = webdriver.Firefox()
driver.get("http://epub.sipo.gov.cn/")
elem = driver.find_element_by_id("soso_text")
f = open( filepath + "year_test_" + str(year), "wb")
flog = open(filepath + "log_" + str(year), "wb")
driver.get("http://epub.sipo.gov.cn/")
elem = driver.find_element_by_id("soso_text")
elem.send_keys(str(year))
elem.send_keys(Keys.RETURN)
content = driver.page_source.encode('utf-8')
for uchar in content:
f.write(bytearray([ord(uchar)]))
flog.write(str(year) + " " + str(1) + "\n")
case = 1
nextpage = driver.find_element_by_xpath("/html/body/div[3]/div[2]/div[4]/a[7]")
turnto = driver.find_element_by_xpath("/html/body/div[3]/div[2]/div[4]/span")
print "hello 0"
print nextpage.get_attribute("innerHTML")
totalnum = int(nextpage.get_attribute("innerHTML"))
print "totalnum: " + str(totalnum)
#try:
# from which page we start downloading, the starting page
for i in range(starting_page, totalnum + 1):
timeinterval_1 = time.time()
print str(year) + " page: " + str(i)
#turnto = driver.find_element_by_xpath("/html/body/div[3]/div[2]/div[4]/span")
turnto = driver.find_element_by_id('pn')
turnto.send_keys(str(i))
turnto.send_keys(Keys.ENTER)
#turnto.submit()
content = driver.page_source.encode('utf-8')
# test file writing speed
time_file_start = time.time()
for uchar in content:
f.write(bytearray([ord(uchar)]))
f.write("\n")
#robust Check
print "interval: " + str(timeinterval_2 - timeinterval_1)
if timeinterval_2 - timeinterval_1 > 60:
flog.write("lost: " + str(year) + " page: " + str(i) + "\n")
print "too long to load " + str(year) + " " + str(i)
continue
else:
flog.write(str(year) + " " + str(i) + "\n")
continue
#except ValueError as err:
print(err.args)
sendmail("xd73_RS: " + err.args + " " + str(time.time())
if __name__ == "__main__":
filepath = "U:/Documents/Python Scripts/test_data_515/"
#sendemail("test email function!")
main(2010, 2, filepath)
This line:
sendmail("xd73_RS: " + err.args + " " + str(time.time())
Has unmatched parentheses. Generally if the syntax error occurs on line n, its a good idea to check the syntax on line n-1.

Categories