How to execute a powershell script within C++? - c++

The point of the whole program:
Pass in a username and password to elevate a user's privileges so that if they are not a user that is allowed to access a protected folder they can still open and view it. The username is mapped in a <map> which contains a key to their folder, it searches for their folder then passes it along with the username and password to do the real elevation in the following powershell script:
param(
    [string]$username,
    [string]$password,
    [string]$folder
    )
    Write-Host $username $password $folder
 
    $securePassword = ConvertTo-SecureString $password -AsPlainText -Force
    $credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
    Start-Process T:\folders\Explorer++\Explorer++.exe \\foo\boo\fileserver\allusers\specialUsers\$folder -Credential $credential
I am passing in the username, password, and folder into this script through the use of System().
The c++ code to execute the script and pass in variables looks like this:
String^ runCommand(string folder, string username, string password)
{
string explorerpp = "\\\\foo\\boo\\examplefolder\\Explorer++\\EXPLORER++.exe";
string space = " ";
string quote = "\"";
string start = "C:\\ProgramData\\Microsoft\Windows\\Start Menu\\Programs\\System Tools\\Windows Powershell";
string open = "open";
string domain = "domain\\";
string pwShell = "S:\\foo\\boo\\locationofscript\\pwShell.ps1 ";
string parentFolder = """\\\\foo\\boo\\folder\\Parent_folder\\special_users \\""";
string path = parentFolder + folder;
String^ dir = gcnew String(path.c_str());
string param = quote + domain+ username + quote + space + quote + password + quote + space + quote + folder + quote;
string command = "start powershell.exe" + space + pwShell + param;
system(command.c_str());
return dir;
}
Note: The code looks the way it does due to a massive amount of debugging, I understand that I am probably using a lot of un needed variables.
When ran through System() or _popen it either opens up a .txt containing a script or errors out on the command prompt.
If I were take what the value of string command is and paste it into a command prompt I would get the script running correctly and then opening the correct folder.
What is the issue with C++ that is not allowing the script to execute properly when the command prompt is executing everything correctly?
BIG EDIT:
The error I am getting is C:\OurProj\pwShell.ps1 : File C:\OurProj\pwshell.ps1 cannot be loaded because running scripts is disabled on this system.
I did just talk to the IT guys, and I am able to run scripts on this system, tried to make everything local, and if I run the script through powershell it works.
EDIT 2:
I have changed the Execution Policy as has been suggested, and it does return RemoteSigned, however when the code executes in C++ I am still told that I have scripts disabled.

In one environment you can execute unsigned power shell scripts, but in another one you can't. 64-bit and 32-bit each have a separate execution policy for power shell. Most likely you're running on a 64-bit operating system and building a 32-bit C++ program (default for visual studio).
You can get to a 32-bit power shell by doing the following:
On the Start screen, type Windows PowerShell (x86). Run this as administrator.
Next run the command:
Set-ExecutionPolicy RemoteSigned
Now you should be able to run unsigned local power script files from a 32 bit environment on your computer.
From the start menu you can get to either PowerShell environment, be sure the same execution policy is set for both using the command:
Get-ExecutionPolicy

Related

Byte of Python backup program is not working on Windows System

byte of python backup program is not working
The error I'm getting is zip command is not a recognized command on windows command prompt even after installing zip utility tool and setting the environment variables
This is the code:
import os
import time
source = ['"F:\PYTHON\byte of python code"']
target_dir = 'F:\\Backup'
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
if not os.path.exists(target_dir):
os.mkdir(target_dir) # make directory
zip_command = "zip -r {0} ".format(target,' '.join(source))
print "Zip command is:"
print zip_command
print "Running:"
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'
raw_input("Press<Enter>")
The error I'm getting is
Zip command is:
zip -r F:\Backup\20170220120316.zip
Running:
'zip' is not recognized as an internal or external command,
operable program or batch file.
Backup FAILED
Press<Enter>
Any help would be greatly appreciated. Thank you

GitPython: How can I access the contents of a file in a commit in GitPython

