Thursday, October 13, 2016

Check for a hotfix on a remote Windows Server with WMI

 $KB = Read-Host -Prompt "Enter KB number: "  
 $computername = Read-Host -Prompt "Enter FQDN of Computer or IP"  
 $query = "select HotFixID from Win32_QuickFixEngineering"  
 $HotFixes = Get-WmiObject -Query $query -ComputerName $computername  
 $found = $false  
 foreach ($HotFix in $HotFixes)  
 {  
   #Write-Host $HotFix.HotFixID  
   if ($HotFix.HotFixID -eq $KB)  
   {  
     Write-Host "HotFix $KB installed"  
     $found = $true  
   }  
 }  
 if ($found -eq $false)  
 {  
   Write-Host "HotFix not found"  
 }  
 Clear-Variable $HotFixes  

Tuesday, May 10, 2016

Puppet module to install PowerBroker open and join machines to domain

init.pp
class pbis (
  $domain = $pbis::params::domain,
  $ldapbindaccount = $pbis::params::ldapbindaccount,
  $ldapbindpassword = $pbis::params::ldapbindpassword,
  $sudogroup = $pbis::params::sudogroup,
) inherits pbis::params {
}

params.pp
class pbis::params {
  $domain = 'example.com'
  $ldapbindaccount = 'user'
  $ldapbindpassword = 'password'
  $sudogroup = 'domain^admins'
}

install.pp
class pbis::install inherits pbis {
  include apt

  apt::source { 'powerbroker':
    comment  => 'Powerbroker Identity Services',
    location => 'http://repo.pbis.beyondtrust.com/apt',
    release  => 'pbiso',
    repos    => 'main',
    pin      => '500',
    key      => {
      'source'     => 'http://repo.pbis.beyondtrust.com/yum/RPM-GPG-KEY-pbis',
      'id'         => 'BE7FF72A6B7C8A9FAE061F4F2E52CD89C9CEECEF',
    },
    include  => {     
      'deb' => true,
    },
  }

  exec { 'pbis-apt-get-update':
    command => '/usr/bin/apt-get update',
    refreshonly => true,
  }

  package { 'pbis-open' :
    ensure => installed,
    provider => apt,
#    source => '/root/pbis-open-8.3.0.3287.linux.x86_64.deb',
  }

  $joindomain = "#!/bin/bash
    domainjoin-cli join $domain \$1 \$2       
    cd /opt/pbis/bin/  
    ./config UserDomainPrefix $domain
    ./config AssumeDefaultDomain true
    ./config LoginShellTemplate /bin/bash
    ./config HomeDirTemplate %H/%U
    ./config RequireMembershipOf '$domain\domain^users'
    "

  file { '/usr/local/bin/join-domain.sh' :
    ensure => present,   
    owner => root,
    group => root,
    mode => '0544',
    content => "$joindomain"
  }
}

join.pp
class pbis::join inherits pbis {

$sudofile="#
# This file MUST be edited with the visudo command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
Defaults        env_reset
Defaults        mail_badpass
Defaults        secure_path=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"
# Host alias specification
# User alias specification
# Cmnd alias specification
# User privilege specification
root    ALL=(ALL:ALL) ALL
# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL
# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL
#Domain Admins
%$domain\\\\$sudogroup        ALL=(ALL:ALL) ALL
# See sudoers(5) for more information on #include directives:
#includedir /etc/sudoers.d
"
  file { '/etc/sudoers' :
    ensure => present,
    owner => root,
    group => root,
    mode => '0440',
    content => "$sudofile"
  }

  exec { 'join':
    command => "/usr/local/bin/join-domain.sh $ldapbindaccount $ldapbindpassword",
    require => Class['pbis::install'],
    unless => "/bin/echo $(/usr/bin/domainjoin-cli query)|/bin/grep $domain",
  }
}

Simple puppet class for a squid server with allow all in conf


install.pp

class squid::install inherits squid {
  include apt

