Using Powershell invoke-expression to uninstall Java on all domain computers - java

I can ps-session to a remote machine, run the following, and successfully uninstall Java:
invoke-expression "msiexec /q /x '{26A24AE4-039D-4CA4-87B4-2F83218025F0}' "
I am trying to create a script that will uninstall from all domain computers:
Import-Module ActiveDirectory
function uninstallJava {
$badcomp = #()
$CompList = Get-ADComputer -Filter 'name -like "*"' | select -ExpandProperty Name
foreach ($c in $CompList) {
Try {
Enter-PSSession -ComputerName $computer
Invoke-expression "msiexec.exe /q /x '{26A24AE4-039D-4CA4-87B4-2F83218025F0}' "
}
Catch {
$badcomp += $c
}
}
}
uninstallJava
"the following servers could not be reached:"
$badcomp
I don't receive any errors, but it doesn't uninstall Java from the remote machines.
Any ideas appreciated.

Import-Module ActiveDirectory
$badcomp = #()
Function uninstallJava {
$CompList = Get-ADComputer -Filter 'name -like "*"' | Select -ExpandProperty Name
ForEach ($c In $CompList) {
Try {
Invoke-Command -ComputerName $c {
C:\Windows\System32\cmd.exe /C msiexec.exe /q /x '{26A24AE4-039D-4CA4-87B4-2F83218025F0}'
}
} Catch {
$badcomp += $c
}
}
}
uninstallJava
Write-Host "the following servers could not be reached:"
$badcomp

You should be using Invoke-Command, not Enter-PSSession. The latter is for interactively working in another machine. The former is for running a command in the other machine and getting back results (if any).
Basically, your try block should look like this:
Try {
Invoke-Command -ComputerName $c -ScriptBlock { msiexec.exe /q /x '{26A24AE4-039D-4CA4-87B4-2F83218025F0}' }
}
If you want more detailed control and error information, consider using WMI to uninstall the product instead of shelling out to msiexec.

Related

Jenkins Error : Unknown stage section "stage". Starting with version 0.5, steps in a stage must be in a ‘steps’ block

