SSH SUDO passwordless to run commands on remote server

Hi Experts,
We are running various OS/Network and Database related commands and scripts on Local and Remote Server to perform/compare the results
As part of this activity, we have bottleneck on running commands/scripts on the remote server as we need to provide password everytime whenever we use SSH command
Also, we need to run command as ssh sudo su - oracle for security purpose which prompts password two times.
we would like to automate this process in order to save password securely(temporarily) while running ssh sudo commands/scripts.
I see, there are various solutions using SSHPASS,EXPECT commands, however we dont have anything available to use within our group.
We may not be able to use SSHPASS as this component not installed during VM build, so we left with only option to use EXPECT.
So, Need your help to get any example working script using EXPECT for ssh sudo passwordless connection.
Appreciate if anybody can share ideas or working scripts
Thanks in advance

FWIW, here is a small script that I wrote several years ago that may help you to automate the password less ssh setup with a remote system. I just verified it and changed it to create a RSA key. The script still works and runs fine under Oracle Linux and Mac OS X.
Simply create a script called "passwordless-ssh" with the content shown below.
Assign execute privileges: chmod u+x passwordless-ssh
Then run the script as following:
./passwordless-ssh user@target_hostname_or_ip
The script will create a ssh RSA private and public key, prompt for the remote host password and the copy the pubic key to the remote host. A subsequent ssh login to the remote host should no longer prompt for the password. It is essential however that the scrips runs in an interactive session, which is verified.
#!/bin/bash
# Creating SSH public RSA key if non exist and copying it to remote target
# for passwordless SSH login.
# Author: Catch 22, Oracle OTN, 28-APR-2015
# Arguments: $1 (ssh login to remote target)
ME=passwordless-ssh
LOGFILE="/tmp/$ME.log"
f-mode()
# Check if session is interactive (terminal) or non-interactive (UDEV).
# Output: 0 = interactive, 1 = non-interactive
   [[ -t 0 || -p /dev/stdin ]] && return 0 || return 1
f-log()
# Display messages in interactive mode, or write output to syslog
# (/var/log/messages) when in non-interactive mode. Write the messages
# to a logfile if the syslog logger interface command is not available.
# Input: $1 = text
   if f-mode; then
      echo "$ME: $1"
   elif hash logger; then
      logger "$ME: $1"
   else
      echo "$ME:`date`: [logger] Cannot execute, aborting" >> $LOGFILE
      echo "$ME:`date`: $1" >> $LOGFILE
   fi     
# Exit and show error if current session is not interactive.
[ ! f-mode ] && f-log "[session] non-interactive, aborting" && exit 1
keyfile="$HOME/.ssh/id_rsa"
[ -z "$1" ] && echo "Missing 'user@target_host' argument. Aborted." && exit 1
if [ ! -f $keyfile ]; then
   mkdir -p $HOME/.ssh
   ssh-keygen -t rsa -f $keyfile -N ''
fi
keycode=`cat $keyfile.pub`
remote_cmd2="echo "$keycode" >> $remote_ssh_file; chmod 644 $remote_ssh_file;"
remote_ssh_dir="~/.ssh"
remote_ssh_file="$remote_ssh_dir/authorized_keys"
ssh -q $1 "mkdir -p $remote_ssh_dir; chmod 700 $remote_ssh_dir
echo "$keycode" >> $remote_ssh_file; chmod 644 $remote_ssh_file"
unset ME LOGFILE keyfile keycode remote_ssh_dir remote_ssh_file
#END