  exec { 'squid-update-apt':
    command => '/usr/bin/apt-get update',
    refreshonly => true,
  }

  package { 'squid3' :
    require => Class['squid::setup'],  
    ensure => installed,
    provider => apt,
  }


}

setup.pp

class squid::setup inherits squid {

  $squidconf="acl SSL_ports port 443
acl Safe_ports port 80          # http
acl Safe_ports port 21          # ftp
acl Safe_ports port 443         # https
acl Safe_ports port 70          # gopher
acl Safe_ports port 210         # wais
acl Safe_ports port 1025-65535  # unregistered ports
acl Safe_ports port 280         # http-mgmt
acl Safe_ports port 488         # gss-http
acl Safe_ports port 591         # filemaker
acl Safe_ports port 777         # multiling http
acl CONNECT method CONNECT
http_access allow all
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow localhost manager
http_access deny manager
http_access allow localhost
http_access deny all
http_port 3128
coredump_dir /var/spool/squid3
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern -i (/cgi-bin/|\?) 0     0%      0
refresh_pattern (Release|Packages(.gz)*)$      0       20%     2880
refresh_pattern .               0       20%     4320
"

  file { '/etc/squid3/squid.conf' :
    notify => Service['squid3'],
    ensure => present,
    owner => root,
    group => root,
    mode => '0644',
    content => $squidconf
  }
}

init.pp
class squid (
  $example = $squid::params::example,
) inherits squid::params {
}

params.pp
class squid::params {
  $example = 'example1'
}

Friday, March 25, 2016

Way more fun AD C# functions...