When i try to build my main in jenkins it gives me the error in the title, even though i checked and this seems like a valid configuration.
This is th code :
pipeline {
agent any
environment {
DOCKER_PASSWORD = credentials("docker_password")
GITHUB_TOKEN = credentials(".....")
}
stages {
stage('Build & Test') {
steps {
sh './gradlew clean build'
}
stage('Tag image') {
steps {
script {
GIT_TAG = sh([script: 'git fetch --tag && git tag', returnStdout: true]).trim()
MAJOR_VERSION = sh([script: 'git tag | cut -d . -f 1', returnStdout: true]).trim()
MINOR_VERSION = sh([script: 'git tag | cut -d . -f 2', returnStdout: true]).trim()
PATCH_VERSION = sh([script: 'git tag | cut -d . -f 3', returnStdout: true]).trim()
}
sh '''
docker build -t tibicode/hello-img:${MAJOR_VERSION}.\$((${MINOR_VERSION} + 1)).${PATCH_VERSION} ."
docker login docker.io -u tibicode -p ........"
docker push <tibicode>/hello-img:$IMAGE_VERSION"
'''
}
}
}
}

Is there any way to check password hash sync status in Java code?

I'm working with azure SDK and I need to check the status of "password hash sync" in code. Is there any way to check in Java?
below are some document I researched:
https://github.com/Azure/azure-sdk-for-java
https://learn.microsoft.com/en-us/azure/active-directory/hybrid/tutorial-password-hash-sync
https://learn.microsoft.com/en-us/azure/active-directory/hybrid/how-to-connect-password-hash-synchronization
I'm afraid there's no SDK to get the status of password hash sync. Only Get-ADSyncAADCompanyFeature can help you.
You could try to create a powershell script and then invoke the powershell script from java.
Import-Module ADSync
$connectors = Get-ADSyncConnector
$aadConnectors = $connectors | Where-Object {$_.SubType -eq "Windows Azure Active Directory (Microsoft)"}
$adConnectors = $connectors | Where-Object {$_.ConnectorTypeName -eq "AD"}
if ($aadConnectors -ne $null -and $adConnectors -ne $null)
{
if ($aadConnectors.Count -eq 1)
{
$features = Get-ADSyncAADCompanyFeature
Write-Host
Write-Host "Password sync feature enabled in your Azure AD directory: " $features.PasswordHashSync
foreach ($adConnector in $adConnectors)
{
Write-Host
Write-Host "Password sync channel status BEGIN ------------------------------------------------------- "
Write-Host
Get-ADSyncAADPasswordSyncConfiguration -SourceConnector $adConnector.Name
Write-Host
$pingEvents =
Get-EventLog -LogName "Application" -Source "Directory Synchronization" -InstanceId 654 -After (Get-Date).AddHours(-3) |
Where-Object { $_.Message.ToUpperInvariant().Contains($adConnector.Identifier.ToString("D").ToUpperInvariant()) } |
Sort-Object { $_.Time } -Descending
if ($pingEvents -ne $null)
{
Write-Host "Latest heart beat event (within last 3 hours). Time " $pingEvents[0].TimeWritten
}
else
{
Write-Warning "No ping event found within last 3 hours."
}
Write-Host
Write-Host "Password sync channel status END ------------------------------------------------------- "
Write-Host
}
}
else
{
Write-Warning "More than one Azure AD Connectors found. Please update the script to use the appropriate Connector."
}
}
Write-Host
if ($aadConnectors -eq $null)
{
Write-Warning "No Azure AD Connector was found."
}
if ($adConnectors -eq $null)
{
Write-Warning "No AD DS Connector was found."
}
Write-Host
For more details, see here.

Getting issue in adding cron expression to crontab from java and CLI

I am running the command below with is passing two argument to my script file(This below command is being constructed from java):
sh /home/accure/Desktop/scripts/cronhandler.sh "/home/accure/Desktop/scripts/pipeline.sh 028d8ccb-4c46-4e02-a9b0-3c97a383daaf" "* * * * */5"
Where "/home/accure/Desktop/scripts/pipeline.sh 028d8ccb-4c46-4e02-a9b0-3c97a383daaf" is the first argument and "* * * * */5" is the second argument which is basically a cron expression.
cronhandler.sh is my script file which contain this code:
if [ "$#" -eq 2 ]
then
echo "Crontab with create & update functionality"
command=$1
cron_exp=$2
echo "cron_exp=$cron_exp"
echo "command=$command"
cron_exp=`echo $cron_exp | sed 's/"//g' `
command=`echo $command | sed 's/"//g' `
echo "cron_exp=$cron_exp"
echo "command=$command"
if [[ "$cron_exp" != " " && "$command" != " " ]]
then
crontab -l | grep -q "$command"
if [ $? -eq 0 ]
then
crontab -l | grep -v "$command" | crontab -
echo "CRON entry deleted successfully.."
else
echo "CRON entry deletion failed."
fi
crontab -l | grep -q "$command" || (crontab -l 2>/dev/null; echo "$cron_exp $command") | crontab -
if [ $? -eq 0 ]
then
echo "CRON entry added successfully.."
else
echo "CRON entry addition failed."
fi
fi
fi
The error I'm getting while running the script is below. Actually it's listing out my files and folders from current working directory instead of adding the cron expression to cron tab.
Crontab with create & update functionality cron_exp=* * * * */5
command=/home/accure/Desktop/scripts/pipeline.sh
028d8ccb-4c46-4e02-a9b0-3c97a383daaf cron_exp=14.5 LinkedList vs
ArrayList in Java-QWMyhFUtFHo.mp4
[57.64911004342139,10.407439861446619]
accure-facebook-parser-1.0-SNAPSHOT-jar-with-dependencies.jar
apache-tomcat-7.0.41 Core Java With OCJP_SCJP - Collections Part-11 _
Map _ Hashmap _ linked Hashmap-pSGvbJ7GJ68.mp4.part Desktop Documents
Downloads epel-release-6-8.noarch.rpm How HashMap works in Java With
Animation!! whats new in java8 tutorial-c3RVW3KGIIE.mp4 ingester Java
interview - How Hashmap works -YR7Vp7HcAgs.mp4 jce_policy-8.zip
mongodata Music netbeans-7.4 NetBeansProjects Pictures Public quasar
robomongo-0.8.4-x86_64 sa softs solr-6.2.1 solr-6.2.1.tgz Templates
testdata UnlimitedJCEPolicyJDK8 Videos Vinod 14.5 LinkedList vs
ArrayList in Java-QWMyhFUtFHo.mp4
[57.64911004342139,10.407439861446619]
accure-facebook-parser-1.0-SNAPSHOT-jar-with-dependencies.jar
apache-tomcat-7.0.41 Core Java With OCJP_SCJP - Collections Part-11 _
Map _ Hashmap _ linked Hashmap-pSGvbJ7GJ68.mp4.part Desktop Documents
Downloads epel-release-6-8.noarch.rpm How HashMap works in Java With
Animation!! whats new in java8 tutorial-c3RVW3KGIIE.mp4 ingester Java
interview - How Hashmap works -YR7Vp7HcAgs.mp4 jce_policy-8.zip
mongodata Music netbeans-7.4 NetBeansProjects Pictures Public quasar
robomongo-0.8.4-x86_64 sa softs solr-6.2.1 solr-6.2.1.tgz Templates
testdata UnlimitedJCEPolicyJDK8 Videos Vinod 14.5 LinkedList vs
ArrayList in Java-QWMyhFUtFHo.mp4
[57.64911004342139,10.407439861446619]
accure-facebook-parser-1.0-SNAPSHOT-jar-with-dependencies.jar
apache-tomcat-7.0.41 Core Java With OCJP_SCJP - Collections Part-11 _
Map _ Hashmap _ linked Hashmap-pSGvbJ7GJ68.mp4.part Desktop Documents
Downloads epel-release-6-8.noarch.rpm How HashMap works in Java With
Animation!! whats new in java8 tutorial-c3RVW3KGIIE.mp4 ingester Java
interview - How Hashmap works -YR7Vp7HcAgs.mp4 jce_policy-8.zip
mongodata Music netbeans-7.4 NetBeansProjects Pictures Public quasar
robomongo-0.8.4-x86_64 sa softs solr-6.2.1 solr-6.2.1.tgz Templates
testdata UnlimitedJCEPolicyJDK8 Videos Vinod 14.5 LinkedList vs
ArrayList in Java-QWMyhFUtFHo.mp4
[57.64911004342139,10.407439861446619]
accure-facebook-parser-1.0-SNAPSHOT-jar-with-dependencies.jar
apache-tomcat-7.0.41 Core Java With OCJP_SCJP - Collections Part-11 _
Map _ Hashmap _ linked Hashmap-pSGvbJ7GJ68.mp4.part Desktop Documents
Downloads epel-release-6-8.noarch.rpm How HashMap works in Java With
Animation!! whats new in java8 tutorial-c3RVW3KGIIE.mp4 ingester Java
interview - How Hashmap works -YR7Vp7HcAgs.mp4 jce_policy-8.zip
mongodata Music netbeans-7.4 NetBeansProjects Pictures Public quasar
robomongo-0.8.4-x86_64 sa softs solr-6.2.1 solr-6.2.1.tgz Templates
testdata UnlimitedJCEPolicyJDK8 Videos Vinod */5
command=/home/accure/Desktop/scripts/pipeline.sh
028d8ccb-4c46-4e02-a9b0-3c97a383daaf CRON entry deletion failed.
"-":2: bad minute errors in crontab file, can't install. CRON entry
addition failed.
Note: Rather being added to crontab, * in cron expression is listing out my files and folder from current working directory.
Java code from where i am calling the command line is given below :
String pipelineFilePath="sh /home/accure/Desktop/scripts/pipeline.sh 028d8ccb-4c46-4e02-a9b0-3c97a383daaf";
String cronExp="* * * * */5";
pipelineFilePath = "\"" + pipelineFilePath + "\"";
cronExp = "\"" + cronExp + "\"";
command = "sh " + /home/accure/Desktop/scripts/cronhandler.sh + " " + pipelineFilePath + " " + cronExp;
runScript(command);
public void runScript(String script) throws InterruptedException {
final String cmd = script;
Thread runScript = new Thread(new Runnable() {
public void run() {
try {
DefaultExecutor executor = new DefaultExecutor();
CommandLine commandLine = CommandLine.parse(cmd);
executor.setExitValue(1);
int exitValue = executor.execute(commandLine);
} catch (Exception ex) {
}
}
});
runScript.start();
Thread.sleep(10000);
}
Try to put single quotes (') instead of double quotes (") around your arguments:
sh /home/accure/Desktop/scripts/cronhandler.sh '/home/accure/Desktop/scripts/pipeline.sh 028d8ccb-4c46-4e02-a9b0-3c97a383daaf' '* * * * */5'
It will prevent your shell's filename expansion.

How to pass two arguments while calling jar file in batch script?

Following is my batch script
#echo off
set /a java_output=43350674
set /a img_id=1
setlocal enableDelayedExpansion
:top
for /f "tokens=1-2 delims= " %%A in ( 'java -jar test.jar %java_output%,%img_id%' ) do (
set /a java_output=%%A
set /a img_id=%%B
)
echo %java_output%
SET /A "err=error"
if "%java_output%" EQU "%err%" (
echo %img_id% > batch_log.txt
echo "End of batch script"
exit /b %ERRORLEVEL%
) else (
if %java_output% LSS 43350681 (
goto top
)
)
endlocal
Getting expected output but I am getting "Missing operand" error each time the for loops runs.
Error in " set /a img_id=%%B "
I have doubt in this line for /f "tokens=1-2 delims= " %%A in ( 'java -jar test.jar %java_output%,%img_id%' ) do (
Is this the correct way to pass 2 batch variables to jar file ?
Following is my java code in jar file.
public class Test {
public static void main(String[] args)
{
System.out.println(args[0]);
int ret = Integer.parseInt(args[0]);
// for error scenarios
String err = "error";
if(ret == 43350677)
{
System.out.println(err+" "+ret);
}
else
{
System.out.println(ret+1+" "+ret);
}
}
}
Following is my output :
C:>test.bat
Missing operand.
43350675
Missing operand.
43350676
Missing operand.
43350677
Missing operand.
0
"End of batch script"
If you want to start a jar file together with parameters out of a Windows script use the following syntax:
call java -jar my-jar-file.jar parm1 parm2 ...
The call is essential, otherwise the parameters are ignored.

RMI Client invokes Graceful shutdown. Server Stops. Manually started again. But somehow gets autokilled. Why?

Everthing on Java.
Environment: RedHat Linux 12.3
Lets get into details of the communication flow:
fig1.
NOTE: 1. Old model: There was NO A.java
"script.sh" starts/stops B.java as process
2. New model: There IS A.java
"script.sh" never uses A
"script.sh" starts B.java as process.
"myGraceful.sh" stops process Gracefully
"script.sh" is NEVER used for stopping
Server(B.java in server.jar):
Java Process triggered as: ./script.sh {start|stop}
Its a legacy class existing for 10 yrs or more
has RemoteB Interface
has
graceFul(){ ..handles all DB ,user states,connection...etc
..works perfectly from Admin
..invoked as RMI from JSP
..never invoked by script till now
}
initServer(){...}
getUsers(){...}
Requirement & My Effort:
Everyone knows how the code RMI Looks or .sh to invoke java. Hence I dont think pasting a proprietary code should be expected here.
Graceful needs to be done from shell script on same Server node. On Server everything runniing by Spring. I will die if I try to Inject a Bean as there is going to be 100x1000 dependencies coming in queue. Hence I created
RMI Client(com/common/task/A.java in same server.jar):
A can be triggered by: ./myGraceful.sh stop (eg. java -cp... com.A 2>&1)
in same server.jar - hence inevitaby loaded (note not running) on same Server node.
having p s v main(String args[])
Forks Thread ..thread calls RMI shutdown on B ...and thread expected
to die on own.
Problem:
Server shutting down perfectly. Then If I isssue following command AGAIN and AGAIN:
./script.sh start
Server starts up. But within a minute it stops automatically. I dont have any clue what and which is stopping the Server. I Observed
Prior to any of my new modifications:
"./script.sh stop" [used to work flawlessly calling kill -9 $pid ]
"ps - aefwww | grep java" used to show:
pid ppid.. /usr/java/jdk/bin/java ........java -D.... -Djava.timeout=.. -D....
pid ppid.. .../abc/ ....java...
pid ppid.. .../xyz/ .................java...
But now
"./myGraceful.sh stop" triggers modified server.jar(which now has A.java):
"ps - aefwww | grep java" shows:
pid ppid.. .../abc/ ....java...
pid ppid.. .../xyz/ .................java...
Here goes some code:
myGraceful.sh:
----------------
#!/bin/bash
CLASSPATH=$COMMON_CLASS_PATH:$LIB_INHOUSE/server.jar
rmiIp=x.y.zz.www [hidden]
rmiPort=xxxx [hidden]
peerId=1
period=5
function kill_server(){
echo -n "Shutting down Server ($pid): "
echo "executing Arnab"
echo "arg0 : $0 pid : $pid"
java -Djava.rmi.server.hostname=localhost \
com.common.task.GracefulRunner $rmiIp $rmiPort $peerId $period 2>&1
echo Done
}
case "$1" in
start)
get_pids "CustomBootstrap" $2
if [ "$pid" != "" ] ; then
get_processname "CustomBootstrap" $2
if [ "$server" != "" ] ; then
echo "Server already running. pid = $pid"
exit 1
fi
if [ "$ctserver" != "" ] ; then
echo "Shutting down CT Server($pid): "
kill -SIGQUIT $pid
kill -9 $pid
echo Done
fi
fi
$0 run $2 1>&2 &
sleep 2
$0 status $2
# $0 err
;;
stop)
$0 kill $2
;;
kill)
get_pids "CustomBootstrap" $2
if [ "$pid" != "" ] ; then
kill_server
echo "Server ended at `date`"
else
get_pids "Launcher" $2
if [ "$pid" != "" ] ; then
kill_server
else
echo "Server is not running !"
fi
fi
;;
esac
A.java
public class A {
class GracefulStopperThread implements Runnable{
private String serverRMIIp = null;
private int serverRmiPort =0;
private String serverPeerId =null;
private int shutDownPeriod =0;
public GracefulStopperThread(String rmiIp,String rmiPort,String peerId,String period){
serverRMIIp = rmiIp;
serverRmiPort = Integer.parseInt(rmiPort);
serverPeerId = peerId;
shutDownPeriod =Integer.parseInt(period);
}
public void run() {
System.out.println("***************************************** GracefulStopper is running *******************************************");
System.out.println("serverPeerId :="+serverPeerId+" , shutDownPeriod :="+shutDownPeriod);
try {
IRemoteServer serverRef = null;
String rmiUrl = getURL(serverRMIIp,serverRmiPort,serverPeerId);
System.out.println("THE RMI URL : "+rmiUrl);
serverRef = (IRemoteServer) Naming.lookup(rmiUrl );
com.server.ds.IRemoteServer pcServerRef = (com.server.ds.IRemoteServer) serverRef;
pcServerRef.graceful(SHUTDOWN_TYPE_SERVER_NOTSYSTEM,"Gracefully Shutting down withing 10 mins", shutDownPeriod);
System.out.println("GracefulStopperThread completed ");
} catch (Exception e) {
e.printStackTrace();
}
}
private String getURL(String rmiIp,int rmiPort,String peerId) {
return new StringBuffer(32).append("rmi://").append(serverRMIIp).append(':').append(serverRmiPort)
.append('/').append(serverPeerId).toString();
}
}
public static void main(String args[]) throws InterruptedException {
A agent = new A();
Runnable stopper = agent.new GracefulStopperThread(args[0],args[1],args[2],args[3]);
Thread t = new Thread(stopper);
t.start();
t.join();
System.out.println("MainThread completed ");
}
}
From catalina and tomcat logs it became clear - there was a wrong missing JMX entry in the jmx config file which has nothing to do with all above. This caused Tomcat to stop after 85 % of its start. Hence it actually never started. Question can be closed and marked solved.

Categories

Resources