When popen performs status check on service that dosen't exist error no results returned - subprocess

I am attempting to use subprocess.Popen() to read a service status.
If I get an unrecognized service error the value, while printed to the screen, is not saved to out or err for later viewing.
If the service does exist, "is running" gets saved to the out value. I would like to accomplish the same results when the unrecognized error is encountered.
I have tried using subprocess.check_output but it is unrecognized.
If I use an existing service it works as desired.
My code:
p = subprocess.Popen(['service','PretendService','status'], stdout=subprocess.PIPE)
out,err = p.communicate()

You need to pipe stderr as well as stdout:
p = subprocess.Popen(['service','PretendService','status'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out,err = p.communicate()
# Now err will have your error message

Related

FindItems() does not work in first run but works in the second run

I am trying to fetch latest mail from my Outlook Exchange server mailbox using PowerShell. I have seen that the most common solution is to do a FindItems() method on the inbox object. However, I find that that running the code first time throws error stating
Exception calling "FindItems" with "1" argument(s): "The request failed.
When I run it once again, the script completes successfully returning the last mail from my mailbox. In order to make it more clear, I wrote a script to execute the FindItems() method to execute twice in a while loop as shown below:
# bind to the Inbox folder of the target mailbox
$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($ews,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
echo outsideWhile
$i = 0
while ($i -ne 2) {
echo insideWhileBefore
$inbox.FindItems(1)
echo insideWhileAfter
$i += 1
}
The first execution of $inbox.FindItems(1) fails but the second execution goes through fine returning the desired results.
The result output is as shown below
outsideWhile
insideWhileBefore
Exception calling "FindItems" with "1" argument(s): "The request failed. The remote server returned an error: (501)" ........
insideWhileAfter
insideWhileBefore
<MAIL CONTENTS>
insideWhileAfter
Please help me out in understanding why this happening so and how I can overcome it.

How to get AWStats Error Notification via email?

I'm trying to find a way for an email notification in awstats.
The idea is that whenever there's an error (missing log files, statistics couldn't be generated) an email with an error message should be send to a specific email address.
I already found the config-Attribute "ErrorMessages" but as far as i get it its just for displaying an error.
Is there an attribute like "ErrorMessages" for activating mail notifications or do i have to implement it myself?
You can use cron job to run awstats update proccess.
And it'll sent update process result via email to you.
Example:
* * * * * /usr/local/awstats/update.sh | mail abc#xzy.com
I found a way to trap Errors while my code is executed. It's not an awstats feature, more a generic way:
Inside my script:
#Error Handling
set -e
function sendErrorNotification(){
echo "Awstats: An error occured during processing server logs." | mail -s "AWSTATS ERROR" "...#..."
}
trap sendErrorNotification EXIT
....code goes here...
set +e
trap - EXIT

System command output leaking - perl

just starting to use Perl here. I previously have successfully used backticks to capture system command output in Perl, such as:
my #sysOut = `cleartool checkout -nc \"$file\"`; # works fine!
but I have run into some trouble, and even after looking around for some time I didn't find the solution to this problem. I am trying to write a Perl script to check in a list of checked out files (#allfiles) using cleartool, except if any are identical to their predecessor, then un-checkout them.
The way I am (...failing at!) detecting whether they are identical or not is to get the output from the check in attempt, see if it matches /error.*identical/i, and then if so uncheckout the file. However, for some reason the output seems to bypassing the array I am passing it into.
See code which generates this problem:
foreach my $file (#allfiles){
chomp( my #checkInErr = `cleartool checkin -nc \"$file\"`);
foreach my $err (#checkInErr) { # if no error, checkin done
if ($err =~ m/error.*identical/i) { # if there is error:
print $err;
print "No change detected: unchecking out.\n"; # uncheckout same version
system "cleartool uncheckout -rm -cact \"$file\"";
}
}
}
Here is my command line output (as if I had just used a system() call):
cleartool: Error: Unable to check in "a5TI.txt".
cleartool: Error: By default, won't create version with data identical to predecessor.
cleartool: Error: Unable to check in "a6cm.txt".
cleartool: Error: By default, won't create version with data identical to predecessor.
cleartool: Error: Unable to check in "a6FT.txt".
cleartool: Error: By default, won't create version with data identical to predecessor.
cleartool: Error: Unable to check in "a6pm.txt".
cleartool: Error: By default, won't create version with data identical to predecessor.
cleartool: Error: Unable to check in "a6TI.txt".
cleartool: Error: By default, won't create version with data identical to predecessor.
SOLUTION: check std error stream as well when grabbing output (in retrospect this makes sense as I was trying to parse error messages... oh well)
my #checkInErr = `cleartool checkin -nc \"$file\" 2>&1`;
It's possible the error output from cleartool is not coming out on Standard Output (stdout). With any luck, it's coming out on Standard Error (stderr). If so, this should work:
system "cleartool uncheckout -rm -cact \"$file\" 2>&1";

How do I get topshelf to return error code when command fails?

I am trying to start my service with powershell but currently it fails. I don't know why it fails but that is not the point here. When trying to start the host all I don't get the correct exit code so my automatic deploy fails silently.
What I'm trying to do is:
$cmd = "$folder" + "\MyService.exe"
try
{
& $cmd stop
& $cmd uninstall
& $cmd install
& $cmd start
}
catch
{
Write-Host "Error: Update of service failed"
exit 1
}
The start command fails with the following messge:
Topshelf.Hosts.StartHost Error: 0 : The service failed to start., System.InvalidOperationException: Cannot start service MyService on computer '.'. ---> System.ComponentModel.Win32Exception: The service cannot be started, either because it is disabled or because it has no enabled devices associated with it
--- End of inner exception stack trace ---
at System.ServiceProcess.ServiceController.Start(String[] args)
at System.ServiceProcess.ServiceController.Start()
at Topshelf.Runtime.Windows.WindowsHostEnvironment.StartService(String serviceName)
at Topshelf.Hosts.StartHost.Run()
and I never get into the catch statement of my powershell script.
UPDATE:
Note that I am asking for how to get the method to the catch statement and not the solution to the actual exception. I have solved the actual exception but I want better feedback in the future if it fails, and that is want the catch statement to be executed which it isn't in case of error.
try/catch in PowerShell doesn't work with exe.
After myservice.exe calls you need to check the automatic variable $LastExitCode.
Try something like this:
$out = & $cmd start
if ($LastExitCode -ne 0) # if exe returns 0 on success, if not change the condition accordingly
{
"ERROR: $out"
return # to exit script or do something else.
}

Is there a way to add errors from build step in TeamCity to the email notification?

I have a Powershell build step, and I'd like to add some messages fromt the script to the resulting email that is sent to people on the notification list. I see this happen for tests where the number of failures and the error is added to the email. But, how can I add my custom messages from the PowerShell build step to the resulting email?
Have you tried using service messages?
See here:http://confluence.jetbrains.com/display/TCD7/Build+Script+Interaction+with+TeamCity
You could use
write-host "##teamcity[message text='Its broken again' errorDetails='Your exception message' status='FAILURE']"
In order for the errors to be included in emails, I found I needed to add "compilationStarted" and "compilationFinished" tags, e.g:
##teamcity[compilationStarted compiler='Solution.sln']
##teamcity[message text='1>File.cpp(1): error C2065: "stackoverflow" : undeclared identifier' status='ERROR']
##teamcity[compilationFinished compiler='Solution.sln']
I use a Python script to parse the output from devenv, looking for specific strings to add as errors and warnings. The email adds these under a "compilation errors" section.
If you mean to pipe the output of an error that occurred in the Powershell script you are running then try piping the error object to a TeamCity service message after it has been caught
This is untested code but it might work for you:
trap [SystemException]
{
write-host "##teamcity[message text='An error occurred' errorDetails='$_' status='ERROR']";exit 1
}
OR
try
{
# Something...
}
catch
{
write-host "##teamcity[message text='An error occurred' errorDetails='$_' status='ERROR']";exit 1
}