This goes well with my last post!
     public void UnlockUser(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             if (usr.IsAccountLockedOut())  
             {  
               usr.UnlockAccount();  
               MessageBox.Show(usr.DisplayName + "'s account unlocked");  
             }  
             else  
             {  
               MessageBox.Show(usr.DisplayName + "'s account not locked, " + "last logon at " + usr.LastLogon.ToString() + ", " + "user has " + usr.BadLogonCount.ToString() + " bad password attempts.");  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
         }  
       }  
     }  
     public void ResetUsersPassword(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             DialogResult yesNoDialog;  
             string resetPasswordString = "Are you sure you want to reset " + usr.DisplayName + "'s password?";  
             yesNoDialog = MessageBox.Show(resetPasswordString, "Password Reset", MessageBoxButtons.YesNo);  
             if (yesNoDialog == DialogResult.Yes)  
             {  
               usr.SetPassword("Password1");  
               usr.ExpirePasswordNow();  
               MessageBox.Show(usr.DisplayName + "'s password has been reset.");  
             }  
             if (usr.IsAccountLockedOut())  
             {  
               usr.UnlockAccount();  
               MessageBox.Show(usr.DisplayName + "'s account unlocked");  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
         }  
       }  
     }  
     public void PsLoggedOn(string psLoggedOnArgs, string pcname)  
     {  
       if (PcNameIsNotNullOrVoid(pcname))  
       {  
         DialogResult yesNoDialog;  
         yesNoDialog = MessageBox.Show("Would you like to run psLoggedIn also?", "psLoggedOn?", MessageBoxButtons.YesNo);  
         if (yesNoDialog == DialogResult.Yes)  
         {  
           try  
           {  
             System.Diagnostics.Process proc = new System.Diagnostics.Process();  
             proc.EnableRaisingEvents = false;  
             proc.StartInfo.FileName = "psLoggedOn";  
             proc.StartInfo.UseShellExecute = false;  
             if (PcNameIsNotNullOrVoid(pcname))  
             {  
               proc.StartInfo.Arguments = " " + backslashes + pcname + " " + psLoggedOnArgs;  
             }  
             proc.StartInfo.RedirectStandardOutput = true;  
             proc.Start();  
             //string tasklist = proc.StandardOutput.ReadToEnd();  
             MessageBox.Show(proc.StandardOutput.ReadToEnd());  
             //proc.WaitForExit();  
           }  
           catch (Exception tasklistException)  
           {  
             MessageBox.Show(tasklistException.Message);  
           }  
         }  
       }  
     }  
     public List<string> GetGroups(string user, string fQDomainName, string ou)  
     {  
       List<string> groupList = new List<string>();  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             var groups = usr.GetGroups();  
             foreach (Object gr in groups)  
             {  
               groupList.Add(gr.ToString());  
               //MessageBox.Show(gr.ToString());  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
           return groupList;  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
           return groupList;  
         }  
       }  
       return groupList;  
     }  
     public void DisableAccount(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             DialogResult yesNoDialog;  
             string disableAccountString = "Are you sure you want to disable " + usr.DisplayName + "'s account?";  
             string userInfoString = "\n\nUSER INFO:\n" + "\nName:\t\t" + usr.DisplayName + "\nTitle:\t\t" + usr.title + "\nDepartment\t" + usr.department + "\nCompany:\t" + usr.company + "\nOffice:\t\t" + usr.office + "\nEmail:\t\t" + usr.EmailAddress + "\nLogin:\t\t" + usr.SamAccountName + "\nDescription:\t" + usr.Description;  
             yesNoDialog = MessageBox.Show(disableAccountString + userInfoString, "Disable Account?", MessageBoxButtons.YesNo);  
             if (yesNoDialog == DialogResult.Yes)  
             {  
               if (usr.Enabled == true)  
               {  
                 usr.Enabled = false;  
                 usr.SetPassword("sdP32*&^kna0^d$");  
                 string toDay = DateTime.Today.Date.ToString();  
                 usr.Description = "disabled " + toDay.Substring(0, toDay.IndexOf(" ")) + " " + Environment.UserName;  
                 usr.Save();  
                 MessageBox.Show(usr.DisplayName + "'s account has been disabled");  
                 string removeGroupsString = "Would you like to remove " + usr.DisplayName + " from all AD groups and move to Disabled Users OU?";  
                 yesNoDialog = MessageBox.Show(removeGroupsString, "Remove AD Groups?", MessageBoxButtons.YesNo);  
                 if (yesNoDialog == DialogResult.Yes)  
                 {  
                   RemoveUserFromAllGroups(user, fQDomainName, ou);  
                   MoveToDisabledUsersOU(usr.DistinguishedName, disabledUsersOU);  
                   MessageBox.Show(usr.DisplayName + " has been removed from all AD groups and moved to Disabled Users.");  
                 }  
                 string deleteTSProfilesString = "Would you like to delete " + usr.DisplayName + "'s profiles from all the Terminal Servers?";  
                 yesNoDialog = MessageBox.Show(deleteTSProfilesString, "Delete TS Profiles?", MessageBoxButtons.YesNo);  
                 if (yesNoDialog == DialogResult.Yes)  
                 {  
                   DiskTools dt = new DiskTools();  
                   dt.DeleteTSProfiles(usr.SamAccountName.ToLower());  
                   MessageBox.Show(usr.DisplayName + "'s profiles are being deleted from all terminal servers.");  
                 }  
               }  
               else  
               {  
                 MessageBox.Show(usr.DisplayName + "'s account is already disabled");  
               }  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
         }  
       }  
       else  
       {  
         MessageBox.Show("User not found");  
       }  
     }  
     public void DisableAccountTemp(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             DialogResult yesNoDialog;  
             string disableAccountString = "Are you sure you want to temporarily disable " + usr.DisplayName + "'s account?";  
             string userInfoString = "\n\nUSER INFO:\n" + "\nName:\t\t" + usr.DisplayName + "\nTitle:\t\t" + usr.title + "\nDepartment\t" + usr.department + "\nCompany:\t" + usr.company + "\nOffice:\t\t" + usr.office + "\nEmail:\t\t" + usr.EmailAddress + "\nLogin:\t\t" + usr.SamAccountName + "\nDescription:\t" + usr.Description;  
             yesNoDialog = MessageBox.Show(disableAccountString + userInfoString, "Temporarily Disable Account?", MessageBoxButtons.YesNo);  
             if (yesNoDialog == DialogResult.Yes)  
             {  
               if (usr.Enabled == true)  
               {  
                 usr.Enabled = false;  
                 usr.SetPassword("sdP32*&^kna0^d$");  
                 string toDay = DateTime.Today.Date.ToString();  
                 usr.Description = "disabled " + toDay.Substring(0, toDay.IndexOf(" ")) + " " + Environment.UserName;  
                 usr.Save();  
                 MessageBox.Show(usr.DisplayName + "'s account has been disabled");  
               }  
               else  
               {  
                 MessageBox.Show(usr.DisplayName + "'s account is already disabled");  
               }  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
         }  
       }  
     }  
     public void EnableAccount(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             DialogResult yesNoDialog;  
             string enableAccountString = "Are you sure you want to enable " + usr.DisplayName + "'s account?";  
             string userInfoString = "\n\nUSER INFO:\n" + "\nName:\t\t" + usr.DisplayName + "\nTitle:\t\t" + usr.title + "\nDepartment\t" + usr.department + "\nCompany:\t" + usr.company + "\nOffice:\t\t" + usr.office + "\nEmail:\t\t" + usr.EmailAddress + "\nLogin:\t\t" + usr.SamAccountName + "\nDescription:\t" + usr.Description;  
             yesNoDialog = MessageBox.Show(enableAccountString + userInfoString, "Enable Account?", MessageBoxButtons.YesNo);  
             if (yesNoDialog == DialogResult.Yes)  
             {  
               if (usr.Enabled == false)  
               {  
                 usr.Enabled = true;  
                 //usr.SetPassword("Password1");  
                 string toDay = DateTime.Today.Date.ToString();  
                 usr.Description = "enabled " + toDay.Substring(0, toDay.IndexOf(" ")) + " " + Environment.UserName;  
                 usr.Save();  
                 MessageBox.Show(usr.DisplayName + "'s account has been enabled");  
               }  
               else  
               {  
                 MessageBox.Show(usr.DisplayName + "'s account is already enabled");  
               }  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
         }  
       }  
     }  
     public void AddUserToGroup(string user, string fQDomainName, string ou, string groupName)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName))  
           {  
             UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
             GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);  
             group.Members.Add(usr);  
             group.Save();  
           }  
         }  
         catch (Exception e)  
         {  
           MessageBox.Show(e.Message);  
         }  
       }  
     }  
     public void RemoveUserFromGroup(string user, string fQDomainName, string ou, string groupName)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName))  
           {  
             UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
             GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);  
             group.Members.Remove(usr);  
             group.Save();  
           }  
         }  
         catch (Exception e)  
         {  
           MessageBox.Show(e.Message);  
         }  
       }  
     }  
     public void RemoveUserFromAllGroups(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           List<string> groupList = GetGroups(user, fQDomainName, ou);  
           foreach (object group in groupList)  
           {  
             if (!string.Equals(group.ToString(), "Domain Users"))  
             {  
               RemoveUserFromGroup(user, fQDomainName, ou, group.ToString());  
             }  
           }  
         }  
         catch (Exception e)  
         {  
           MessageBox.Show(e.Message);  
         }  
       }  
     }  
     public void MoveToDisabledUsersOU(string userDN, string newOU)  
     {  
       //Move an object from one ou to another  
       DirectoryEntry eLocation = new DirectoryEntry("LDAP://" + userDN);  
       DirectoryEntry nLocation = new DirectoryEntry("LDAP://" + newOU);  
       string newName = eLocation.Name;  
       eLocation.MoveTo(nLocation, newName);  
       nLocation.Close();  
       eLocation.Close();  
     }  
     public string RandomPassword(int passwordLength)  
     {  
       string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";  
       char[] chars = new char[passwordLength];  
       Random rd = new Random();  
       for (int i = 0; i < passwordLength; i++)  
       {  
         chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];  
       }  
       return new string(chars);  
     }  
     public void PopulateADLocations(string fQDomainName, string ou)  
     {  
       foreach (string location in Properties.Settings.Default.ADLocations)  
       {  
         //populations AD PhysicalDeliveryOfficeName field based on group membership  
         RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();  
         Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);  
         myRunSpace.Open();  
         Pipeline ps = myRunSpace.CreatePipeline();  
         Command getADGroupMemberCommand = new Command("Get-ADGroupMember");  
         CommandParameter getADGroupMemberArgs = new CommandParameter("Identity", location);  
         getADGroupMemberCommand.Parameters.Add(getADGroupMemberArgs);  
         ps.Commands.Add(getADGroupMemberCommand);  
         Command setADUserCommand = new Command("Set-ADUser");  
         CommandParameter setADUserArgs = new CommandParameter("Office", location);  
         setADUserCommand.Parameters.Add(setADUserArgs);  
         ps.Commands.Add(setADUserCommand);  
         // Call the PowerShell.Invoke() method to run the   
         // commands of the pipeline.  
         StringBuilder output = new StringBuilder();  
         foreach (PSObject result in ps.Invoke())  
         {  
           output.AppendLine(result.ToString());  
         } // End foreach.  
         MessageBox.Show(output.ToString() + location + " complete.");  
         myRunSpace.Dispose();  
       }  
     }  
     public void PopulateADTitles(string fQDomainName, string ou)  
     {  
       foreach (string title in Properties.Settings.Default.ADTitles)  
       {  
         //populations AD Title field based on group membership  
         RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();  
         Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);  
         myRunSpace.Open();  
         Pipeline ps = myRunSpace.CreatePipeline();  
         Command getADGroupMemberCommand = new Command("Get-ADGroupMember");  
         CommandParameter getADGroupMemberArgs = new CommandParameter("Identity", title);  
         getADGroupMemberCommand.Parameters.Add(getADGroupMemberArgs);  
         ps.Commands.Add(getADGroupMemberCommand);  
         Command setADUserCommand = new Command("Set-ADUser");  
         CommandParameter setADUserArgs = new CommandParameter("Title", title.TrimEnd('s'));  
         setADUserCommand.Parameters.Add(setADUserArgs);  
         ps.Commands.Add(setADUserCommand);  
         // Call the PowerShell.Invoke() method to run the   
         // commands of the pipeline.  
         StringBuilder output = new StringBuilder();  
         foreach (PSObject result in ps.Invoke())  
         {  
           output.AppendLine(result.ToString());  
         } // End foreach.  
         MessageBox.Show(output.ToString() + title + " complete.");  
         myRunSpace.Dispose();  
       }  
    }  

