I'm trying to use textFSM to compile some Juniper "show" command outputs and get specific fields from them and finally printing collected info in one run.
This is my code:
import textfsm
import getpass
from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException
import os
def enable_netconf(remote_device):
junos_device = ConnectHandler(**remote_device)
command_2 = junos_device.send_command("show interfaces")
junos_device.disconnect()
def main():
print("Enter Device info to check:\n")
tuser = input("Enter username: ")
tpw = getpass.getpass()
with open("D:\Documents\sample3.csv", encoding='utf-8') as tf:
for line in tf:
my_ip = line.rstrip(os.linesep)
remote_device = {
'device_type': 'juniper',
'ip': my_ip,
'username': tuser,
'password': tpw,
}
enable_netconf(remote_device)
with open("D:\Documents\juniper_junos_show_interfaces.textsm", "r") as f:
template = textfsm.TextFSM(f)
result = template.ParseText(command_2)
print(result)
if __name__ == '__main__':
main()
I used Netmiko to connect to Juniper vMX device. I also download textFSM "show interfaces" temple from this link (https://github.com/networktocode/ntc-templates/blob/master/ntc_templates/templates/juniper_junos_show_interfaces.textfsm) and saved them in D:\Documents folder.
first of All I need to make the basic function of textFSM to work. in the above code I got the error saying that "command_2" variable has not been defined which as seen I defined it inside the "def enable_netconf(remote_device)".
Would you please help me on this as I'm a newbie in Python.
Thanks.
If you want to use a variable in a different def, you can use the global command. In this example, just put "global comman_2" just below def enable_netconf(remote_device):
def enable_netconf(remote_device):
global command_2
junos_device = ConnectHandler(**remote_device)
command_2 = junos_device.send_command("show interfaces")
junos_device.disconnect()
Related
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 wrote simple script in python
#!/usr/bin/python
from uuid import getnode as get_mac
import socket
import requests
import datetime
#import tkMessageBox as messagebox
#import Tkinter as tk
def main():
print('start')
i = datetime.datetime.now()
headers = {"Content-Type": "text/html; charset=UTF-8"}
r = requests.post("http://michulabs.pl", data={'name' : 'CI17nH', 'ip' : getIp(), 'mac' : getMac(), 'source' : 'so', 'join_date' : i})
print(r.status_code, r.reason)
print(r.text) # TEXT/HTML
print(r.status_code, r.reason) # HTTP
"""
method to read ip from computer
it will be saved in database
"""
def getIp():
ip = socket.gethostbyname(socket.gethostname())
print 'ip: ' + str(ip)
return ip
"""
method to read mac from computer
it will be saved in database
"""
def getMac():
mac = get_mac()
print 'mac: ' + str(mac)
return mac
if __name__ == "__main__":
main()
Then by py2exe generated .exe file and tried to use RTLO character in filename which made script called moc.pdf instead of pdf.com. Actually it works good with pdf.com but it doesn't after using RTLO character. Did Windows blocked that trick in filenames, or am I doing something wrong?
PS Windows didn't block that trick because it does work with other file.
I am trying to write a Volatility plugin to extract configuration file used by a malware from memory dump. However, when I run this plugin (without 'sudo') without root privileges the plugin crashes at the line yara.compile. If I run this plugin with 'sudo', code after yara.compile line is not getting executed. I am not sure why yara.compile is causing this problem. Could someone help me with this? Following is the code I have written:
import volatility.plugins.common as common
import volatility.utils as utils
import volatility.win32.tasks as tasks
import volatility.debug as debug
import volatility.plugins.malware.malfind as malfind
import volatility.conf as conf
import volatility.plugins.taskmods as taskmods
try:
import yara
HAS_YARA = True
except ImportError:
HAS_YARA = False
YARA_SIGS = {
'malware_conf' : 'rule malware_conf {strings: $a = /<settings/ condition: $a}'
}
class malwarescan(taskmods.PSList):
def get_vad_base(self, task, address):
for vad in task.VadRoot.traverse():
if address >= vad.Start and address < vad.End:
return vad.Start
return None
def calculate(self):
if not HAS_YARA:
debug.error('Yara must be installed for this plugin')
print "in calculate function"
kernel_space = utils.load_as(self._config)
print "before yara compile"
rules = yara.compile(sources=YARA_SIGS)
print "after yara compile"
for process in tasks.pslist(kernel_space):
if "IEXPLORE.EXE".lower() == process.ImageFileName.lower():
scanner = malfind.VadYaraScanner(task=process, rules=rules)
for hit, address in scanner.scan():
vad_base_addr = self.get_vad_base(process, address)
yield process, address
def render_text(self, outfd, data):
for process, address in data:
outfd.write("Process: {0}, Pid: {1}\n".format(process.ImageFileName, process.UniqueProcessId))
So when I run this plugin with root privilege, I dont see the line "print 'after yara compile'" gets executed. What could be the reason? Thank you.
I installed "yara" through "pip". If you install yara through pip, you actually get yara-ctypes (https://github.com/mjdorma/yara-ctypes) which is a bit different than yara-python. So I uninstalled yara-ctypes and installed yara-python. Then it worked.
This question already exists:
How can I display environment variable [duplicate]
Closed 8 years ago.
I code in python and I have a problem.
I have file1.py :
import os, sys, platform, getpass, tempfile
import webbrowser
import string
import json
import cgi, cgitb
def main( addr, name):
os.environ["REMOTE_ADDR"] = addr
print os.environ ["REMOTE_ADDR"]
template = open('file2.py').read()
tmpl = string.Template(template).substitute(
name = name,
addr = cgi.escape(os.environ["REMOTE_ADDR"]),
os = user_os,
user_name = user_login,
)
f = tempfile.NamedTemporaryFile(prefix='/tmp/info.html', mode='w', delete=False)
f.write(contenu)
f.close()
webbrowser.open(f.name)
if __name__ == "__main__":
addr = sys.argv[1]
name = sys.argv[2]
user_os = sys.platform
sys.argv.append(user_os)
user_login = getpass.getuser()
sys.argv.append(user_login)
main(addr, name)
in the file2.py
<form name="sD" method="get" action="${addr}">
but I have this error and I have tried to resolve it, but I don't know how can do that :(
Traceback (most recent call last):
File "./file1.py", line 47, in <module>
main(addr, name)
File "./file1.py", line 22, in main
addr = cgi.escape(os.environ["REMOTE_ADDR"])
File "/usr/lib/python2.6/UserDict.py", line 22, in __getitem__
raise KeyError(key)
KeyError: 'REMOTE_ADDR'
My problem is, I don't know how can I put a addr variable in command line and recover that IP address in an URL when I click on the OK button
Help me please :(
You have multiple problems with your code.
First, as mentioned in your previous question:
you dont (I repeat: you dont) want the IP of the client as the url for
your form's action
What, exactly, do you think this line of code is going to do?
<form name="sD" method="get" action="${addr}">
It will attempt to send the form to your end user's IP address. This will fail. This will fail because
They likely don't have a web server running
Even if they do, they likely don't have a script built to handle your form
You should be submitting the form to a page you control so that you can process it
As for your missing key error, you don't have an environment variable set. You can do this a few ways:
From outside of your python script, use this command: set REMOTE_ADDR=<value>. Replace <value> with an appropriate value.
From within your python script, use this code
Remember to import os
import os
os.environ["REMOTE_ADDR"] = "value"
Again, value should be an appropriate value.
A very simple example of what you want:
import os, sys
def main( addr, name):
os.environ["REMOTE_ADDR"] = addr
print os.environ["REMOTE_ADDR"]
if __name__ == "__main__":
addr = sys.argv[1]
name = sys.argv[2]
main(addr, name)
This outputs:
>python test.py "address" "name"
address
>python test.py "http://www.google.com" "name"
http://www.google.com
Finally, as mentioned in your previous question:
you dont (I repeat: you dont) want the IP of the client as the url for
your form's action
From your shell (i.e. command line)
$> set REMOTE_ADDR=<some url>
$> python
>>> import os
>>> print os.environ['REMOTE_ADDR']
<some url>
if you define it in the python instance it is only available to that instance
but by putting in the 'environment' before calling any module it is 'globally' available
File "G:\Python25\Lib\site-packages\PyAMF-0.6b2-py2.5-win32.egg\pyamf\util\__init__.py", line 15, in <module>
ImportError: cannot import name python
How do I fix it?
If you need any info to know how to fix this problem, I can explain, just ask.
Thanks
Code:
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import webapp
from TottysGateway import TottysGateway
import logging
def main():
services_root = 'services'
#services = ['users.login']
#gateway = TottysGateway(services, services_root, logger=logging, debug=True)
#app = webapp.WSGIApplication([('/', gateway)], debug=True)
#run_wsgi_app(app)
if __name__ == "__main__":
main()
Code:
from pyamf.remoting.gateway.google import WebAppGateway
import logging
class TottysGateway(WebAppGateway):
def __init__(self, services_available, root_path, not_found_service, logger, debug):
# override the contructor and then call the super
self.services_available = services_available
self.root_path = root_path
self.not_found_service = not_found_service
WebAppGateway.__init__(self, {}, logger=logging, debug=True)
def getServiceRequest(self, request, target):
# override the original getServiceRequest method
try:
# try looking for the service in the services list
return WebAppGateway.getServiceRequest(self, request, target)
except:
pass
try:
# don't know what it does but is an error for now
service_func = self.router(target)
except:
if(target in self.services_available):
# only if is an available service import it's module
# so it doesn't access services that should be hidden
try:
module_path = self.root_path + '.' + target
paths = target.rsplit('.')
func_name = paths[len(paths) - 1]
import_as = '_'.join(paths) + '_' + func_name
import_string = "from "+module_path+" import "+func_name+' as service_func'
exec import_string
except:
service_func = False
if(not service_func):
# if is not found load the default not found service
module_path = self.rootPath + '.' + self.not_found_service
import_string = "from "+module_path+" import "+func_name+' as service_func'
# add the service loaded above
assign_string = "self.addService(service_func, target)"
exec assign_string
return WebAppGateway.getServiceRequest(self, request, target)
You need to post your full traceback. What you show here isn't all that useful. I ended up digging up line 15 of pyamf/util/init.py. The code you should have posted is
from pyamf import python
This should not fail unless your local environment is messed up.
Can you 'import pyamf.util' and 'import pyamf.python' in a interactive Python shell? What about if you start Python while in /tmp (on the assumption that you might have a file named 'pyamf.py' in the current directory. Which is a bad thing.)
= (older comment below) =
Fix your question. I can't even tell where line 15 of util/__init__.py is supposed to be. Since I can't figure that out, I can't answer your question. Instead, I'll point out ways to improve your question and code.
First, use the markup language correctly, so that all the code is in a code block. Make sure you've titled the code, so we know it's from util/__init__.py and not some random file.
In your error message, include the full traceback, and not the last two lines.
Stop using parens in things like "if(not service_func):" and use a space instead, so its " if not service_func:". This is discussed in PEP 8.
Read the Python documentation and learn how to use the language. Something like "func_name = paths[len(paths) - 1]" should be "func_name = paths[-1]"
Learn about the import function and don't use "exec" for this case. Nor do you need the "exec assign_string" -- just do the "self.addService(service_func, target)"