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.
Related
This error usually should not appear, but recently when I run this, this error appears, and I have no clue how I will fix it.
Please if Anyone can help me to fix this error on this code below:
import requests
import json
from time import sleep
global OFFSET
OFFSET = 0
botToken = ""
global requestURL
global sendURL
requestURL = "http://api.telegram.org/bot" + botToken + "/getUpdates"
sendURL = "http://api.telegram.org/bot" + botToken + "/sendMessage"
def update (url):
global OFFSET
try:
update_raw = requests.get(url + "?offset=" + str(OFFSET))
update = update_raw.json()
result = extract_result(update)
if result != False:
OFFSET = result['update_id'] + 1
return result
else:
return False
except requests.exceptions.ConnectionError:
pass
def extract_result (dict):
result_array = dict['result']
if result_array == []:
return False
else:
result_dic = result_array[0]
return result_dic
def is_callback (dict):
if 'callback_query' in dict:
return True
def send_message (chatId, message):
requests.post(sendURL + "?chat_id=" + str(chatId) + "&text=" + message)
def send_message_button (chatId, message, buttonJSON):
requests.post(sendURL + "?chat_id=" + str(chatId) + "&reply_markup=" + buttonJSON + "&text=" + message)
#print (sendURL + "?chat_id=" + str(chatId) + "&reply_markup=" + buttonJSON + "&text=" + message)
while True:
newmessage = update (requestURL)
if newmessage != False:
if is_callback(newmessage) == True:
userchatid = newmessage['callback_query']['message']['chat']['id']
usertext = newmessage['callback_query']['message']['text']
username = newmessage['callback_query']['message']['chat']['first_name']
callback_data = newmessage['callback_query']['data']
send_message (userchatid, "Callback from " + callback_data + ", pressed by " + username)
else:
userchatid = newmessage['message']['chat']['id']
usertext = newmessage['message']['text']
username = newmessage['message']['chat']['first_name']
if usertext.lower() == "button":
buttonDict1 = {"text":"Knopf\n" + "hitest", "callback_data":"Knopf"}
buttonDict2 = {"text":"Knopf2", "callback_data":"Knopf2"}
buttonArr = {"inline_keyboard":[[buttonDict1, buttonDict2]]}
send_message_button (userchatid, "Hi " + username, json.dumps(buttonArr))
else:
send_message(userchatid, "You said: " + usertext)
sleep (1)
This is the error that appears to me after I run this bot
Line: 67
userchatid = newmessage['message']['chat']['id']
KeyError: 'message'
You catch the requests.exceptions.ConnectionError but don't handle it ( in the update function ), so now update does not return False as it returns nothing at all and can pass your check and cause havock.
Try to deal with the exception, or at least put a print in there to see if it's the one causing you issues, good luck!
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. '''
So I am working on a certain code to modify a text file. When I use this function individually, it works perfectly
TextRotation.rotTextC("cv.txt")
But when I use it in batch as a list like this
def files_LTXT(pathF):
return glob.glob(pathF + "*" + ".txt")
for i in range (len(listFileTXT)):
TextRotation.rotTextC(listFileTXT[i])
IT gives the following error:
File "C:\Users\Administrator\PycharmProjects\openCV\TextRotation.py", line
9, in rotLineC
0
valueObj = int(lineStr[c1])
0.472917 0.713281 0.845833 0.376563
IndexError: string index out of range
Function rotLineC is as follows:
def rotLineC(lineStr, c1):
if len(lineStr) > 2:
valueObj = int(lineStr[c1])
print(valueObj)
valueXC = float(lineStr[(c1+2):(c1+10)])
valueYC = float(lineStr[(c1+11):(c1+19)])
valueW = float(lineStr[(c1+20):(c1+28)])
valueH = float(lineStr[(c1+29):(c1+37)])
# print(valueXC)
# print(valueYC)
# print(valueW)
# print(valueH)
nValueXC = round(1 - valueYC, 6)
nValueYC = round(valueXC, 6)
nValueW = round(valueH, 6)
nValueH = round(valueW, 6)
rotString = str(int(valueObj)) + " " + str(nValueXC) + " " + \
str(nValueYC) + " " + str(nValueW) + " " + str(nValueH)
print(str(nValueXC) + " " + str(nValueYC) + " " + str(nValueW) + " " + str(nValueH))
print(rotString)
return rotString
This function works fine!
for i in range (len(listFileJPG)):
ImageRotation.rotImage(listFileJPG[i])
Mind to include the / to the end of the path! (I am assuming a UNIX environment here)
If the path is 'dev/my_pat', for example, your function will fail. The path must end with a /. You can it to your function:
...
if pathF[-1] != '/':
return glob.glob(pathF + "/*.txt")
...
Also, do not iterate using indices, use the pythonic way!
for file in listFileTXT(my_path):
TextRotation.rotTextC(file)
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`
I am trying to get the System User's Login Time using Python 3.7. I have tried win32net and platform module for Python but, functions are not defined in platform module and Win32net is not compatible with Python 3 and more. I have tried following code:
import platform
platform.uname()
import platform
os_name = platform.uname()[0].lower()
if os_name == "windows":
get_win_login_time()
elif os_name.endswith("nix"):
get_nix_login_time()
Try These ( install win32com.client and subprocess modules first ):
import win32com.client, time
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("SELECT * FROM Win32_NetworkLoginProfile")
def Convert_to_human_time(dtmDate):
strDateTime = ""
if dtmDate[4] == 0:
strDateTime = dtmDate[5] + '/'
else:
strDateTime = dtmDate[4] + dtmDate[5] + '/'
if dtmDate[6] == 0:
strDateTime = strDateTime + dtmDate[7] + '/'
else:
strDateTime = strDateTime + dtmDate[6] + dtmDate[7] + '/'
strDateTime = strDateTime + dtmDate[0] + dtmDate[1] + dtmDate[2] + dtmDate[3] + " " + dtmDate[8] + dtmDate[9] + ":" + dtmDate[10] + dtmDate[11] +':' + dtmDate[12] + dtmDate[13]
return strDateTime
for objItem in colItems:
if objItem.Name is not None:
print("Name: " + str(objItem.Name))
if objItem.LastLogon is not None:
print("Last Logon (Normal Format): " + str(objItem.LastLogon))
print("Last Logon (Human Readable Format): " + Convert_to_human_time(objItem.LastLogon))
if objItem.LastLogoff is not None:
print("Last Logoff (Normal Format): " + str(objItem.LastLogoff))
print("Last Logoff (Human Readable Format): " + Convert_to_human_time(objItem.LastLogoff))
if objItem.LogonHours is not None:
print("Logon Hours: " + str(objItem.LogonHours))
if objItem.LogonServer is not None:
print("Logon Server: " + str(objItem.LogonServer))
if objItem.NumberOfLogons is not None:
print("Number Of Logons: " + str(objItem.NumberOfLogons))
Another way :
from subprocess import check_output
import sys
get_result = check_output("wmic netlogin get name, fullname, lastlogon", shell=True, stderr=False)
print(get_result)
clean_result = str(get_result).lstrip("b'").rstrip("'").replace("\\r\\r\\n", "\n").replace('\n\n', '\n').split('\n')[2:-1]
for items in clean_result:
print(items.lstrip().rstrip())
Good Luck ...