Get Some AD info in C#

     private void getUsersADInfoToolStripMenuItem_Click(object sender, EventArgs e)  
     {  
       UserTools ut = new UserTools();  
       var combinedList = new List<string>();  
       combinedList.AddRange(ut.GetADUserInfo(profileNameBox.Text, fullyQualifiedDomainName, organizationalUnit));  
       combinedList.Add("");  
       combinedList.Add("GROUP MEMBERSHIPS: ");  
       combinedList.AddRange(ut.GetGroups(profileNameBox.Text, fullyQualifiedDomainName, organizationalUnit));  
       //ListBoxForm.ShowList(combinedList, "AD Info for " + ut.GetFullName(profileNameBox.Text, fullyQualifiedDomainName, organizationalUnit));  
       TextBoxForm.ShowText(string.Join<string>(Environment.NewLine, combinedList), "AD Info for " + ut.GetFullName(profileNameBox.Text, fullyQualifiedDomainName, organizationalUnit));  
     }  
     public List<string> GetADUserInfo(string user, string fQDomainName, string ou)  
     {  
       List<string> resultList = new List<string>();  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             resultList.Add("NAME:\t\t" + usr.DisplayName);  
             resultList.Add("TITLE:\t\t" + usr.title);  
             resultList.Add("DEPARTMENT:\t" + usr.department);  
             resultList.Add("COMPANY:\t" + usr.company);  
             resultList.Add("OFFICE:\t\t" + usr.office);  
             resultList.Add("EMAIL:\t\t" + usr.EmailAddress);  
             resultList.Add("LOGIN:\t\t" + usr.SamAccountName);  
             resultList.Add("PROFILE:\t" + usr.HomeDirectory);  
             if(!string.IsNullOrEmpty(usr.Description))  
             {  
               resultList.Add("DESCRIPTION:\t" + usr.Description);  
             }  
             usr.Dispose();  
           }  
           else resultList.Add("");  
           ctx.Dispose();  
           return resultList;  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
           resultList.Add("");  
           return resultList;  
         }  
       }  
       else resultList.Add("");  
       return resultList;  
     }  
     public string GetSamAccountName(string user, string fQDomainName, string ou)  
     {  
       string samAccountName;  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             samAccountName = usr.SamAccountName.ToString();  
             usr.Dispose();  
           }  
           else samAccountName = "";  
           ctx.Dispose();  
           return samAccountName;  
         }  
         catch (Exception getSamAccountNameException)  
         {  
           MessageBox.Show(getSamAccountNameException.Message);  
           samAccountName = "";  
           return samAccountName;  
         }  
       }  
       else samAccountName = "";  
       return samAccountName;  
     }  
     public string GetFullName(string user, string fQDomainName, string ou)  
     {  
       string fullName;  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             fullName = usr.Name.ToString();  
             usr.Dispose();  
           }  
           else fullName = "";  
           ctx.Dispose();  
           return fullName;  
         }  
         catch (Exception getFullNameException)  
         {  
           MessageBox.Show(getFullNameException.Message);  
           fullName = "";  
           return fullName;  
         }  
       }  
       else fullName = "";  
       return fullName;  
     }  
     public string GetEmailAddress(string user, string fQDomainName, string ou)  
     {  
       string emailAddress;  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             emailAddress = usr.EmailAddress.ToString();  
             usr.Dispose();  
           }  
           else emailAddress = "";  
           ctx.Dispose();  
           return emailAddress;  
         }  
         catch (Exception getEmailException)  
         {  
           MessageBox.Show(getEmailException.Message);  
           emailAddress = "";  
           return emailAddress;  
         }  
       }  
       else emailAddress = "";  
       return emailAddress;  
     }  
     public string GetManager(string user, string fQDomainName, string ou)  
     {  
       string managerName;  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             managerName = GetFullName(usr.manager, fullyQualifiedDomainName, organizationalUnit);  
             usr.Dispose();  
           }  
           else managerName = "";  
           ctx.Dispose();  
           return managerName;  
         }  
         catch (Exception getManager)  
         {  
           MessageBox.Show(getManager.Message);  
           managerName = "";  
           return managerName;  
         }  
       }  
       else managerName = "";  
       return managerName;  
     }  
     public string GetCompany(string user, string fQDomainName, string ou)  
     {  
       string company;  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             company = usr.company.ToString();  
             usr.Dispose();  
           }  
           else company = "";  
           ctx.Dispose();  
           return company;  
         }  
         catch  
         {  
           MessageBox.Show("Warning: Company not set!");  
           company = "";  
           return company;  
         }  
       }  
       else company = "";  
       return company;  
     }  

