Possible encoding issue between PS and C++ - c++

I have a C++ program written using Qt that I'm using as a front end to create AD accounts. Essentially I launch an elevated process that executes PowerShell commands within an elevated PowerShell session. I can create the accounts fine but when I attempt to pull membership from a pre-existing user to copy it over to the new one it fails. I need to understand why it's failing and resolve the issue, any help is greatly appreciated. It fails with the following error:
Get-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the
argument, and then try running the command again.
At line:2 char:28
+ "}); $groups = (Get-ADUser $tmpusr -Properties MemberOf).MemberOf; $u ...
+ ~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser
The $tmpusr variable is just the value of duser.template_user which is pulled from a QComboBox and is deffinetly not null because it outputs correctly and shows the selected template account. In C++ it's just data added to a struct member:
duser.set_groups_command = "$tmpusr = (Get-ADUser -Filter {Name -like " "\"" + duser.template_user + "\"" "}); "
"$groups = (Get-ADUser $tmpusr -Properties MemberOf).MemberOf; "
"$usr = " "\"" + duser.sam_name + "\"" + "; "
"Foreach ($group in $groups) {Add-ADGroupMember -Identity (Get-ADGroup $group).name -Members $usr} ";
If I strip the C++ and run the same command within PowerShell it executes fine:
$tmpusr = (Get-ADUser -Filter {Name -like "Example User"}); $groups = (Get-ADUser $tmpusr -Properties MemberOf).MemberOf; $usr = "TestUser"; Foreach ($group in $groups) {Add-ADGroupMember -Identity (Get-ADGroup $group).name -Members $usr}
The purpose of the command is to determine which groups "Example User" belongs to and then to add "TestUser" to the same groups. Again, creating the user works fine. That is done with:
duser.complete_command = p + "New-ADUser -Name " + "\"" + duser.employe_name +"\"" + " -GivenName " + "\"" + duser.given_name + "\""
+ " -Surname " + "\"" + duser.surname + "\"" + " -AccountPassword $sec " + " -UserPrincipalName " + "\"" + duser.userpname + "\""
" -DisplayName " + "\"" + duser.display_name + "\"" + " -EmailAddress " + "\"" + duser.email_address + "\"" + " -SamAccountName " +
"\"" + duser.sam_name + "\"" + " -Enabled " + duser.is_enabled;
You'll note the existence of "p" which is another QString created earlier on to convert to a secure string. The only other component is the function that elevates and executes:
void MainWindow::elevate_and_execute(QString param)
{
QProcess *process = new QProcess();
QStringList params = QStringList();
params = QStringList({"-Command", QString("Start-Process -Verb runAs powershell; "), param});
process->startDetached("powershell", params);
process->waitForFinished();
process->terminate();
}

I was able to resolve the issue. I found that when I pulled the so called template user from the QComboBox it contained a carriage return. I had written the logs to a text file and found it was pushing it to the next line; so the $tmpusr was broken. I was able to resolve the issue by modifying the duser.template_user variable when it's initially filled by stripping that "\r" out with remove(QChar('\r'))

Related

SQLite3 SQL DELETE syntax for two WHERE columns

This string works perfect for one column:
delSQL = "DELETE FROM user WHERE Name='" + datArray[0] + "';";
But what looks correct for two columns has error: expected β€˜;’ before β€˜AND’
delSQL = "DELETE FROM user WHERE Name='" + datArray[0] + "'" AND " Age=" + datArray[1] + ";";
Advice greatly appreciated.
Try this...
delSQL = "DELETE FROM user WHERE Name='" + datArray[0] + "' AND Age=" + datArray[1] + ";";

find snapshots whose volumes are deleted

I am trying to find out how many snapshots are there whose volumes are deleted. In this scenario there is a volume v-fffff whose snapshot is available but volume is deleted. I dont know how can I find it. Below is the code
volList=[{"VolumeId":"vol-sss","State":"in-use"},{"VolumeId":"vol-defghi","State":"available"},{"VolumeId":"vol-sfjfrf","State":"in-use"}]
snapList=[{"VolumeId":"vol-sss","snap-id":"sna-1356"},{"VolumeId":"vol-sss","snap-id":"sna-asd"},{"VolumeId":"vol-defghi","snap-id":"snap-1256"},{"VolumeId":"vol-defghi","snap-id":"snap-11"},{"VolumeId":"vol-sfjfrf","snap-id":"snap-456"},{"VolumeId":"v-fffff","snap-id":"snap-123"}]
for snap in snapList:
for vol in volList:
if snap['VolumeId'] == vol['VolumeId']:
print "match volume id :" + snap['VolumeId'] + " state " + vol['State'] + " snap-id : " + snap['snap-id']
else:
print "not match volume id :" + snap['VolumeId'] + " state not found" + " snap-id : " + snap['snap-id']
I found the solution. Indexing was the solution for such scenario
volList=[{"VolumeId":"vol-sss","State":"in-use"},{"VolumeId":"vol-defghi","State":"available"},{"VolumeId":"vol-sfjfrf","State":"in-use"}]
snapList=[{"VolumeId":"vol-sss","snap-id":"sna-1356"},{"VolumeId":"vol-sss","snap-id":"sna-asd"},{"VolumeId":"vol-defghi","snap-id":"snap-1256"},{"VolumeId":"vol-defghi","snap-id":"snap-11"},{"VolumeId":"vol-sfjfrf","snap-id":"snap-456"},{"VolumeId":"v-fffff","snap-id":"snap-123"}]
print len(snapList)
volIdList=[]
for ids in volList:
volIdList.append(ids['VolumeId'])
mainSnap=[]
for snap in snapList:
try:
if (volIdList.index(snap['VolumeId'])< 0):
print " not match volume id :" + snap['VolumeId']
else:
for v in volList:
if v['VolumeId']==snap['VolumeId']:
print "match volume id :" + snap['VolumeId'] + " " + v['State'] + " " + snap['snap-id']
except ValueError:
print " state not found " + snap['VolumeId'] + " " + snap['snap-id']

