This script is used as custom scheduler
Run as Logged in User
#To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('parameterName') with that parameter's name
user = 'Yes' # Provide 'Yes' to display else provide 'No'
host = 'Yes'
cpu = 'Yes'
ram = 'Yes'
os_version = 'Yes'
ip_address_ethernet = 'Yes'
ip_address_wifi = 'Yes'
subnetmask_ethernet = 'Yes'
subnetmask_wifi = 'Yes'
default_gateway_ethernet = 'Yes'
default_gateway_wifi = 'Yes'
import ctypes
import getpass
import platform
import re
from subprocess import PIPE, Popen
mask_wifi = ''
mask_ethernet = ''
gateway_wifi = ''
gateway_ethernet = ''
registry_key=r'HKEY_CURRENT_USER\Control Panel\Desktop'
reg_field="WallPaper"
import os
import _winreg
reg_key=registry_key.split(os.sep)
key = getattr(_winreg,reg_key[0])
subkey = _winreg.OpenKey(key, os.sep.join(reg_key[1:]), 0, _winreg.KEY_ALL_ACCESS)
(wall_path, type) = _winreg.QueryValueEx(subkey,reg_field)
def ecmd(command):
class disable_file_system_redirection:
_disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
_revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
def __enter__(self):
self.old_value = ctypes.c_long()
self.success = self._disable(ctypes.byref(self.old_value))
def __exit__(self, type, value, traceback):
if self.success:
self._revert(self.old_value)
with disable_file_system_redirection():
obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
out, err = obj.communicate()
ret=obj.returncode
if ret==0:
if out:
return out.strip()
else:
return ret
else:
if err:
return err.strip()
else:
return ret
def get_interfaces():
output = ecmd(r'ipconfig /all')
lines = output.splitlines()
lines = filter(lambda x: x, lines)
ip_address = ''
subnet_mask = ''
default_gateway = ''
name = ''
for line in lines:
# -------------
# Interface Name
is_interface_name = re.match(r'^[a-zA-Z0-9].*:$', line)
if is_interface_name:
# Check if there's previews values, if so - yield them
if name and ip_address:
yield {
"ip_address": ip_address,
"subnet_mask": subnet_mask,
"default_gateway": default_gateway,
"name": name,
}
ip_address = ''
subnet_mask = ''
default_gateway = ''
name = line.rstrip(':')
line = line.strip().lower()
if ':' not in line:
continue
value = line.split(':')[-1]
value = value.strip()
is_ip_address = not ip_address and re.match(r'ipv4 address|autoconfiguration ipv4 address|ip address', line)
if is_ip_address:
ip_address = value
ip_address = ip_address.replace('(preferred)', '')
ip_address = ip_address.strip()
is_subnet_mask = not subnet_mask and re.match(r'subnet mask', line)
if is_subnet_mask:
subnet_mask = value
subnet_mask = subnet_mask.strip()
is_default_gateway = not default_gateway and re.match(r'default gateway', line)
if is_subnet_mask:
default_gateway = value
default_gateway = default_gateway.strip()
if name and ip_address:
yield {
"ip_address": ip_address,
"subnet_mask": subnet_mask,
"default_gateway": default_gateway,
"name": name,
}
if __name__ == '__main__':
for interface in get_interfaces():
if interface.get('name') == 'Wireless LAN adapter Wi-Fi':
mask_wifi = interface.get('subnet_mask')
gateway_wifi = interface.get('default_gateway')
cmd = ecmd(r'ipconfig')
ipaddress=re.findall('IPv4 Address(.*)',cmd)
mask=re.findall('Subnet Mask(.*)',cmd)
gateway=re.findall('Default Gateway(.*)',cmd)
mask_ethernet = " ".join(mask[0].split(':')[1].split())if len(mask) else ''
gateway_ethernet = " ".join(gateway[0].split(':')[1].split()) if len(gateway) else ''
ps_content=r'''
$font="Input"
# Font size in pixels
$size=10.0
# spacing in pixels
$textPaddingLeft = 5
$textPaddingTop = 5
$textItemSpace = 10
#TODO: Line-height multiplyer of the $size in pixels.
#$lineHeight = 1.80
$wallpaperImagesSource = "$Env:USERPROFILE\Pictures\wallpaper"
$wallpaperImageOutput = "$Env:USERPROFILE"
# Get local info to write out to wallpaper
$os = Get-CimInstance Win32_OperatingSystem
$cpu = (Get-WmiObject Win32_Processor).Name.Replace("Intel(R) Core(TM) ", "")
$BootTimeSpan = (New-TimeSpan -Start $os.LastBootUpTime -End (Get-Date))
$ip = (Get-NetIPAddress | Where-Object {$_.InterfaceAlias -eq "Ethernet" -and $_.AddressFamily -eq "IPv4"}).IPAddress
$ipwifi = (Get-NetIPAddress | Where-Object {$_.InterfaceAlias -eq "Wi-Fi" -and $_.AddressFamily -eq "IPv4"}).IPAddress
$gateway = (Get-NetIPAddress | Where-Object {$_.InterfaceAlias -eq "Wi-Fi" -and $_.AddressFamily -eq "Gateway"}).IPAddress
$o = ([ordered]@{})
$user_c = '%s'
$host_c = '%s'
$cpu_c = '%s'
$ram_c = '%s'
$os_c = '%s'
$ip_ether_c = '%s'
$ip_wifi_c = '%s'
$mask_ether_c = '%s'
$mask_wifi_c = '%s'
$gateway_ether_c = '%s'
$gateway_wifi_c = '%s'
If ( $user_c -eq 'Yes'){
$o.Add('User', $os.RegisteredUser)
}
If ( $host_c -eq 'Yes'){
$o.Add('Host',"$($os.CSName)")
}
If ( $cpu_c -eq 'Yes'){
$o.Add('CPU', $cpu)
}
If ( $ram_c -eq 'Yes'){
$o.Add('RAM', "$([math]::round($os.TotalVisibleMemorySize / 1MB))GB")
}
If ( $os_c -eq 'Yes'){
$o.Add('OS', "$($os.Caption) `n$($os.OSArchitecture), $($os.Version)")
}
If ( $ip_ether_c -eq 'Yes'){
$o.Add('IP (Ethernet)', $ip)
}
If ( $mask_ether_c -eq 'Yes'){
$o.Add('Subnet Mask (Ethernet)', '%s')
}
If ( $gateway_ether_c -eq 'Yes'){
$o.Add('Default Gateway (Ethernet)', '%s')
}
If ( $ip_wifi_c -eq 'Yes'){
$o.Add('IP (WI-FI)', $ipwifi)
}
If ( $mask_wifi_c -eq 'Yes'){
$o.Add('Subnet Mask (WI-FI)', '%s')
}
If ( $gateway_wifi_c -eq 'Yes'){
$o.Add('Default Gateway (WI-FI)', '%s')
}
$user_c
$host_c
# original src: https://p0w3rsh3ll.wordpress.com/2014/08/29/poc-tatoo-the-background-of-your-virtual-machines/
Function New-ImageInfo {
# src: https://github.com/fabriceleal/Imagify/blob/master/imagify.ps1
param(
[Parameter(Mandatory=$True, Position=1)]
[object] $data,
[Parameter(Mandatory=$True)]
[string] $in,
[string] $font="Courier New",
[float] $size=12.0,
#[float] $lineHeight = 1.4,
[float] $textPaddingLeft = 0,
[float] $textPaddingTop = 0,
[float] $textItemSpace = 0,
[string] $out="out.png"
)
[system.reflection.assembly]::loadWithPartialName('system') | out-null
[system.reflection.assembly]::loadWithPartialName('system.drawing') | out-null
[system.reflection.assembly]::loadWithPartialName('system.drawing.imaging') | out-null
[system.reflection.assembly]::loadWithPartialName('system.windows.forms') | out-null
$foreBrush = [System.Drawing.Brushes]::White
$backBrush = new-object System.Drawing.SolidBrush([System.Drawing.Color]::FromArgb(192, 0, 0, 0))
# Create font
$nFont = new-object system.drawing.font($font, $size, [System.Drawing.GraphicsUnit]::Pixel)
# Create Bitmap
$SR = [System.Windows.Forms.Screen]::AllScreens | Where Primary | Select -ExpandProperty Bounds | Select Width,Height
echo $SR >> "$wallpaperImageOutput\wallpaper.log"
$background = new-object system.drawing.bitmap($SR.Width, $SR.Height)
$bmp = new-object system.drawing.bitmap -ArgumentList $in
# Create Graphics
$image = [System.Drawing.Graphics]::FromImage($background)
# Paint image's background
$rect = new-object system.drawing.rectanglef(0, 0, $SR.width, $SR.height)
$image.FillRectangle($backBrush, $rect)
# add in image
$topLeft = new-object System.Drawing.RectangleF(0, 0, $SR.Width, $SR.Height)
$image.DrawImage($bmp, $topLeft)
# Draw string
$strFrmt = new-object system.drawing.stringformat
$strFrmt.Alignment = [system.drawing.StringAlignment]::Near
$strFrmt.LineAlignment = [system.drawing.StringAlignment]::Near
$taskbar = [System.Windows.Forms.Screen]::AllScreens
$taskbarOffset = $taskbar.Bounds.Height - $taskbar.WorkingArea.Height
# first get max key & val widths
$maxKeyWidth = 0
$maxValWidth = 0
$textBgHeight = 0 + $taskbarOffset
$textBgWidth = 0
# a reversed ordered collection is used since it starts from the bottom
$reversed = [ordered]@{}
foreach ($h in $data.GetEnumerator()) {
$valString = "$($h.Value)"
$valFont = New-Object System.Drawing.Font($font, $size, [System.Drawing.FontStyle]::Regular)
$valSize = [system.windows.forms.textrenderer]::MeasureText($valString, $valFont)
$maxValWidth = [math]::Max($maxValWidth, $valSize.Width)
$keyString = "$($h.Name): "
$keyFont = New-Object System.Drawing.Font($font, $size, [System.Drawing.FontStyle]::Bold)
$keySize = [system.windows.forms.textrenderer]::MeasureText($keyString, $keyFont)
$maxKeyWidth = [math]::Max($maxKeyWidth, $keySize.Width)
$maxItemHeight = [math]::Max($valSize.Height, $keySize.Height)
$textBgHeight += ($maxItemHeight + $textItemSpace)
$reversed.Insert(0, $h.Name, $h.Value)
}
$textBgWidth = $maxKeyWidth + $maxValWidth
$textBgX = $SR.Width - ($textBgWidth + $textPaddingLeft)
$textBgY = $SR.Height - ($textBgHeight + $textPaddingTop)
$textBgRect = New-Object System.Drawing.RectangleF($textBgX, $textBgY, $textBgWidth, $textBgHeight)
$image.FillRectangle($backBrush, $textBgRect)
echo $textBgRect >> "$wallpaperImageOutput\wallpaper.log"
$i = 0
$cumulativeHeight = $SR.Height - $taskbarOffset
foreach ($h in $reversed.GetEnumerator()) {
$valString = "$($h.Value)"
$valFont = New-Object System.Drawing.Font($font, $size, [System.Drawing.FontStyle]::Regular)
$valSize = [system.windows.forms.textrenderer]::MeasureText($valString, $valFont)
$keyString = "$($h.Name): "
$keyFont = New-Object System.Drawing.Font($font, $size, [System.Drawing.FontStyle]::Bold)
$keySize = [system.windows.forms.textrenderer]::MeasureText($keyString, $keyFont)
echo $valString >> "$wallpaperImageOutput\wallpaper.log"
echo $keyString >> "$wallpaperImageOutput\wallpaper.log"
$maxItemHeight = [math]::Max($valSize.Height, $keySize.Height) + $textItemSpace
$valX = $SR.Width - $maxValWidth
$valY = $cumulativeHeight - $maxItemHeight
$keyX = $valX - $maxKeyWidth
$keyY = $valY
$valRect = New-Object System.Drawing.RectangleF($valX, $valY, $maxValWidth, $valSize.Height)
$keyRect = New-Object System.Drawing.RectangleF($keyX, $keyY, $maxKeyWidth, $keySize.Height)
$cumulativeHeight = $valRect.Top
$image.DrawString($keyString, $keyFont, $foreBrush, $keyRect, $strFrmt)
$image.DrawString($valString, $valFont, $foreBrush, $valRect, $strFrmt)
$i++
}
# Close Graphics
$image.Dispose();
# Save and close Bitmap
$background.Save($out, [system.drawing.imaging.imageformat]::Png);
$background.Dispose();
$bmp.Dispose();
# Output file
Get-Item -Path $out
}
Function Set-Wallpaper {
# src: http://powershell.com/cs/blogs/tips/archive/2014/01/10/change-desktop-wallpaper.aspx
param(
[Parameter(Mandatory=$true)]
$Path,
[ValidateSet('Center', 'Stretch', 'Fill', 'Tile', 'Fit')]
$Style = 'Center'
)
#TODO: there in't a better way to do this than inline C#?
Add-Type @"
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace Wallpaper
{
public enum Style : int
{
Center, Stretch, Fill, Fit, Tile
}
public class Setter {
public const int SetDesktopWallpaper = 20;
public const int UpdateIniFile = 0x01;
public const int SendWinIniChange = 0x02;
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int SystemParametersInfo (int uAction, int uParam, string lpvParam, int fuWinIni);
public static void SetWallpaper ( string path, Wallpaper.Style style )
{
SystemParametersInfo( SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange );
RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);
switch( style )
{
case Style.Tile :
key.SetValue(@"WallpaperStyle", "0") ;
key.SetValue(@"TileWallpaper", "1") ;
break;
case Style.Center :
key.SetValue(@"WallpaperStyle", "0") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Stretch :
key.SetValue(@"WallpaperStyle", "2") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Fill :
key.SetValue(@"WallpaperStyle", "10") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Fit :
key.SetValue(@"WallpaperStyle", "6") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
}
key.Close();
}
}
}
"@
[Wallpaper.Setter]::SetWallpaper( $Path, $Style )
}
echo $o > "$wallpaperImageOutput\wallpaper.log"
# get random wallpaper from a folder full of images
# create wallpaper image and save it in user profile
$WallPaper = New-ImageInfo -data $o -in "%s" -out "$wallpaperImageOutput\wallpaper.png" -font $font -size $size -textPaddingLeft $textPaddingLeft -textPaddingTop $textPaddingTop -textItemSpace $textItemSpace #-lineHeight $lineHeight
echo $WallPaper.FullName >> "$wallpaperImageOutput\wallpaper.log"
# update wallpaper for logged in user
Set-Wallpaper -Path $WallPaper.FullName
'''%(user,host,cpu,ram,os_version,ip_address_ethernet,ip_address_wifi,subnetmask_ethernet,subnetmask_wifi,default_gateway_ethernet,default_gateway_wifi, mask_ethernet, gateway_ethernet, mask_wifi, gateway_wifi, wall_path)
def ecmd(command):
import ctypes
from subprocess import PIPE, Popen
class disable_file_system_redirection:
_disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
_revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
def __enter__(self):
self.old_value = ctypes.c_long()
self.success = self._disable(ctypes.byref(self.old_value))
def __exit__(self, type, value, traceback):
if self.success:
self._revert(self.old_value)
with disable_file_system_redirection():
obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
out, err = obj.communicate()
ret=obj.returncode
if ret==0:
if out:
return out.strip()
else:
return ret
else:
if err:
return err.strip()
else:
return ret
file_name='powershell_file.ps1'
file_path=os.path.join(os.environ['TEMP'], file_name)
with open(file_path, 'wb') as wr:
wr.write(ps_content)
ecmd('powershell "Set-ExecutionPolicy RemoteSigned"')
print ecmd('powershell "%s"'%file_path)
Comments