Wednesday, March 23, 2016

Restart a remote computer's print spooler and delete it's print jobs via C#

Custom functions not included PcNameIsNotNullOrVoid(pcname), CleanPCName(pcname), variables such as cshare, etc. Utilizes windows built in psservice.exe.
     public void RestartTheSpooler(string pcname)  
     {  
       try  
       {  
         StopTheSpooler(pcname);  
         Thread.Sleep(1500);  
         //Thread stopSpoolThread = new Thread(new ThreadStart(stopTheSpooler));  
         //stopSpoolThread.Start();  
         DeletePrintJobs(pcname);  
         StartTheSpooler(pcname);  
       }  
       catch (Exception spoolerException)  
       {  
         MessageBox.Show(spoolerException.Message);  
       }  
     }  
     public void StopTheSpooler(string pcname)  
     {  
       pcname = CleanPCName(pcname);  
       //stop spooler  
       System.Diagnostics.Process stopspooler = new System.Diagnostics.Process();  
       stopspooler.EnableRaisingEvents = false;  
       stopspooler.StartInfo.FileName = "psservice";  
       if (PcNameIsNotNullOrVoid(pcname))  
       {  
         stopspooler.StartInfo.Arguments = backslashes + pcname + " stop spooler";  
         stopspooler.Start();  
         stopspooler.WaitForExit();  
       }  
     }  
     public void DeletePrintJobs(string pcname)  
     {  
       //delete print jobs  
       if (PcNameIsNotNullOrVoid(pcname))  
       {  
         if (Directory.Exists(backslashes + pcname + @"\" + cshare + @"\windows\system32\spool\printers\"))  
         {  
           Directory.Delete(backslashes + pcname + @"\" + cshare + @"\windows\system32\spool\printers", true);  
         }  
         Directory.CreateDirectory(backslashes + pcname + @"\" + cshare + @"\windows\system32\spool\PRINTERS");  
       }  
     }  
     public void StartTheSpooler(string pcname)  
     {  
       //start spooler  
       System.Diagnostics.Process startspooler = new System.Diagnostics.Process();  
       startspooler.EnableRaisingEvents = false;  
       startspooler.StartInfo.FileName = "psservice";  
       if (PcNameIsNotNullOrVoid(pcname))  
       {  
         startspooler.StartInfo.Arguments = backslashes + pcname + " start spooler";  
         startspooler.Start();  
       }  
     }  

Wednesday, March 9, 2016

Puppet install.pp for PBIS-Open

An install.pp in the works for PowerBroker that uses the official ppa. Haven't gotten around to finishing my join.pp yet, will post when I do.
 class optivlabsdomain::install inherits optivlabsdomain {  
  include apt  
  apt::source { 'powerbroker':  
   comment => 'Powerbroker Identity Services',  
   location => 'http://repo.pbis.beyondtrust.com/apt',  
   release => 'pbiso',  
   repos  => 'main',  
   pin   => '500',  
   key   => {  
    'source'   => 'http://repo.pbis.beyondtrust.com/yum/RPM-GPG-KEY-pbis',  
    'id'     => 'BE7FF72A6B7C8A9FAE061F4F2E52CD89C9CEECEF',  
   },  
   include => {  
    'deb' => true,  
   },  
  }  
  exec { 'apt-get update':  
   command => '/usr/bin/apt-get update',  
   refreshonly => true,  
 #  unless => "/usr/local/bin/pbis-installed.sh",    
  }  
  package { 'pbis-open' :  
   ensure => installed,  
   provider => apt,  
  }  
 # file { '/root/pbis-open-8.3.0.3287.linux.x86_64.deb.sh' :  
 #  ensure => present,  
 #  owner => root,  
 #  group => root,  
 #  mode => '0544',  
 #  source => 'puppet:///files/pbis-open-8.3.0.3287.linux.x86_64.deb.sh'  
 # }  
 # file { '/usr/local/bin/pbis-installed.sh' :  
 #  ensure => present,  
 #  content => "$(dpkg-query -W -f='\${status}' pbis-open 2>/dev/null | grep -c 'ok installed')'",  
 #  mode => '0544',  
 #  owner => root,  
 #  group => root,  
 # }  
 # exec { 'install.sh':  
 #  command => '/root/pbis-open-8.3.0.3287.linux.x86_64.deb.sh install',  
 #  refreshonly => true,  
 #  unless => "/usr/local/bin/pbis-installed.sh",    
 # }  
 }