I am new to GitPython and I am trying to get the content of a file within a commit. I am able to get each file from a specific commit, but I am getting an error each time I run the command. Now, I know that the file exist in GitPython, but each time I run my program, I am getting the following error:
returned non-zero exit status 1
I am using Python 2.7.6 and Ubuntu Linux 14.04.
I know that the file exist, since I also go directly into Git from the command line, check out the respective commit, search for the file, and find it. I also run the cat command on it, and the file contents are displayed. Many times when the error shows up, it says that the file in question does not exist. I am trying to go through each commit with GitPython, get every blob or file from each individual commit, and run an external Java program on the content of that file. The Java program is designed to return a string to Python. To capture the string returned from my Java code, I am also using subprocess.check_output. Any help will be greatly appreciated.
I tried passing in the command as a list:
cmd = ['java', '-classpath', '/home/rahkeemg/workspace/CSCI499_Java/bin/:/usr/local/lib/*:', 'java_gram.mainJava','absolute/path/to/file']
subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=False)
And I have also tried passing the command as a string:
subprocess.check_output('java -classpath /home/rahkeemg/workspace/CSCI499_Java/bin/:/usr/local/lib/*: java_gram.mainJava {file}'.format(file=entry.abspath.strip()), shell=True)
Is it possible to access the contents of a file from GitPython?
For example, say there is a commit and it has one file foo.java
In that file is the following lines of code:
foo.java
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class foo{
public static void main(String[] args) throws Exception{}
}
I want to access everything in the file and run an external program on it.
Any help would be greatly appreciated. Below is a piece of the code I am using to do so
#! usr/bin/env python
__author__ = 'rahkeemg'
from git import *
import git, json, subprocess, re
git_dir = '/home/rahkeemg/Documents/GitRepositories/WhereHows'
# make an instance of the repository from specified path
repo = Repo(path=git_dir)
heads = repo.heads # obtain the different repositories
master = heads.master # get the master repository
print master
# get all of the commits on the master branch
commits = list(repo.iter_commits(master))
cmd = ['java', '-classpath', '/home/rahkeemg/workspace/CSCI499_Java/bin/:/usr/local/lib/*:', 'java_gram.mainJava']
# start at the very 1st commit, or start at commit 0
for i in range(len(commits) - 1, 0, -1):
commit = commits[i]
commit_num = len(commits) - 1 - i
print commit_num, ": ", commit.hexsha, '\n', commit.message, '\n'
for entry in commit.tree.traverse():
if re.search(r'\.java', entry.path):
current_file = str(entry.abspath.strip())
# add the current file or blob to the list for the command to run
cmd.append(current_file)
print entry.abspath
try:
# This is the scenario where I pass arguments into command as a string
print subprocess.check_output('java -classpath /home/rahkeemg/workspace/CSCI499_Java/bin/:/usr/local/lib/*: java_gram.mainJava {file}'.format(file=entry.abspath.strip()), shell=True)
# scenario where I pass arguments into command as a list
j_response = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=False)
except subprocess.CalledProcessError as e:
print "Error on file: ", current_file
# Use pop on list to remove the last string, which is the selected file at the moment, to make place for the next file.
cmd.pop()
First of all, when you traverse the commit history like this, the file will not be checked out. All you get is the filename, maybe leading to the file or maybe not, but certainly it will not lead to the file from different revision than currently checked-out.
However, there is a solution to this. Remember that in principle, anything you could do with some git command, you can do with GitPython.
To get file contents from specific revision, you can do the following, which I've taken from that page:
git show <treeish>:<file>
therefore, in GitPython:
file_contents = repo.git.show('{}:{}'.format(commit.hexsha, entry.path))
However, that still wouldn't make the file appear on disk. If you need some real path for the file, you can use tempfile:
f = tempfile.NamedTemporaryFile(delete=False)
f.write(file_contents)
f.close()
# at this point file with name f.name contains contents of
# the file from path entry.path at revision commit.hexsha
# your program launch goes here, use f.name as filename to be read
os.unlink(f.name) # delete the temp file

If EXE opens, then RUN

I need a script that. If exe opens, then URL will open. And I did make a shortcut for the URL.
I found this script, on stack overflow, and was going to use it changing the arguments of course, but I figured there would be a simpler way
EDIT: If League of Legends.exe opens [This is the client itself], then run C:..\KSD.url
Option Explicit
Private Const Folder As String = "c:\windows\system32\foldername"
Private Const FileToRun As String = "\\servername\folder\software.exe"
Sub Run(ByVal sFile)
Dim shell
Set shell = CreateObject("WScript.Shell")
shell.Run Chr(34) & sFile & Chr(34), 1, False
Set shell = Nothing
End Sub
Dim fs
Set fs = CreateObject("Scripting.FileSystemObject")
If Not fs.FolderExists(Folder) Then
Run FileToRun
End If
Try Exec : http://msdn.microsoft.com/en-us/library/ateytk4a(v=vs.84).aspx
objExec = shell.Exec Chr(34) & sFile & Chr(34)
if objExec.Status = 0 then ' your program is running
' open your url
end if
You may need error handling if your file does not open (see MSDN documenation above). Please code responsibly :-)