How to get Jenkins pending build id in python

views.py
here i can get the all information of build of jenkins job which is currently running. but when user runs or triggers same job again it will make queue on jenkins but as a pending build.
so i get the build id of currently running job and not of pending jenkins build. Actualy i want build id of pending build.
try:
print "in try.."
jenkinsStream = urllib2.urlopen( "http://10.211.213.138:8080/job/TE-mobius/lastBuild/api/json?pretty=true" )
print "after fetching url"
except urllib2.HTTPError, e:
print "URL Error: " + str(e.code)
print " (job name [" + jobName + "] probably wrong)"
try:
print "Before loading json"
buildStatusJson = json.load( jenkinsStream )
print "After loading json"
except:
print "Failed to parse json"
print "before while.."
print buildStatusJson["building"]
#print "[" + jobName + "] duration: " + str(buildStatusJson["duration"])
print buildStatusJson.has_key( "result" )
if buildStatusJson.has_key( "result" )==True:
print "in if"
print "[" + jobname + "] duration: " + str(buildStatusJson["duration"])
print "[" + jobname + "] building: " + str(buildStatusJson["building"])
print "[" + jobname + "] timestamp: " + str(buildStatusJson["timestamp"])
print "[" + jobname + "] url: " + str(buildStatusJson["url"])
print "[" + jobname + "] result: " + str(buildStatusJson["result"])
print "[" + jobname + "] build number: " + str(buildStatusJson["number"])
print "[" + jobname + "] JobName: " + str(buildStatusJson["fullDisplayName"])
There's an API endpoint at http://10.211.213.138:8080/job/TE-mobius/api/json?pretty=true that has a nextBuildNumber key.
It also has
"queueItem" : {
"blocked" : false,
"buildable" : true,
"id" : 119,
"inQueueSince" : 1401783373284,
"params" : "",
"stuck" : false,
"task" : {
"name" : "YourJobName",
"url" : "http://jenkins/job/YourJobName/"
},
"url" : "queue/item/119/",
"why" : "Waiting for next available executor",
"buildableStartMilliseconds" : 1401783373290,
"pending" : false
}
with some basic information about that pending build. Some of the build information you're trying to print in your code won't exist in Jenkins until the build has started.
Unfortunately, this will only let you get the build number of the next pending build. If you have a parameterised build and multiple builds in the queue for one job, I'm not aware of any way to get the build numbers of the other pending builds. You might have to write a plugin if you need to get those.

Accessing data required out of for loop in python and store the data at specific location

