The Invisible Invalid Syntax - python

I am running this code to list the IP addresses on my network along with the mac addresses but i ran into this problem. it says invalid syntax but i can't seem to find what is wrong with it
I've tried removing spaces and replacing them with tabs but it doesn't fix it. i also tried moving them one up or down but still doesn't work. Any help?
The Whole code:
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 + get_mac_address(ip=ip, network_request=True)
elif (ip == '192.168.2.' + str(maxr + 1) and exit_code == 0):
print('192.168.2.' + str(maxr), bcolors.OKGREEN + "ONLINE" + bcolors.ENDC + get_mac_address(ip=ip, network_request=True))
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)
I am supposed to see the IP addressees along with the mac but i get this error code:
$ python test.py
File "test.py", line 34
elif (ip == '192.168.2.' + str(maxr + 1) and exit_code == 0):
^
SyntaxError: invalid syntax

I just forgot to add the ) at the end of the line above. Thanks to #depperm he showed me my mistake. Where it says ''' print(ip, bcolors.OKGREEN + "ONLINE" + bcolors.ENDC + get_mac_address(ip=ip, network_request=True)
at the end of the bracket add one more. '''

Related

unexpected EOF while looking for matching `'': What does this mean?

these are the error messages I am receiving from the terminal when I run add_user.py
sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file
After some reading online I am led to believe that these errors are thrown when I am missing a matching parenthesis or quotation mark?I have looked through the file several times but since it has been a few hours, I might just be looking straight over the error. If it is not a missing quotation mark or parenthesis, please explain what might be causing the issue so I can fix it. Thanks to all who help!
import csv
import os
filename = "/root/Downloads/linux_users.csv"
def create_username(aList):
if (len(aList) < 2):
print("INVALID RECORD")
else:
tokens = list(aList[2])
username = tokens[0].lower() + aList[1].lower()
return username
with open(filename) as f_handle:
csv_reader = csv.reader(f_handle)
next(csv_reader)
userList = []
groupList = []
recordCopy = []
rep = 0
tick = True
for record in csv_reader:
if (record[7] == ""):
record.remove(record[7])
for data in record:
if (data == ""):
print("ERROR: MISSING INFORMATION. USER ID: " + record[0] + " HAS NOT BEEN ADDED")
tick = False
if ((record[6] not in groupList) and (tick == True)):
groupList.append(record[6])
if (tick == True):
username = create_username(record)
if (username in userList):
username += str(rep)
rep += 1
userList.append(username)
recordCopy.append(record)
else:
tick = True
for group in groupList:
os.system("groupadd " + group)
print("GROUP: " + group + " HAS SUCCESSFULLY BEEN CREATED")
i = 0
for record in recordCopy:
if (record[5] == "ceo"):
os.system("adduser " + userList[i] + " -g " + record[6] +
" -d /home/" + record[5] + " -s /bin/csh -u " + record[0] + " -p password")
os.system("passwd -e " + userList[i])
else:
os.system("adduser " + userList[i] + " -g " + record[6] +
" -d /home/" + record[5] + " -s /bin/bash -u " + record[0] + " -p password")
os.system("passwd -e " + userList[i])
i += 1
print("USER: " + record[0] + " HAS SUCCESSFULLY BEEN ADDED")

how to telnet huawei switch with python script?

I want to telnet huawei switch with python script to read some basic staff like "display int brief" result. I know basic huawei command and some programming.
I can telnet cisco router with python script.
Here is my attempt so far
import telnetlib
import datetime
now = datetime.datetime.now()
host = "myhost" # your router ip
username = "user" # the username
password = "pass"
tn = telnetlib.Telnet(host,23,6)
tn.read_until("Username:")
tn.write(username+"\n")
tn.read_until("Password:")
tn.write(password+"\n")
tn.write("display int description"+"\n")
#tn.write("sh run"+"\n")
tn.write("quit"+"\n")
output = tn.read_all()
fp = open("sw_hu.txt","w")
fp.write(output)
fp.close()
I would use pexpect library then open connection with pexpect.spawn('telnet ip_address') module documentation is great start. If you now commands then it is mostly combination off sendline, expect and before.
child = pexpect.spawn ('telnet %s' % dev_name)
try:
i = child.expect_exact(['Password:', 'Username:'])
except (pexpect.EOF, pexpect.TIMEOUT):
return False
if i == 1:
child.sendline(user_name)
child.expect_exact('Password:')
child.sendline(passw)
else:
child.sendline(passw)
if child.expect_exact(['>', 'Wrong', pexpect.TIMEOUT], timeout=5):
child.close()
return False
child.sendline('sup')
i = child.expect_exact(['Password:', '>', 'Unknown', 'not set'])
if i == 1:
child.sendline('')
elif i == 2 or i == 3:
child.close()
return False
else:
child.sendline(ena)
if child.expect_exact(['>', 'Password', 'failed']):
child.close()
child.sendline('tftp %s put %s %s.backup.txt' % (TFTP, conf_name, name))
child.expect_exact(['>', 'successfully'])
if 'Unable' in child.before:
....
....
Edit: Added partial example to backup config (it is python 2.x and old Huawei router)
if w['router_type'] == "cisco":
tn.read_until("Username:")
tn.write(user.encode('ascii')+"\n"
#tn.write(user +"\n")
if password:
tn.read_until("Password:")
tn.write(password.encode("ascii") + "\n")(indent)
tn.write("terminal length 0\n")
tn.write("show version\n")
tn.write("show running-config view full\n")
tn.write("exit\n")
tn_output = tn.read_all()
print ("Logging out Router ") + w['host_name'] + ("_") + w['router_type'] + (".....")
flag = 1
if w['router_type'] == "huawei":
tn.read_until("Username:")
tn.write(user + "\n")
if password:
tn.read_until("Password:")
tn.write(password + "\n")
tn.write("screen-length 0 temporary\n")
tn.write("dis version\n")
tn.write("dis current-configuration\n")
tn_output = tn.read_until("return")
tn.write("quit\n")
print ("Logging out Router ") + w['host_name'] + ("_") + w['router_type'] + (".....")
flag = 1
if w['router_type'] == "MAIPU":
tn.read_until("login:")
tn.write(user + "\n")
if password:
tn.read_until("password:")
tn.write(password + "\n")
tn.write("more off\n")
tn.write("show version\n")
tn.write("show running\n")
tn.write("logout\n")
tn_output = tn.read_all()
flag = 1
print ("Logging out Router ") + w['host_name'] + ("_") + w['router_type'] + (".....")
print ("\n Count: " )+ str(v_count) + ("---\n")
if flag:
if v_count==0:
saveoutput = open ("BACKUP/" + HOST + ".txt" , "w")
saveoutput.write(tn_output)
print ("Saving new file ") + HOST + ("......")
elif v_count == 1:
previous_file = open("BACKUP/" + HOST + ".txt")
temp_file = previous_file.read()
if str(temp_file) != str(tn_output):
saveoutput = open ("BACKUP/" + HOST + "_v2.txt" , "w")
saveoutput.write(tn_output)`enter code here`
print ("Saving new file " )+ HOST + ("......")
elif v_count > 1:
previous_file = open("BACKUP/" + HOST + "_v" + str(v_count) + ".txt")
temp_file = previous_file.read()
if str(temp_file) != str(tn_output):
saveoutput = open ("BACKUP/" + HOST + "_v" + str(v_count + 1) + ".txt" , "w")
print ("Saving new version of file ") + HOST + ("......")`enter code here`

Python 2.7.12 netaddr.IPNetwork AddrFormatError

Version: Python 2.7.12
OS: Ubuntu 16.04.1
Kernel: 4.4.0-31-generic #50-Ubuntu SMP
Arch: ppc64le
netaddr.IPNetwork fails with:
netaddr.core.AddrFormatError: invalid IPNetwork '9.2.0.0/16'
I have a function:
def innet2(ip, net):
print("ip: "+ip, "net: " + net)
ip = IPAddress(ip).value
print("ipnew: " + str(ip))
network = IPNetwork(net)
print("network-first: " + str(network.first))
print("network-last: " + str(network.last))
if ip >= network.first and ip <= network.last:
return True
else:
return False
If I call this function at the beginning of my program for debug purposes
and it executes properly:
if __name__ == "__main__":
FLAGS(sys.argv)
startSSH()
print ("service ssh finished")
isParamReady = False
hostsStr = ""
isChef = False
for i in range(0, 100):
time.sleep(20)
print("test: " + str(innet("9.2.132.186", "9.2.0.0/16")))
print("test2: " + str(innet2("9.2.132.186", "9.2.0.0/16")))
print("test2: " + str(innet2("10.1.3.2", "9.2.0.0/16")))
isParamReady, hostsStr, isChef = **getHostIpStr()**
break
if (isParamReady is True and isChef is True):
execCommand(hostsStr)
else:
waitOrExit()
When it is called from getHostIPStr() it generates the AddrFormatError
def getHostIpStr():
hostsStr = "-host "
isChef = False
print("namespace= " + namespace)
print("FLAGS.job_name= " + FLAGS.job_name)
print("FLAGS.network= " + FLAGS.network)
ps_pods = v1.list_namespaced_pod(namespace, label_selector="job="
+ FLAGS.job_name)
job = v1batch.list_namespaced_job(namespace, label_selector="job="
+ FLAGS.job_name)
worker_num = job.items[0].spec.parallelism
items = ps_pods.items
print("items= ", len(items))
print("worker_num= " + str(worker_num))
if (len(items) < worker_num):
return False, "", False
for i in range(0, len(items)):
podIp = items[i].status.pod_ip
print("podIp:" + podIp)
print("localIp:" + localIp)
if (i == 0 and podIp == localIp):
isChef = True
hostIPs = getIp(podIp)
net = FLAGS.network
print("len of Ips: " + str(len(hostIPs)))
for j in range(0, len(hostIPs)):
print("j: " + str(j), "hostIPs[j]: " + hostIPs[j],
"network: " + FLAGS.network)
ip = hostIPs[j];
res = innet2(ip, net)
if (res is True):
podIp = hostIPs[j]
hostsStr = hostsStr + podIp
break
if (i < len(items)-1):
hostsStr = hostsStr + ","
return True, hostsStr, isChef
I discovered my problem.
I was passing a quoted network address and IPNetwork was failing when trying to convert the octet from of ip address into decimal format because the first octet had the string quote in it.

Python 3 ASCII code 219 issue

I compared code to other training example code out there and did a compare and everything matches. Here is my issue: I have a health bar and when I take damage the bar decreases.
The problem is when in my code I use █ the pipe line after the bar never stays put, it always move dynamically. When I use / the pipe bar always stays put and no issue. I'm guessing there is something in my terminal tool (using Pycharm) that it doesn't like ascii code 219. If it matters from reading forums the tool is set to UTF-8. example below so might not format correctly but top part you can see the | being shifted when using █ and the bottom part is fine when using /.
______________________________ __________
CARLOS: 2210/3260 |■■■■■■■■■■■■■■■■■ | 132/132 |//////////|
__________________ __________
CARLOS: 2219/3260 |///////////////// | 132/132 |//////////|
Code:
def get_stats(self):
hp_bar = ""
bar_ticks = (self.hp / self.maxhp) * 100 / 4
mp_bar = ""
mp_ticks = (self.mp / self.maxmp) * 100 / 10
while bar_ticks > 0:
hp_bar += '█'
bar_ticks -= 1
#num_spaces_needed = (100/4) - len(hp_bar)
#str_spaces_needed = ""
#while num_spaces_needed > 0:
#str_spaces_needed += " "
#num_spaces_needed -= 1
while len(hp_bar) < 25:
hp_bar += " "
while mp_ticks > 0:
mp_bar += "/"
mp_ticks -= 1
while len(mp_bar) < 10:
mp_bar += " "
hp_string = str(self.hp) + "/" + str(self.maxhp)
current_hp = ""
if len(hp_string) < 9:
decreased = 9 - len(hp_string)
while decreased > 0:
current_hp += " "
decreased -= 1
current_hp += hp_string
else:
current_hp = hp_string
mp_string = str(self.mp) + "/" + str(self.maxmp)
current_mp = ""
if len(mp_string) < 7:
decreased = 7 - len(mp_string)
while decreased > 0:
current_mp += " "
decreased -= 1
current_mp += mp_string
else:
current_mp = mp_string
print(" _______________________________ __________ ")
print(bcolors.BOLD + self.name + " " +
current_hp + " |" + bcolors.BAR + hp_bar + bcolors.ENDC + "| " +
current_mp + " |" + bcolors.OKBLUE + mp_bar + bcolors.ENDC + "| ")
You have to change your font type
Navigate to File -> Settings -> Editor -> Font
Font: Source Code Pro
Apply -> Ok
Rerun the program
Try the following at the top of your script:
import sys
reload(sys)
sys.setdefaultencoding('utf8')

Calling one module into another module

I have two python modules called main.py and black.py :
Main.py content as follows :
import os,sys,string,time
import subprocess,commands,re
import random
import black
class bcolors:
BOLD = '\033[1m'
UNBOLD = '033[0m'
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
def disable(self):
self.BOLD = ''
self.UNBOLD = ''
self.HEADER = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
self.FAIL = ''
self.ENDC = ''
def print_menu():
#subprocess.call("tput clear")
print " "
#print bcolors.OKBLUE + (35 * '-') + bcolors.OKBLUE
print bcolors.OKBLUE + '\t\t\t\t' + (52 * '*') + bcolors.OKBLUE
print ("\t\t\t\t\t\tM A I N - M E N U")
print '\t\t\t\t' + (52 * '*')
print ("\t\t\t\t 0. Enter POD Name(s).")
print ("\t\t\t\t 1. QUIT")
print '\t\t\t\t' + (52 * '*') + bcolors.ENDC
is_valid=0
while not is_valid:
try :
choice = int ( raw_input('Enter your choice [0-24] : ') )
is_valid = 1
except ValueError, e :
print ("'%s' is not a valid integer." % e.args[0].split(": ")[1])
return choice
########## M A I N #####################
rUser=commands.getoutput("id -un").strip()
if rUser != "oracle":
print bcolors.FAIL + " Login as mc_admin to run the script. Exiting .." + bcolors.ENDC
exit ()
else:
os.system("tput clear")
choice = print_menu()
###################
global podList #
podList = None #
###################
while choice >= 0 and choice < 1:
if choice == 0:
pPODName()
black.blackout()
and black.py content as follows:
def blackout():
def pPODName():
global podList
podList = str(raw_input('Enter pipe separated list of PODS : ')).upper().strip()
if podList:
try:
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -p " + "\"" + podList + "\""
prodP = commands.getoutput(cmd).strip()
if prodP:
print bcolors.FAIL + "Production Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + prodP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -t " + "\"" + podList + "\""
stagP = commands.getoutput(cmd).strip()
if stagP:
print bcolors.FAIL + "Stage/Test Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + stagP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -d " + "\"" + podList + "\""
devP = commands.getoutput(cmd).strip()
if devP:
print bcolors.FAIL + "Dev/Upgrade Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + devP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -i " + "\"" + podList + "\""
intstgP = commands.getoutput(cmd).strip()
if intstgP:
print bcolors.FAIL + "Internal Staging Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + intstgP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -r " + "\"" + podList + "\""
prtnP = commands.getoutput(cmd).strip()
if prtnP:
print bcolors.FAIL + "Partner Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + prtnP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -s " + "\"" + podList + "\""
stbyP = commands.getoutput(cmd).strip()
if stbyP:
print bcolors.FAIL + "DR/Standby Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + stbyP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -u " + "\"" + podList + "\""
unalloP = commands.getoutput(cmd).strip()
if unalloP:
print bcolors.FAIL + "Unallocated Pods [Status: Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + unalloP + bcolors.ENDC
cmd = "/fsnadmin/f516478/romeshar/myfolder/PodDetails.sh -l " + "\"" + podList + "\""
trlP = commands.getoutput(cmd).strip()
if trlP:
print bcolors.FAIL + "Trial Pods [Status: Customer Active|Dev Post Provisioning|Cloud Ops Provisioning]: \n" + bcolors.OKBLUE + trlP + bcolors.ENDC
except OSError:
print bcolors.FAIL + "Could not invoke Pod Details Script. " + bcolors.ENDC
podList = vPodName(podList)
print bcolors.FAIL + "\nYou Have Entered PodList as: " + podList + "\n" + bcolors.ENDC
uResp = str(raw_input('Do You Want To Continue [YES|Y|NO|N] : ')).upper().strip()
#if uResp == "NO" or uResp == "N":
if uResp != "YES" and uResp != 'Y':
pPODName ()
if __name__ == '__main__':
blackout()
I want black.py module to be called in main.py but when I am running main.py I am getting the following error:
[oracle#localhost tmp]$ ./main.py
****************************************************
M A I N - M E N U
****************************************************
0. Enter POD Name(s).
1. QUIT
Enter your choice [0-24] : 0
Traceback (most recent call last):
File "./main.py", line 131, in <module>
pPODName()
NameError: name 'pPODName' is not defined
pPODName has not been defined as far as main.py can tell.
Firstly
pPODName is defined within another function, so only that function is aware of it. This is referred to as being in local scope. Basically anything defined within a function is only accessible to that function, and nothing else.
For an example:
def test():
def test_local():
return 3
return test_local()
Running the function test gives you
>>> test()
3
However running the function test_local
>>> test_local()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'test_local' is not defined
Secondly
Secondly, when importing modules, you need to either qualify them with the module name, like you have done with black.blackout(), of you need to use:
from black import *
Although personally I don't like that, it makes it hard to see where methods are coming from.
Fix
For main.py to be able to call pPODName, it must be defined within the module as a whole, e.g.:
def blackout()
#do stuff here
def pPODNAME()
#do other stuff here
#note the indentation level is the same as blackout
and you must call it with
black.pPODName()
From main.py
You have some programming hierarchy level mistake
why pPODName is inner function of blackout ?
and has James said- if you are using outer and inner function the outer needs to call the inner.
I suggest you to use regular function in black.py
blackout function does nothing except containing the pPODName so you don't need it
Shlomy

Categories

Resources