Similar Messages

  • How do I run a unix command to quit ARD if it is running on a remote server I am trying to access?

    how do I run a unix command to quit ARD if it is running on a remote server I am trying to access?

    killall "Remote Desktop"
    Regards.

  • REP-0177: An error occurred while running in a remote server.

    I am getting the following errors while trying to run a report script.  The report was created in Report Builder.
    REP-0177: An error occurred while running in a remote server.
    Reference parameter OT_RUN_DATE in the distribution list is invalid.
    OT_RUN_DATE is a static field converting SYSDATE to a string (TO_CHAR(SYSDATE, 'YYYYMMDD')).  Unfortunately, I inherited this report and did not create it.  I do not know what purpose it serves but would like more insight into what the reference parameter and distribution list mean.
    REP-0177: An error occurred while running in a remote server.
    Too many errors pushed on the stack
    I assume this is related to the first error but am not certain.
    Any help is greatly appreciated...

    Michel,
    It appears that in the past few days you have not received a response to your
    posting. That concerns us, and has triggered this automated reply.
    Has your problem been resolved? If not, you might try one of the following options:
    - Do a search of our knowledgebase at http://support.novell.com/search/kb_index.jsp
    - Check all of the other support tools and options available at
    http://support.novell.com.
    - You could also try posting your message again. Make sure it is posted in the
    correct newsgroup. (http://support.novell.com/forums)
    Be sure to read the forum FAQ about what to expect in the way of responses:
    http://support.novell.com/forums/faq_general.html
    If this is a reply to a duplicate posting, please ignore and accept our apologies
    and rest assured we will issue a stern reprimand to our posting bot.
    Good luck!
    Your Novell Product Support Forums Team
    http://support.novell.com/forums/

  • Command Center Remote Server

    Evening All,
    (My first post.. hoping to hand around as its my first MSI board too!)
    Just a quickie, i've download the app store "Command Center" and also the desktop version however i am unable to locate the "Command Center Remote Server" tray icon on my PC? So i am unable to obtain the port in use and the security key :( Just wondering if anyone was able to help me?
    INFO:
    MSI Z87-G43
    2TB HDD
    Intel i5 1150 3.2 Quad Core CPU
    Water cooled
    Anything i've forgot let me know!
    Thanks guys!

    I will take a look at it and post back. I tried it once and got it to work. i think the key shows in the app, you just need it and the IP that is needed.
    Edit:
    Okay, open control center, click on the mobile control tab. Turn on the app on you phone, hit the settings button to see the ip and key. It brings up the wrong ip the first time (did for me) enter you computers ip with :81 at the end (that's the port). If you don't know your ip go to command prompt and enter ipconfig /all    then look at the IPv4 address.

  • Check if IIS running on a remote server

    Hi,
    I need to check if IIS is running in a remote server. This is what I have collected from web, but not working. Even though IIS is running in the remote-server, but this check always saying "Not running".
    $servers = @("STGNX150-1")
    foreach($server in $servers)
    $iis = get-wmiobject Win32_Service -ComputerName $server -Filter "name='IISADMIN'"
    if($iis.State -eq "Running")
    {Write-Host "IIS is running on $server"}
    else
    {Write-Host "IIS is not running on $server"}

    I get the feeling that IIS is not installed on the server. Get-WMIObject returns nothing when a filter is not met regardless of if it is run against a remote computer, or on the local computer. This could be enough to make some people think it is not working.
    Log on to your server and run the first four examples - do you get any results? Then try the following four from a remote computer changing 'computername' to the name of your IIS computer.
    #Local
    Get-WmiObject Win32_Service -Filter "Name='Winmgmt'"
    Get-WmiObject Win32_Service -Filter "Name='eventlog'"
    Get-WmiObject Win32_Service -Filter "Name='Dnscache'"
    Get-WmiObject Win32_Service -Filter "Name='Netlogon'"
    #Remote
    Get-WmiObject Win32_Service -Filter "Name='Winmgmt'" -ComputerName computername
    Get-WmiObject Win32_Service -Filter "Name='eventlog'" -ComputerName computername
    Get-WmiObject Win32_Service -Filter "Name='Dnscache'" -ComputerName computername
    Get-WmiObject Win32_Service -Filter "Name='Netlogon'" -ComputerName computername
    Also, be sure to try the Get-Service cmdlet locally and remotely, as well.
    #Local
    Get-Service -Name 'IISADMIN'
    Get-Service -Name 'Winmgmt'
    Get-Service -Name 'eventlog'
    Get-Service -Name 'Dnscache'
    Get-Service -Name 'NetLogon'
    #Remote
    Get-Service -Name 'IISADMIN' -ComputerName computername
    Get-Service -Name 'Winmgmt' -ComputerName computername
    Get-Service -Name 'eventlog' -ComputerName computername
    Get-Service -Name 'Dnscache' -ComputerName computername
    Get-Service -Name 'NetLogon' -ComputerName computername

  • Run commands on remote Hyper-V host in different domain/network with powershell

    Hi experts,
    My Setup: Windows Server 2012 R2 / SCVMM 2012 managing localhost and other Hyper-V hosts
    I need to run a script on the remote Hyper-V Host which is in different domain/workgroup using powershell.
    I have tried
    Invoke-SCScriptcommand cmdlet. But I am getting the below error
    Error (2917)
    Virtual Machine Manager cannot process the request because an error occurred while authenticating MY-PC-15.mydomain.local. Possible causes are:
    1) The specified user name or password are not valid.
    2) The Service Principal Name (SPN) for the remote computer name and port does not exist.
    3) The client and remote computers are in different domains and there is not a two-way full trust between the two domains.
    The network path was not found (0x80070035)
    I tried the 'Run Script Command' option in the Host tab in VMM. But getting the same error.
    Checked that it uses the 'Invoke-ScScriptcommand' PS cmdlet.
    Could someone explain how to run scripts on remote Hyper-V host in different Domain/Perimeter network ?
    Regards,
    Saleem

    Hi Saleem,
    Please try to follow the article below to regarding using command "enter-pssession" across domains :
    https://social.technet.microsoft.com/Forums/windowsserver/en-US/f60a29ef-925e-4712-9788-1f95e12c8cfc/forum-faq-introduce-windows-powershell-remoting?forum=winserverpowershell
    (I tested it in my lab )
    Best Regards,
    Elton Ji
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact [email protected] .

  • Why Java VisualVm Could not show running applications of remote server

    Hi,everyone. I run jstatd in the remote server, and run java visualVM in local ,but the applications running in remote server could not display in the visualVM panel.
    this is local viaualVm Info:
    ===============================================
    Version:
    1.7.0_02 (Build 1320-110325); platform 110131-9c8b3bfb3a1e
    System:
    Windows 7 (6.1) Service Pack 1, amd64 64bit
    Java:
    1.7.0_02; Java HotSpot(TM) 64-Bit Server VM (22.0-b10, mixed mode)
    Vendor:
    Oracle Corporation, http://java.oracle.com/
    Environment:
    GBK; zh_CN (visualvm)
    Userdir:
    C:\Users\Johnny\AppData\Roaming\.visualvm\7
    Clusters:
    C:\Java\jdk1.7.0_02\lib\visualvm\platform
    C:\Java\jdk1.7.0_02\lib\visualvm\visualvm
    C:\Java\jdk1.7.0_02\lib\visualvm\profiler
    有关详细信息,请访问 http://visualvm.java.net。在 NetBeans 平台上构建。
    ==============================================================
    the OS of remote server is CentOS 6. jvm info:
    ==============================================================
    java version "1.7.0_02"
    Java(TM) SE Runtime Environment (build 1.7.0_02-b13)
    Java HotSpot(TM) 64-Bit Server VM (build 22.0-b10, mixed mode)
    ==============================================================
    start jstatd command is :
    ====================================
    ./jstatd -J-Djava.security.policy=jstatd.all.policy -p 2020
    ====================================
    the content if jstatd.all.policy which in the $JAVA_HOME\bin
    =====================================
    grant codebase "file:${java.home}/../lib/tools.jar" {
    permission java.security.AllPermission;
    =====================================
    whats wrong happened ?
    帖子经 user5950241编辑过

    are you running jstatd on the remote server as a user with permission to see the jvm processes you care about?

  • How do you get values of local machine running applet on remote server?

    Hi,
    I have an applet that runs great running the html file on my local machine from a root directory. I've placed my code(java, class, and html files) on the web server and loaded the applet onto a page. The results are merely:
    "Computer Name: localhost"
    "IP Address : 127.0.0.1"
    Instead of:
    "Computer Name: ACTUALNAME"
    "IP Address : 189.40.20.211"
    etc...
    The code is as follows:
    import java.applet.*;
    import java.awt.*;
    import java.net.InetAddress;
    public class IPFinder extends Applet {
    public void paint(Graphics g) {
    super.paint(g);
    try {
    InetAddress localaddr = InetAddress.getLocalHost () ;
    g.drawString("Computer Name: " + localaddr.getHostName (), 2, 13);
    g.drawString("IP Address : "+localaddr.getHostAddress (), 3, 25);
    g.drawString("", 3, 45);
    String str = localaddr.getHostName();
    InetAddress[] localaddrs = InetAddress.getAllByName ( str ) ;
    for ( int i=0 ; i<localaddrs.length ; i++ )
    if ( ! localaddrs[ i ].equals( localaddr ) )
    // g.drawString("Local hostname : " + localaddrs[ i].getHostName () , 3, (i+0)+50);
    g.drawString("Local IP Address("+i+"): " + localaddrs[ i].getHostAddress () , 3, (12*i)+((i+10)+45));
         }} } catch (Exception e) {
    g.drawString("Can't detect localhost : " + e +". Check Network settings.", 3, 60);
    public static void main(String[] args) { new IPFinder(); }
    I'm trying to get Real IP Addresses (as the code was setup to do) from a browser running on the web server. I have read some of the threads in this forum and some mention to use NetworkInterface while others recommended using Sockets (not an option since we do not use them), and another to use a signature as a workaround. Anyone know the best direction to get the results expected?
    Thanks in advance,
    Geoff-

    I have an applet that runs great running the html file
    on my local machine from a root directory. I've
    placed my code(java, class, and html files) on the web
    server and loaded the applet onto a page. The results
    are merely:
    "Computer Name: localhost"
    "IP Address : 127.0.0.1"This indicates that your applet when run over a web
    server has not the rights to query the local name and
    address. Look [url
    http://java.sun.com/j2se/1.4.2/docs/api/java/net/InetAd
    ress.html#getLocalHost()]here. The so-called
    loopback address is 127.0.0.1
    Check your documentation for "signed jar" (or search
    the forum or the sun website) if you want to give your
    applet more rights, but I don't think that this is
    worth the effort in this case.
    gdsimz, since you already started two new threads based on my suggestion, how about at least saying "thank you" or "sorry, didn't help"?

  • Javascript: Check Internet connection before attempting to run SQL command on remote server

    Good evening,
    I am developing a form that reads and posts data from/to a table hosted on a remote PC running XP/SQL Server Express 2008 R2. I access the server through the Internet.
    My problem is that if the internet connection happens to be down when I -eg- try to save data to the table using the form, the SQL command tries to reach the server for a while, and eventually crashes.
    Is there a way to programatically verify that a remote SQL server is reachable over the Internet before attempting to run a command on it?
    Many thanks in advance for any help you can provide!
    Randy

    Did you find a solution to this? I am attempting a similar form and need to verify there is an active internet connection before allowing the form to process.

  • Stored Proc can't run psexec to remote server but SQLCMD mode can - help?

    I'm really hoping someone can help with my Access Denied issue issuing an xp_cmdshell "psexec" that otherwise works in SQLCMD Mode and the command line.  Any help would really be appreciated.
    The setup:
    Server 1.1.1.1:
    I have a db MYDB (trustworthy, I'm an admin logging in using Windows Authentication)
    I have psexec (running as admin, "everyone" has full-control from G:\
    Server 1.1.2.1:
    I have application ABC.exe (again, running as admin, "everyone" has full-control) on E:\Program Files
    The problem
    I can start ABC.exe from      1.1.1.1 from my command prompt for my user:
    psexec.exe
    \\1.1.2.1 -d -u DOMAIN\USER -p PASSWORD 
    "E:\Program Files\ABC.exe" /accepteula
    I can start ABC.exe from      1.1.1.1 from SSMS using the SQLCMD Mode:
    !!G:\psexec.exe
    \\1.1.2.1 -d -u DOMAIN\USER -p PASSWORD 
    "E:\Program Files\ABC.exe" /accepteula
    I
    cannot get the command to run by      calling it from
    a stored procedure or trigger:
    EXEC xp_cmdshell 'G:\psexec.exe
    \\1.1.2.1 -d -u DOMAIN\USER -p PASSWORD 
    "E:\Program Files\ABC.exe" /accepteula'
    I
    cannot get ABC.exe to start on the      remote machine
    by putting in the working command from #1 above into a batch file and calling that, either!
    Thanks in advance,
    Dave

    OK, thanks. 
    MORE INFORMATION: SQL is SQL 2012, two machines are WINDOWS SERVER 2012
    I realize I'm probably treading in dangerous waters here, but I try to set the xp_cmdshell proxy account to two different users and I'm getting different results. 
    Here's my two blocks of sql code:
    GRANT EXECUTE ON xp_cmdshell TO [DOMAIN\user1]
    EXEC xp_cmdshell 'whoami'
    EXEC sp_xp_cmdshell_proxy_account 'DOMAIN\user1','pwd1'
    EXECUTE AS login = 'DOMAIN\user1'
    EXEC xp_cmdshell 'whoami'
    EXEC xp_cmdshell 'G:\psexec.exe \\1.1.2.1 DOMAIN\user1 -p pwd1 "E:\Program Files\ABC.exe" /accepteula'
    REVERT
    GRANT EXECUTE ON xp_cmdshell TO [DOMAIN\user2]
    exec xp_cmdshell 'whoami'
    EXEC sp_xp_cmdshell_proxy_account 'DOMAIN\user2','pwd2'
    EXECUTE AS login = 'DOMAIN\user2'
    exec xp_cmdshell 'whoami'
    EXEC xp_cmdshell 'G:\psexec.exe \\1.1.2.1 DOMAIN\user2 -p pwd2 "E:\Program Files\ABC.exe" /accepteula'
    REVERT
    And the results are (1) unexpected in terms of who the cmdshell user is and (2) the two executions are different failures:
    Results from ALL the exec xp_cmdhell  'whoami' is DOMAIN\user3!
    And the two different outputs (after both "Access is denied.") are
    1 - Connecting to 1.1.2.1 ...                                                                           
    Connecting to 1.1.2.1 ...
    Couldn't access 1.1.2.1 :
    and
    2-Connecting to 1.1.2.1 ...
    Connecting to 1.1.2.1 ...
    Starting PsExec service on 1.1.2.1 ...
    Could not start PsExec service on 1.1.2.1 :
    I'm sure there's a clue in this output somewhere, it's just evading me.  I'm guessing there's something missing on the remote machine's security, but....

  • Issue with groups not being able to run applications on remote server

    Hi all..
    I've got an older PowerMac G5 running 10.5.8 that gets the OpenDirectory accounts from our MacMini server running 10.6.5. I've got a group setup called "Children" that my kids belong to and which is managed care of the Workgroup manager. However, I find that some of my apps can't be run by any of the kids if they're in subdirectories within /Applications. They receive a "The operation could not be completed because you do not have enough access privileges." I've tried playing around with various settings and finally decided to not restrict access to any applications but the problems remain.. Some apps can be run just fine but others are out of reach.. Any ideas on how to fix this or perhaps diagnose it?
    Thx!

    Hi
    Another approach is to create a folder in the local Administrators Home folder. Name it Applications. Place the applications you want to restrict access to into that folder. If you have ARD you could use the mkdir and mv commands to achieve this. In some situations I find this an easier way of managing applications rather than what's available in WorkGroup Manager. For me it only tends to work with Apple's built in applications effectively. Anything else is liable to cause a problem along the lines you mention. Some 3rd-Party applications can have dependencies that may be sited in different locations. The trick is tracking down them.
    Tony

  • Xcommand - run commands in X server

    xcommand is a very small and simple script I made.
    Essentially you start "xcommand --daemon &" when X starts and it binds to a unix socket.
    You can then pass a command to it using "xcommand <command>" and xcommand will run this command, e.g. "xcommand notify-send testing"
    aur package: https://aur.archlinux.org/packages/xcommand

    Updated to 0.1.1
    I have this problem to nc.openbsd and unix sockets where it locks up or something with 100% cpu usage, so i added customization where if you have a ~/.xcommandrc it will source it for the variables NC_LISTEN and NC_WRITE and i made one for myself which binds to a tcp socket instead. e.g.
    #!/bin/bash
    NC_LISTEN="nc.openbsd -lk localhost 1234"
    NC_WRITE="nc.openbsd localhost 1234"
    I don't know if other people have this problem with nc.openbsd and unix sockets so for now the defaults remain to bind to a unix socket (~/.xcommand.socket)
    EDIT: Updated to 0.1.1-2, removed line when it would delete socket on exit
    Last edited by BennyBolton (2012-11-16 23:03:42)

  • To upload the time data from a remote server into R/3 2011 infotype

    hi all,
          i have been given a task to upload the time data of the employees into the 2011 infotype from a remote time recording server, can this problem be solved with the help of a rfc which will run on that remote server, please guide me how to approach this problem.
    thanks & regards,
    santosh.

    Hi Santosh,
    You can use ALE for this. The message type is HRSM_D for upload of time data.
    Reward if useful.
    Regards,
    Senthil

  • IPhone SDK : Communication between iPhone client and a remote server

    Hi,
    This is w.r.t iPhone Cocoa Touch native application.
    i need to populate my application 's data from a remote application server ( which in turn connects to the database) . I require some tips in the communication between client sitting on the iPhone and the remote application server. I am planning to proceed in XML transaction way.
    I referred the SeismicXML sample application provided by Apple. In this sample,client reads the physically existing xml file from @"http://earthquake.usgs.gov/eqcenter/catalogs/eqs7day-M2.5.xml"; and the client parses the xml file and display the content on the table view.
    i have following 2 queries ,
    1. I do not want to read from a physically present file,i want the data to be transferred on the go.
    Means, request should be sent from the client to a application server and the server process returns the data in form of xml file ( but its not creating any physical xml file) .
    Basically i am looking for request - response concept.
    2. Can we call a java process(which returns xml data) running on a remote server from the cocoa touch client.? If not java process,what would be other best way...
    i am going through the Apple provided frameworks. Do any of the iPhone SDK frameworks support this request? If some one has any idea on the above mentioned queries, pls help me.
    any pointers will also be helpful.
    It might be too early to talk about these,but i have to take some business decision related on this.
    thanks in advance.

    You already know how to send a string via HTTP Post? And you know how to make XML into a string? Put the two together.

  • How can you run a command with elevated rights on a remote server with invoke-command ?

    I am trying to run a script on a remote server with invoke-command.  The script is starting and is running fine, but the problem is that it should be running with elevated rights on the remote server.  On the server where I start the invoke-command, my account has the necessary rights.
    The server were I launch the invoke-command is a W2K8 R2.  The remote box is a W2K3 with powershell v2.0 installed.
    When I launch the script on the remote-box from the command line, I don't get the access denied's.
    Is there a way to do this ?
    Thanks in advance

    The script that I want to run is to install the windows updates.  I get an access denied on the download of the updates.
    When I execute the script on an W2K8 box, (not remotely) and I run it with non-elevated rights, I get the same error.
    The script is running fine when it is launched on W2K3 box locally with a domain account that has local admin rights, or on a W2K8 R2 server with a domain account that has local admin rights, but with elevated rights.
    Thanks in advance for your help.
    #=== start script ====
    param($installOption="TESTINSTALL",$rebootOption="NOREBOOT")
    Function Show-Help
    Write-Host ""
    Write-Host "SCRIPT: $scriptName <installOption> <RebootOption>"
    Write-Host ""
    Write-Host "DESCRIPTION: Installatie van WSUS updates op de lokale server"
    Write-Host ""
    Write-Host "PARAMETERS"
    Write-Host " -installOption <[INSTALL|TESTINSTALL]>"
    Write-Host " -rebootOption <[REBOOT|NOREBOOT|REBOOT_IF_UPDATED]>"
    Write-Host ""
    Write-Host "EXAMPLE:"
    Write-Host "$ScriptName -installOption INSTALL -rebootOption REBOOT_IF_UPDATED"
    Write-Host "$ScriptNAme INSTALL NOREBOOT"
    Write-Host ""
    Write-Host "Indien beide parameter weggelaten worden zijn de defaultwaarden :"
    Write-Host " installOption=TESTINSTALL "
    Write-Host " RebootOption=NOREBOOT"
    Write-Host ""
    Exit
    #Include alle globale variablen
    $CEIF_WIN_PATH = (get-content env:CEIF_WIN_PATH)
    $includeFile=$CEIF_WIN_PATH + "\Scripts\include_win.ps1"
    . $includeFile
    #initialiseer error count
    $errcnt=0
    $scriptName=$MyInvocation.MyCommand.Name
    #argumenten controleren
    $arrInstallOption= "TESTINSTALL", "INSTALL" # Mandatory variable with predefined values
    If (!($arrInstallOption –contains $installOption)){ Show-Help }
    $arrRebootOption = "REBOOT", "NOREBOOT","REBOOT_IF_UPDATED" # Mandatory variable with predefined values
    If (!($arrRebootOption –contains $rebootOption)){ Show-Help }
    #Logfile opbouwen
    $logfile = get-logfileName($MyInvocation.MyCommand.Name)
    Log-scriptStart $MyInvocation.MyCommand.Name $logfile
    function Get-WIAStatusValue($value)
    switch -exact ($value)
    0 {"NotStarted"}
    1 {"InProgress"}
    2 {"Succeeded"}
    3 {"SucceededWithErrors"}
    4 {"Failed"}
    5 {"Aborted"}
    function boot-server()
    if ($installOption -eq "TESTINSTALL")
    logger "TESTINSTALL : - Reboot local Server" $logfile
    else
    logger " - Reboot local Server" $logfile
    $thisServer = gwmi win32_operatingsystem
    $thisServer.psbase.Scope.Options.EnablePrivileges = $true
    $thisServer.Reboot()
    $logmsg="Install option = " + $installOption + ", RebootOption = $rebootOption"
    logger "$logmsg" $logfile
    logger "" $logfile
    logger " - Creating WU COM object" $logfile
    $UpdateSession = New-Object -ComObject Microsoft.Update.Session
    $UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
    logger " - Searching for Updates" $logfile
    $SearchResult = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0 and IsInstalled=0")
    logger " - Found [$($SearchResult.Updates.count)] Updates to Download and install" $logfile
    $Updates=$($SearchResult.Updates.count)
    logger "" $logfile
    foreach($Update in $SearchResult.Updates)
    if ($Update.EulaAccepted -eq 0)
    $Update.AcceptEula()
    # Add Update to Collection
    $UpdatesCollection = New-Object -ComObject Microsoft.Update.UpdateColl
    $UpdatesCollection.Add($Update) | out-null
    if ($installOption -eq "TESTINSTALL")
    else
    # Download
    logger " + Downloading Update $($Update.Title)" $logfile
    $UpdatesDownloader = $UpdateSession.CreateUpdateDownloader()
    $UpdatesDownloader.Updates = $UpdatesCollection
    $DownloadResult = $UpdatesDownloader.Download()
    $Message = " - Download {0}" -f (Get-WIAStatusValue $DownloadResult.ResultCode)
    if ($DownloadResult.ResultCode -eq 4 )
    { $errcnt = 1 }
    logger $message $logfile
    # Install
    logger " - Installing Update" $logfile
    $UpdatesInstaller = $UpdateSession.CreateUpdateInstaller()
    $UpdatesInstaller.Updates = $UpdatesCollection
    $InstallResult = $UpdatesInstaller.Install()
    $Message = " - Install {0}" -f (Get-WIAStatusValue $InstallResult.ResultCode)
    if ($InstallResult.ResultCode -eq 4 )
    { $errcnt = 1 }
    logger $message $logfile
    logger "" $logfile
    #Indien er een fout gebeurde tijdens download/installatie -> stuur mail naar windowsteam
    if ( $errcnt -gt 0 )
    logger " - Fout tijdens de uitvoering van script -> send mail" $logfile
    $mailSubject=$MyInvocation.MyCommand.Name
    $msg = new-object Net.Mail.MailMessage
    $att = new-object Net.Mail.Attachment($logfile)
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $msg.From = $mailFrom
    $msg.To.Add($mailTo)
    $msg.Subject = $mailSubject
    $msg.Body = “Meer details in attachement”
    $msg.Attachments.Add($att)
    $smtp.Send($msg)
    #Moet de server herstart worden ?
    if ($rebootOption -eq "REBOOT_IF_UPDATED" )
    if ($Updates -gt 0)
    #Reboot the server when updates are installed
    boot-server
    elseif ($rebootOption -eq "REBOOT")
    #reboot the server always
    boot-server
    else
    #Do not reboot the server
    logger "Do not reboot the server" $logfile
    Log-scriptEnd $MyInvocation.MyCommand.Name $logfile
    exit 0

Maybe you are looking for