SSH into switch using paramiko module

I am able to open a ssh session into switch using paramiko. Able to enter the commands and gets it respective output.
My question is that I want to enter many command into the switch simultaneously. But before entering new command, wanted to know that previous command is successfully entered into the switch.For example
switch>enable
switch#
switch#config t
switch(config)
Enter the 2nd command, until i see # sign and 3rd command untill i see config.
Following is the code i am using
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('ip-address',username='username', password='password')
list =['enable','config t']
command = '\n'.join(list)
#for i in range(len(list)):
print command
stdin,stdout,stderr = ssh.exec_command(command)
print(stdout.read())
use interactive invoke shell
##invoke interactive shell chan = ssh.invoke_shell(); chan.send(command + '\n') ;
while not chan.recv_ready(): print 'waiting for challenge' time.sleep(1) ;
resp = chan.recv(1024) ; print resp

Boost-Python: Load python module with unicode chars in path

I'm working on game project. I use python 2.7.2 for scripting. My application works fine with non unicode path to .exe. But it can't load scripts with unicode path using
boost::python::import (import_path.c_str());
I tried this example
5.3. Pure Embedding http://docs.python.org/extending/embedding.html#embedding-python-in-c
It also can't handle unicode path. I linked python as dll.
Explain me, please, how to handle such path.
boost::python::import needs a std::string, so chances are that import_path misses some characters.
Do you have to work on multiple platform ? On Windows, you could call GetShortPathName to retreive the 8.3 filename and use that to load your dll.
You can make a quick test :
Rename your extension to "JaiDéjàTestéÇaEtJaiDétestéÇa.pyd".
At the command line, type dir /x *.pyd to get the short file name (JAIDJT~1.PYD on my computer)
Use the short name to load your extension.
+The file name above if French for "I already tested this and I didn't like it". It is a rhyme that takes the edge off working with Unicode ;)
This isn't really an answer that will suit your needs, but maybe it will give you something to go on.
I ran into a very similar problem with Python, in my case my application is a pure Python application. I noticed as well that if my application was installed to a directory with a path string that could not be encoded in MBCS (what Python converts to internally for imports, at least Python prior to 3.2 as far as I understand), the Python interpreter would fail, claiming not module of that name existed.
What I had to do was write an Import Hook to trick it into loading those files anyway.
Here's what I came up with:
import imp, os, sys
class UnicodeImporter(object):
def find_module(self,fullname,path=None):
if isinstance(fullname,unicode):
fullname = fullname.replace(u'.',u'\\')
exts = (u'.pyc',u'.pyo',u'.py')
else:
fullname = fullname.replace('.','\\')
exts = ('.pyc','.pyo','.py')
if os.path.exists(fullname) and os.path.isdir(fullname):
return self
for ext in exts:
if os.path.exists(fullname+ext):
return self
def load_module(self,fullname):
if fullname in sys.modules:
return sys.modules[fullname]
else:
sys.modules[fullname] = imp.new_module(fullname)
if isinstance(fullname,unicode):
filename = fullname.replace(u'.',u'\\')
ext = u'.py'
initfile = u'__init__'
else:
filename = fullname.replace('.','\\')
ext = '.py'
initfile = '__init__'
if os.path.exists(filename+ext):
try:
with open(filename+ext,'U') as fp:
mod = imp.load_source(fullname,filename+ext,fp)
sys.modules[fullname] = mod
mod.__loader__ = self
return mod
except:
print 'fail', filename+ext
raise
mod = sys.modules[fullname]
mod.__loader__ = self
mod.__file__ = os.path.join(os.getcwd(),filename)
mod.__path__ = [filename]
#init file
initfile = os.path.join(filename,initfile+ext)
if os.path.exists(initfile):
with open(initfile,'U') as fp:
code = fp.read()
exec code in mod.__dict__
return mod
sys.meta_path = [UnicodeImporter()]
I still run into two issues when using this:
Double clicking on the launcher file (a .pyw file) in windows explorer does not work when the application is installed in a trouble directory. I believe this has to do with how Windows file associations passes the arguments to pythonw.exe (my guess is Windows passes the full path string, which includes the non-encodeable character, as the argument to the exe). If I create a batch file and have the batch file call the Python executable with just the file name of my launcher, and ensure it's launched from the same directory, it launches fine. Again, I'm betting this is because now I can use a relative path as the argument for python.exe, and avoid those trouble characters in the path.
Packaging my application using py2exe, the resulting exe will not run if placed in one of these trouble paths. I think this has to do with the zipimporter module, which unfortunately is a compiled Python module so I cannot easily modify it (I would have to recompile, etc etc).