I am using a for loop for getting data from the user in command prompt using python 2.7. Then storing the data in a text file in certain format. I am looking for a method to get the data from the user and store it in a list and use it where required.
for Input_Number in range(Number_Of_Inputs):
Input_Number = Input_Number+1
GUI_Parameter = str(raw_input("Please enter input parameter " + str(Input_Number) + " :"))
GUI_Parameter_Name = str(raw_input("Enter the GUI name for the parameter " + str(Input_Number) + " :"))
Store_GUI_Parameter(Opened_File, GUI_Parameter, GUI_Parameter_Name)
I would like to use this data to store it in a specific location in a text file according to required syntax. The above code stores the data in the text file. But the problem is it doesn't store it at the required place.
def Store_GUI_Parameter(Opened_File, GUI_Parameter, GUI_Parameter_Name):
GUI_Description = "| " + '"'+ GUI_Parameter_Name + '"' + " |$" + GUI_Parameter.title() + " |"
Write_Data(Opened_File, GUI_Description)
print "GUI parameters written to NDF file"
return
The data storage is done using the above function...
I tried this, but unfortunately this also is not working
GUI_Parameter= []
GUI_Parameter_Name = []
for Input_Number in range(Number_Of_Inputs):
Input_Number = Input_Number+1
GUI_Parameter[Input_Number] = str(raw_input("Please enter input parameter " + str(Input_Number) + " :"))
GUI_Parameter_Name[Input_Number] = str(raw_input("Enter the GUI name for the parameter " + str(Input_Number) + " :"))
Using it outside the loop in the same function...
GUI_Description(Opened_File, GUI_Parameter_Name[Input_Number], GUI_Parameter[Input_Number])
The function implementation:
def GUI_Description(Opened_File, GUI_Parameter_Name[Input_Number], GUI_Parameter[Input_Number]):
Iteration = 0
while Iteration < Input_Number:
Iteration += 1
GUI_Description = "| " + '"'+ GUI_Parameter_Name[Input_Number] + '"' + " |$" + GUI_Parameter[Input_Number].title() + " |"
Write_Data(Opened_File, GUI_Description)
print "GUI parameters written to NDF file"
return
But it shows syntax error at the def GUI_Description
C:\Users\padmanab\Desktop>python CtoN.py File "CtoN.py", line 173
def GUI_Description(Opened_File, GUI_Parameter_Name[Input_Number], GUI_Parameter[Input_Number]):
^ SyntaxError: invalid syntax
The syntax error in the function GUI_Description is caused by your input arguments. 'GUI_Parameter_Name[Input_Number]' is not a valid input argument. Since your function requires both 'GUI_Parameter_Name' and 'Input_Number' they should be separate input arguments. The code snippet below would solve this syntax error:
def GUI_Description(Opened_File, Input_Number, GUI_Parameter_Name, GUI_Parameter):
...
The code below will give an 'index out of range' error since the lists 'GUI_Parameter' and 'GUI_Parameter_Name' have zero length.
GUI_Parameter= []
GUI_Parameter_Name = []
Number_Of_Inputs = 1
for Input_Number in range(Number_Of_Inputs):
Input_Number = Input_Number+1
GUI_Parameter[Input_Number] = str(raw_input("Please enter input parameter " + str(Input_Number) + " :"))
GUI_Parameter_Name[Input_Number] = str(raw_input("Enter the GUI name for the parameter " + str(Input_Number) + " :"))
If you want to add items to the arrays you should append them:
GUI_Parameter.append(raw_input())

Sublime Snippet Regex Replacement

I've recently been creating quite a few Sublime Text 3 plugins/snippets/etc. to automate repetitive tasks. The current one I am stuck on uses regex in a snippet to get my default skeleton for a new function.
Ideally, I would like the snippet would generate something similar to:
// Multiple Args (one arg would obviously look like (..." + "a: " + a + ")");)
function Foo(a, b, c)
{
Log.AppendFolder("Foo(" + "a: " + a + ", b: " + b + ", c: " + c + ")");
//body
Log.PopLogFolder();
}
// Zero Args
function Foo()
{
Log.AppendFolder("Foo()");
//body
Log.PopLogFolder();
}
So far, I can get it formatted with 1 argument or many arguments, not all possible combos (zero, one, many).
The outline is current this, I just need to figure out the second ${2} with regex:
<snippet>
<content><![CDATA[
function ${1:function_name}(${2:arguments})
{
Log.AppendFolder("$1(" + ${2/(?#stuck here)//} + ")");
${3://body}
Log.PopLogFolder();
}$0]]></content>
<tabTrigger>fun</tabTrigger>
<scope>source.js</scope>
<description>Function Template</description>
</snippet>
One Arg:
"$1(" + ${2/^([A-z0-9_-]*),?.*/"\1\: " + \1 + /}");"
Many Args (with 1 arg, this shows "a: " + a + a):
"$1(" + ${2/^([A-z0-9_-]*),?(.*)/"\1\: " + \1 + /}${2/([A-z0-9_-]*)(?:, *([A-z0-9_-]*))/"$2\: " + $2 + /g}");"
One method worked by had an extra + "" + in there, which I'd like to avoid:
${2/([A-z_0-9]+)((?:, ?)?)/"\1\: " + \1 + "\2" + /g}
I've tried a conditional look-ahead based on commas, but that gets messed up >1 arg, probably due to my lack of understanding of them:
${2/(?(?!,)^([A-z0-9_-]*)$|([A-z0-9_-]*), *)/"\1\: " + \1/g}
I could easily do this via a normal plugin (this is easy programmatically), but ideally this can remain a snippet/code-completion since I can just override the JS "fun" code-completion.
What am I missing to accomplish this (or is it simply the wrong avenue - if that's the case, I'd still like to know to learn more about regex)?
Finally figured this out, there is a conditional replacement option:
?n:then:else
So the final format looks like:
<snippet>
<content><![CDATA[
function ${1:function_name}(${2:args})
{
Log.AppendFolder("$1(${2/.+/" + /}${2/([A-z_0-9-]+) *(,)? */"$1\: " + $1 ?2: + "$2 " + :+ /g}${2/.+/"/})");
${3:// body...}
Log.PopLogFolder();
}$0]]></content>
<tabTrigger>fun</tabTrigger>
<scope>source.js</scope>
<description>Function</description>
</snippet>
Which will give the desired result:
function function_name()
{
Log.AppendFolder("function_name()");
// body...
Log.PopLogFolder();
}
function function_name(a)
{
Log.AppendFolder("function_name(" + "a: " + a + ")");
// body...
Log.PopLogFolder();
}
function function_name(a, b)
{
Log.AppendFolder("function_name(" + "a: " + a + ", " + "b: " + b + ")");
// body...
Log.PopLogFolder();
}