can anyone help? I got an error when I was trying to test a simple code with napalm. I used cisco on GNS3. I also added optional arguments (delay_factor), but it got the same error.
from napalm import get_network_driver
driver = get_network_driver("ios")
others = {
"secret" : "cisco",
"dest_file_system" : "nvram:",
'delay_factor': 5
}
device = driver(hostname="192.168.124.148", username="cisco", password="cisco", optional_args=others)
device.open()
device.load_merge_candidate(filename="candidate")
compare = device.compare_config()
print(compare)
device.commit_config()
device.close()
Traceback (most recent call last):
File "c.py", line 16, in <module>
device.commit_config()
File "/Users/zakky.muhammad/Downloads/tmp/Env/lib/python3.8/site-packages/napalm/ios/ios.py", line 555, in commit_config
output += self.device.save_config()
File "/Users/zakky.muhammad/Downloads/tmp/Env/lib/python3.8/site-packages/netmiko/cisco/cisco_ios.py", line 37, in save_config
return super(CiscoIosBase, self).save_config(
File "/Users/zakky.muhammad/Downloads/tmp/Env/lib/python3.8/site-packages/netmiko/cisco_base_connection.py", line 224, in save_config
output = self.send_command(command_string=cmd)
File "/Users/zakky.muhammad/Downloads/tmp/Env/lib/python3.8/site-packages/netmiko/base_connection.py", line 1335, in send_command
raise IOError(
OSError: Search pattern never detected in send_command_expect: R\#
You can use the code that I have shared below.
from napalm import get_network_driver
driver = get_network_driver('eos')
device = driver('ip_address', 'username', 'password')
device.open()
device.load_replace_candidate(filename='device.conf')
print (device.compare_config())
if len(device.compare_config()) > 0:
choice = input("\nWould you like to Replace the Configuration file? [yN]: ")
if choice == 'y':
print('Committing ...')
device.commit_config()
choice = input("\nWould you like to Rollback to previous config? [yN]: ")
if choice == 'y':
print('Rollback config is in progress ...')
device.rollback()
else:
print('Discarding ...')
device.discard_config()
else:
print ('No difference')
device.close()
print('Done.')
Related
During a small test to learn how to run a small server, the method 'start' returns an error when I tried to start the server afet including the endpoint and some variables:
from opcua import Server
import datetime
import time
my_server = Server()
url = 'opc.tcp//192.168.1.5:4841'
my_server.set_endpoint(url)
name = "OPCUA_TEST_Server"
addspace = my_server.register_namespace(name)
node = my_server.get_objects_node()
param = node.add_object(addspace, "Parameters")
t_text1 = param.add_variable(addspace, "Text 1", "Text_1")
i_int1 = param.add_variable(addspace, "myInteger1", 0)
b_bool1 = param.add_variable(addspace, "myBool1", False)
t_text1.set_writable()
i_int1.set_writable()
b_bool1.set_writable()
my_server.start()
print("Server started at {}".format(url))
print("At" + str(datetime.datetime.now()))
while True:
time.sleep(0.5)
And in line of
my_server.start()
Returns the following error:
Endpoints other than open requested but private key and certificate are not set.
Traceback (most recent call last):
File "C:/Users/a767611/Desktop/Repositorios/flexigrid/opc-ua-server/test-opc-ua-server.py", line 23, in <module>
my_server.start()
File "C:\Users\a767611\Anaconda3\lib\site-packages\opcua\server\server.py", line 347, in start
raise exp
File "C:\Users\a767611\Anaconda3\lib\site-packages\opcua\server\server.py", line 344, in start
self.bserver.start()
File "C:\Users\a767611\Anaconda3\lib\site-packages\opcua\server\binary_server_asyncio.py", line 116, in start
self._server = self.loop.run_coro_and_wait(coro)
File "C:\Users\a767611\Anaconda3\lib\site-packages\opcua\common\utils.py", line 197, in run_coro_and_wait
return task.result()
File "C:\Users\a767611\Anaconda3\lib\asyncio\base_events.py", line 1393, in create_server
raise ValueError('Neither host/port nor sock were specified')
ValueError: Neither host/port nor sock were specified
Your endpoint URL is malformed.
It should be:
url = 'opc.tcp://192.168.1.5:4841'
note the missing colon after opc.tcp.
Hi I am trying to make a simple login in system and having problems with hashing the password and comparing it with the users input using bcrypt using tkinter in python 3. I think I have encoded/decoded them properly but now i am getting the error message "invalid salt", any suggestions?
error code:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Kev\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:/Users/Kev/IdeaProjects/HelloWorld/Login/login.py", line 296, in <lambda>
command=lambda: [sign_in(), root.withdraw()])
File "C:/Users/Kev/IdeaProjects/HelloWorld/Login/login.py", line 33, in sign_in
if sign_in_verification():
File "C:/Users/Kev/IdeaProjects/HelloWorld/Login/login.py", line 54, in sign_in_verification
if bcrypt.checkpw(pw, pw_to_check):
File "C:\Users\Kev\AppData\Local\Programs\Python\Python38\lib\site-packages\bcrypt\__init__.py", line 107, in checkpw
ret = hashpw(password, hashed_password)
File "C:\Users\Kev\AppData\Local\Programs\Python\Python38\lib\site-packages\bcrypt\__init__.py", line 86, in hashpw
raise ValueError("Invalid salt")
ValueError: Invalid salt
password = tk.StringVar()
raw_password = r"{}".format(password) # convert tkinter string variable to raw string
hashed_password = bcrypt.hashpw(raw_password.encode("utf-8"), bcrypt.gensalt()) # generate hashed pw
def add_account():
new_password_info = hashed_password.decode("utf-8")
new_username_info = username.get()
file = open(file_name, "a")
file.write(new_username_info + "." + new_password_info ")
file.close()
def sign_in_verification():
pw = password.get().encode("utf-8") # encode password
if username.get() == "" or pw == "":
return False
else:
for line in open(file_name, "r").readlines():
login_info = line.strip().split(".")
if username.get() == login_info[0]:
pw_to_check = login_info[1].encode("utf-8") #
# check passwords match
if bcrypt.checkpw(pw, pw_to_check):
return True
I am new to programming and I created a son program that stores your name, than the items in your list.
import json
list_ = []
filename = 'acco.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What is your name? ")
while True:
list_items = input("What is the item you want to add? q to quit")
if list_items == 'q':
break
list_.append(list_items)
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("These is your list of items:")
print(list_)
print("We'll remember you when you come back, " + username + "!")
json.dump(list_items, f_obj)
else:
print("Welcome back, " + username + "!")
print("Here are the items of your list:")
print(_list)
However, an error keeps showing up when I run the program. The error says that there is an error in line 8, the line of code where it says
username = json.load(f_obj)
This is the exact error
Traceback (most recent call last):
File "/Users/dgranulo/Documents/rememberme.py", line 8, in <module>
username = json.load(f_obj)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 8 (char 7)
If anyone can help that would be greatly appreciated,
Thanks,
You're serializing objects one by one. A str and a list. Do it once in a collection like a list or dict.
This one works;
>>> print(json.loads('"a"'))
a
But this one a str and a list is an error;
>>> json.loads('"a"[1]')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.6/json/decoder.py", line 342, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 4 (char 3)
Write to the file with a dict;
with open(filename, 'w') as f_obj:
# json.dump(username, f_obj)
print("These is your list of items:")
print(list_)
print("We'll remember you when you come back, " + username + "!")
# json.dump(list_items, f_obj)
# dump a dict
json.dump({'username': username, 'items': list_}, f_obj)
Now json.load will return a dict with keys username and items.
I have the following code which returns the public IP's
def gather_public_ip():
ACCESS_KEY = config.get('aws','access_key')
SECRET_KEY = config.get('aws','secret_key')
regions = regions = ['us-west-2','eu-central-1','ap-southeast-1']
# regions = config.get('aws','region').split(',')
all_EIP = []
for region in regions:
client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
addresses_dict = client.describe_addresses()
for eip_dict in addresses_dict['Addresses']:
if 'PrivateIpAddress' in eip_dict:
print eip_dict['PublicIp']
# return str(eip_dict['PublicIp'])
all_EIP.append(eip_dict['PublicIp'])
print all_EIP
# print str(all_EIP)
return str(all_EIP)
This is called and returned as :
net_range = gather_public_ip()
for ip in net_range:
r = s.run(ip)
run looks like :
def run(self, targets="" ,options="-Pn"):
#start a new nmap scan on localhost with some specific options
syslog.syslog("Scan started")
parsed = None
nmproc = NmapProcess(targets,options)
rc = nmproc.run()
if rc != 0:
syslog.syslog("nmap scan failed: {0}".format(nmproc.stderr))
try:
parsed = NmapParser.parse(nmproc.stdout)
self.report = parsed
except NmapParserException as e:
syslog.syslog("Exception raised while parsing scan: {0}".format(e.msg))
syslog.syslog("Scan complete")
syslog.syslog("Scan duration: "+ str(parsed.elapsed))
self.report = parsed
return parsed
after printing the list , this throws me :
Traceback (most recent call last):
File "portwatch.py", line 300, in <module>
r = s.run(ip)
File "portwatch.py", line 239, in run
rc = nmproc.run()
File "/usr/local/lib/python2.7/dist-packages/libnmap/process.py", line 257, in run
else shlex.split(self.__nmap_command_line)
File "/usr/lib/python2.7/shlex.py", line 279, in split
return list(lex)
File "/usr/lib/python2.7/shlex.py", line 269, in next
token = self.get_token()
File "/usr/lib/python2.7/shlex.py", line 96, in get_token
raw = self.read_token()
File "/usr/lib/python2.7/shlex.py", line 172, in read_token
raise ValueError, "No closing quotation"
ValueError: No closing quotation
Make sure your ip is not "" or shlex will fail, cf Which exception to raise if a given string does not match some format?
This is my first post. I am getting the error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "intruder.py", line 47, in <module>
main()
File "intruder.py", line 16, in main
readfile()
File "intruder.py", line 34, in readfile
pickle.load(f)
File "/usr/lib/python2.7/pickle.py", line 1378, in load
return Unpickler(file).load()
File "/usr/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.7/pickle.py", line 880, in load_eof
raise EOFError
EOFError
For code:
#!/usr/bin/python
import getpass
import bz2
import pickle
import marshal
import os, sys
global data
global firsttime
global password
global user
fp = open("firsttime.txt", "r")
data = fp.read();
firsttime = data
def main():
readfile()
name = raw_input('What is your name? ')
if name == user:
user_input = getpass.getpass('Enter Password: ')
if user_input != password:
print "Intruder alert!"
main()
if name != user:
print "Intruder alert!"
main()
print "Login Successful! "
def savefile():
n = open("settings.pkl", 'wb')
pickle.dump(user, n, 2)
pickle.dump(password, n, 2)
n.close()
def readfile():
f = open("settings.pkl", "rb")
pickle.load(f)
f.close()
if data < 1:
user = raw_input ("Enter desired username: ")
password = getpass.getpass('Enter desired password: ')
# encrypted_password = bz2.compress(password)
# bz2.decompress(encrypted_password)
data = 2
g = open("firsttime.txt", "rb")
outf.write(g(data))
g.close()
savefile()
if data > 1:
main()
EDIT: I fixed the above problem. I changed:
fp = open("firsttime.txt", "r")
to:
fp = file("firsttime.txt", "r")
And now it shows the error:
Traceback (most recent call last):
File "intruder.py", line 47, in <module>
main()
File "intruder.py", line 17, in main
if name == user:
NameError: global name 'user' is not defined
This is strange, because user is defined as the user's raw_input, and it askes me for it right before this error appears.
The global keyword tells Python that you're refering to a global variable.
It doesn't create the variable.
You need to change to the following.
Global defs, remove the global data definitions you have and replace with this:
data = None
firsttime = None
password = None
user = None
Then in your functions you tell Python that you're refering to the global, not a local variable. This is only required to write to the variable, not read from it.
def main():
global user, firsttime, password, user
<snip>
def savefile():
global user, firsttime, password, user
<snip>
def readfile():
global user, firsttime, password, user
<snip>
Apart from that, the code has other issues (fp is never closed, etc), but I won't critique other issues.