I am currently trying to set up a test with Netmiko and Textfsm in Windows 10, but no matter what path I try to setup the textfsm environment variable, it still doesn't pick it up and throws an error:
Valid ntc-templates not found, please install https://github.com/networktocode/ntc-templates
and then set the NET_TEXTFSM environment variable to point to the ./ntc-templates/templates
directory.
I tried setting the environment variable manually via system properties --> environment variables, but still get the same message. I tried absolute as well as relative paths and no go. Ideally a relative path as the template folder will alway be alongside the script calling it. It might be something simple but im totally missing it right now.
The folder structure:
My Code:
import os, json
from netmiko import Netmiko
from netmiko import NetMikoAuthenticationException
templates = os.path.dirname(os.path.abspath(__file__)) + '\\ntc-template\\templates\\'
os.environ['NET_TEXTFSM']= templates
print(os.environ['NET_TEXTFSM'])
###############################################################
#Can i set the env var from within the scirpt using python?
#os.system(f'cmd /c "set NET_TEXTFSM={templates}"')
###############################################################
switch = {'device_type': 'cisco_ios',
'ip': '192.168.0.20',
'username': 'cisco',
'password': 'cisco',
'secret': 'cisco',
'timeout': 10000,
'session_timeout': 10000}
try:
c = Netmiko(**switch)
c.enable()
show_ip_arp = c.send_command('show ip arp', use_textfsm=True)
print(json.dumps(show_ip_arp))
except Exception as e:
print(e)
I was hoping anyone points to what might be wrong or missing. I would love to avoid having to set up any environment variables via cmd unless it can be automated as well. The idea is whoever opens this py file gets all that's needed to use textfsm.
Issue resolved with the help of the netmiko repository owner:
The code below works with the following libs and version:
netmiko==3.1.0
ntc-templates==1.4.0
textfsm==1.1.0
import os, json
import ntc_templates
from netmiko import Netmiko
from netmiko import NetMikoAuthenticationException
switch = {'device_type': 'cisco_ios',
'ip': '192.168.0.20',
'username': 'cisco',
'password': 'cisco',
'secret': 'cisco',
'timeout': 10000,
'session_timeout': 10000}
try:
c = Netmiko(**switch)
c.enable()
show_ip_arp = c.send_command('show ip arp', use_textfsm=True)
print(show_ip_arp)
except Exception as e:
print(e)
Related
I'm using a server for the first time. It has Ubuntu 18.04.
I've never worked with that OS, but after some guides I managed to get my code working, except for the environment variable.
In ~/.bashrc at the end of file I added export KEY="123asd".
Then I reloaded the terminal.
I checked if my environment variable is loaded via printenv KEY and it shows the correct value.
In my main.py there's:
import os
import telebot
API_KEY = os.getenv("KEY")
bot = telebot.TeleBot(API_KEY)
When I run it with pm2 start main.py --interpreter=python3 there's an error in logs:
raise Exception('Bot token is not defined')
Exception: Bot token is not defined
If I understand correctly it means that API_KEY is None so there's a problem with the environment variable.
I tried giving API_KEY an actual value, not an environment variable, and it worked fine.
So what else do I need to do to use an environment variable properly?
I was looking in the wrong place.
If I want to use pm2 then I need to create a ecosystem.config.js file and give it my variable. Like this:
module.exports = {
apps : [{
name: "main.py",
env: {
KEY: "123asd"
}
}]
}
It works, only I'm not sure if it's correct since there are more than 1 processes of my main.py (1 online, others are erorred)
I'm trying to import a custom module that I created, but it breaks my API just to import it.
data directory:
-src
--order
----__init__.py
----app.py
----validator.py
----requirments.txt
--__init__.py
on my app.py I have this code:
import json
from .validator import validate
def handler(event, context):
msg = ''
if event['httpMethod'] == 'GET':
msg = "GET"
elif event['httpMethod'] == 'POST':
pass #msg = validate(json.loads(event['body']))
return {
"statusCode": 200,
"body": json.dumps({
"message": msg,
}),
}
I get this error:
Unable to import module 'app': attempted relative import with no known parent package
However, if I remove line 2 (from .validator import validate) from my code, it works fine, so the problem is with that import, and honestly, I can't figure what is going on. I have tried to import using:
from src.order.validator import validate
but it doesn't work either.
was able to solve my issue by generating a build through the command: sam build, and zipping my file, and putting it on the root folder inside aws-sam, it's not a great solution because I have to rebuild at every small change, but at least it's a workaround for now
It seems app.py has not been loaded as part of the package hierarchy (i.e. src and order packages have not been loaded). You should be able to run
from src.order import app
from the parent directory of src and your code will work. If you run python app.py from the terminal — which I assume is what you did — app.py will be run as a standalone script — not as part of a package.
However, I do not believe you need the .validator in your case since both modules are in the same directory. You should be able to do
from validator import validate
I'm trying to map a remote path on Windows 10 for serveral hours but i don't get it to work. At first i tried it with WNetAddConnection2 but no matter what credentials or flags i use, when I type net use the mapped drive has always the status not available.
Manually i can map drives without problems, I only have problems when i map the drive programmatically.
import win32wnet
import win32netcon
nr = win32wnet.NETRESOURCE()
nr.dwScope = win32netcon.RESOURCE_GLOBALNET
nr.dwType = win32netcon.RESOURCETYPE_DISK
nr.dwUsage = win32netcon.RESOURCEUSAGE_CONNECTABLE
nr.lpLocalName = 'Z:'
nr.lpRemoteName = '\\\\192.168.178.46\\Test'
win32wnet.WNetAddConnection2(nr, None, None, 25)
The 25 is a flag set of interactive and prompt. I don't get any errors and the drive is listed when i type net use, but the status is always not available and the drive is not visible under workstation.
After that I tried NetUseAdd:
import win32net
win32net.NetUseAdd(None, 3, {'remote': r'\\192.168.178.46\Test',
'local': 'Z:', 'username': 'Admin', 'password': '123',
'status': 0, 'flags': 1, 'asg_type': 0})
It runs successfully but net use doesn't list anything and no mapped drives are visible under workstation.
A solution without subprocess would be nice. Can someone help please?
EDIT: Now i understand why it doesn't work. The app is running in admin context and I'm current logged in as non-admin. This behaviour is expalined here: https://superuser.com/questions/495370/why-isnt-a-mapped-drive-available-under-an-elevated-cmd-prompt-but-is-under-a-r
Is it possible to run the app as admin but the WNetAddConnection2 method as current user??
EDIT 2: Following the instructions from eryksun i came up with this:
import ctypes
from win32security import TOKEN_IMPERSONATE, TOKEN_ALL_ACCESS
from win32process import GetWindowThreadProcessId
from win32api import OpenProcess
from win32security import OpenProcessToken
from win32security import ImpersonateLoggedOnUser
from win32security import RevertToSelf
user32 = ctypes.WinDLL('user32', use_last_error=True);
user32.GetShellWindow.restype = ctypes.c_void_p
handle = user32.GetShellWindow()
threadId, processId = GetWindowThreadProcessId(handle)
handle_op = OpenProcess(TOKEN_ALL_ACCESS, True, processId)
handle_opt = OpenProcessToken(handle_op, TOKEN_IMPERSONATE)
ImpersonateLoggedOnUser(handle_opt) # throws access denied error
SOLUTION:
import ctypes
from win32process import GetWindowThreadProcessId
from win32api import OpenProcess
from win32security import OpenProcessToken, ImpersonateLoggedOnUser, RevertToSelf, TOKEN_QUERY, TOKEN_DUPLICATE
from win32con import PROCESS_QUERY_INFORMATION
user32 = ctypes.WinDLL('user32', use_last_error=True);
user32.GetShellWindow.restype = ctypes.c_void_p
handle = user32.GetShellWindow()
threadId, processId = GetWindowThreadProcessId(handle)
handle_op = OpenProcess(PROCESS_QUERY_INFORMATION, False, processId)
handle_opt = OpenProcessToken(handle_op, TOKEN_QUERY | TOKEN_DUPLICATE)
ImpersonateLoggedOnUser(handle_opt)
try:
nr = win32wnet.NETRESOURCE()
nr.dwScope = win32netcon.RESOURCE_GLOBALNET
nr.dwType = DISK
nr.dwUsage = win32netcon.RESOURCEUSAGE_CONNECTABLE
nr.lpLocalName = 'Z:'
nr.lpRemoteName = '\\\\192.168.178.46\\Test'
win32wnet.WNetAddConnection3(None, nr, None, None, 25)
except:
print("Unexpected error...")
RevertToSelf()
win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, drive,
networkPath, None, user, password)
Drive is the local drive you want to map the network drive to, e.g. X:\
For networkpath add \\ in the beginning of the path, e.g. \\\\networkpath02 if you can access the path with \\networkpath02 in explorer.
I know there are many posts about this problem (i've read them all).
But i still have a problem with my exe, still cannot be opened.
I've tried to put the qwindows.dll (i tried with 3 different qwindows.dll) in the folder dist with my exe but doesn't change anyhting.
I've tried with libEGL.dll, nothing.
Any suggestions ? Is there a way to avoid having this problem ?
I've had this issue aswell, after a lot of digging I found the following solution:
Copy the following file next to you main .exe:
libEGL.dll
Copy the following file in a folder "platforms" next to you main .exe:
qwindows.dll
Putting the qwindows.dll in the subfolder is the important part I think, hope this helps
Try:
from setuptools import setup
import platform
from glob import glob
from main import __version__, __appname__, __author__, __author_email__
SETUP_DICT = {
'name': __appname__,
'version': __version__,
'description': 'description',
'author': __author__,
'author_email': __author_email__,
'data_files': (
('', glob(r'C:\Windows\SYSTEM32\msvcp100.dll')),
('', glob(r'C:\Windows\SYSTEM32\msvcr100.dll')),
('platforms', glob(r'C:\Python34\Lib\site-packages\PyQt5\plugins\platforms\qwindows.dll')),
('images', ['images\logo.png']),
('images', ['images\shannon.png']),
),
'options': {
'py2exe': {
'bundle_files': 1,
'includes': ['sip', 'PyQt5.QtCore'],
},
}
}
if platform.system() == 'Windows':
import py2exe
SETUP_DICT['windows'] = [{
'script': 'main.py',
'icon_resources': [(0, r'images\logo.ico')]
}]
SETUP_DICT['zipfile'] = None
setup(**SETUP_DICT)
copy the dependency manually is a bad way to do, because py2exe take care of it. With pyqt5, this setup works, BUT if I try in other computer without pyqt install the exe crashes. I migrated to pyqt4 and run in all computers.
For me it was enough to copy qwindows.dll to platforms folder, like #Inktvisje wrote.
And don't repeat my mistake: don't download this dll from Internet! Copy it from your Python libs folder: YourPythonFolder\Lib\site-packages\PyQt5\plugins\platforms.
I often find myself recreating file structures for Flask apps so I have decided to make a script to do all that for me. I would like the script to create all the folders I need as well as the files with some basic boilerplate, which it does, that part is working fine. However I would also like to create a virtual environment and install Flask to that environment. That is where I am encountering the problem. The script runs but it installs Flask to my system installation of Python.
I followed the advice in this question here but it's not working. I am running Ubuntu 12.04.4 LTS via crouton on a Chromebook.
#!/usr/bin/python
from os import mkdir, chdir, getcwd, system
import sys
APP_NAME = sys.argv[1]
ROOT = getcwd()
PROJECT_ROOT = ROOT + '/' + APP_NAME
# dictionary represents folder structure. Key is the folder name and the value is it's contents
folders = {APP_NAME : {'app' : {'static': {'css' : '', 'img' : '', 'js' : ''}, 'templates' : ''} } }
def create_folders(dic):
for key in dic:
if isinstance(dic[key], dict):
mkdir(key)
prev = getcwd() + '/' + key
chdir(prev)
create_folders(dic[key])
else:
mkdir(key)
create_folders(folders)
chdir(PROJECT_ROOT)
open('config.py', 'a').close()
with open('run.py', 'a') as run:
run.write("""stuff""")
with open('app/__init__.py', 'a') as init:
init.write("""stuff""")
with open('app/views.py', 'a') as views:
views.write("""stuff""")
open('app/models.py', 'a').close()
open('app/forms.py', 'a').close()
with open('app/templates/layout.html', 'a') as layout:
layout.write("""stuff""")
system('chmod a+x run.py')
system('virtualenv venv')
system('. venv/bin/activate;sudo pip install flask') # this does not seem to be working the way I am expecting it to
I suppose your calls are not within the same console session and therefore the console environment is not as expected. I suggest to concatenate the related commands in one system call using subprocess.Popen like this (including suggestions by limasxgoesto0):
subprocess.Popen('virtualenv venv;source venv/bin/activate;pip install flask')
You should probably be using subprocess; os.system is deprecated.