Image

Image

Search This Blog

Showing posts with label Script. Show all posts
Showing posts with label Script. Show all posts

Friday, January 03, 2025

Deploy port forward script on multiple computers

# deploy-cond_portforward.ps1
# a stand-alone script that deploys the port-forward to a list of target computers
# v1.0 - 2024-10-08 s.t. - initial release


# EDIT THIS - create a temporary list of all computer on which we want to deploy
$complstfileToAdd = @'
AH00001
RA00003
BM0001-W10
'@
Set-Content "$env:TEMP\comps.txt" $complstfileToAdd

# create the .ps1 file that will execute the portforward - this file must be tailored to each host after deployment
$psfileToAdd = @'
# condprtforward.ps1
# a powershell script to check the portforwading on iBox and re-add if not present
# To be run by powershell from Task Scheduler */10min with SYSTEM rights and arguments "-noprofile -executionpolicy bypass -file C:\WINDOWS\cond_portfwd.ps1"
# Version 1.0 - 2024 s.t.

# EDIT THIS - define IP and ports
$lclip = "127.0.0.1"
$lclport = "65535"
$2ndlclprt = ""
$rmtip = "127.0.0.2"
$rmtport = "65535"
$2ndrmtprt = ""

# check if run with admin rights
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))  
{  
  $arguments = "& '" +$myinvocation.mycommand.definition + "'"
  Start-Process powershell -Verb runAs -ArgumentList $arguments
  Break
}

#test if the portforward is already active
if (Test-NetConnection $lclip -Port $lclport -WarningAction SilentlyContinue -InformationLevel Quiet) {
 Write-Host "got_response, $lclport is open"
} else {
#add rules
 Write-Host "add_rules $lclip : $lclport $rmtip : $rmtport"
 netsh interface portproxy reset
 netsh advfirewall firewall add rule name="PortProxy Custom 1" dir=in action=allow protocol=TCP localport=$lclport
 netsh interface portproxy add v4tov4 listenport=$lclport listenaddress=$lclip connectport=$rmtport connectaddress=$rmtip
 
 if($2ndrmtprt) {
  Write-Host "2nd port is defined, adding 2nd rule"
  netsh advfirewall firewall add rule name="PortProxy Custom 2" dir=in action=allow protocol=TCP localport=$2ndlclprt
  netsh interface portproxy add v4tov4 listenport=$2ndlclprt listenaddress=$lclip connectport=$2ndrmtport connectaddress=$rmtip
  }
}
##Write-Host "end"
##Start-Sleep 5
'@
Set-Content "$env:TEMP\cond_portfwd.ps1" $psfileToAdd

# create the scheduled task .xml file that will be "imported" in order to create the task
$xmlfileToAdd = @'
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.3" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2024-10-08T00:00:00.0000000</Date>
    <Author>Administrator</Author>
    <Description>Launch and maintain Port Forward</Description>
    <URI>\PortForward</URI>
  </RegistrationInfo>
  <Triggers>
    <BootTrigger>
      <Repetition>
        <Interval>PT10M</Interval>
        <StopAtDurationEnd>false</StopAtDurationEnd>
      </Repetition>
      <Enabled>true</Enabled>
    </BootTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>S-1-5-18</UserId>
      <RunLevel>HighestAvailable</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
    <UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe</Command>
      <Arguments>-noprofile -executionpolicy bypass -file C:\WINDOWS\cond_portfwd.ps1</Arguments>
    </Exec>
  </Actions>
</Task>
'@
Set-Content "$env:TEMP\PortForward.xml" $xmlfileToAdd

# start the deployment. first ask for some admin credentials valid on targets
$cred = Get-Credential -Message "Please enter admin credentials valid on target computers";
if($cred -isnot [PSCredential]) {Write-Host -ForegroundColor Red -BackgroundColor DarkBlue "No valid credentials provided. Exiting!" ; exit 1}
# copy the files to each target computer. no need to see the errors, we have our own errorreporting
$ErrorActionPreference= 'silentlycontinue'
foreach($line in Get-Content $env:TEMP\comps.txt) {
Write-Host -ForegroundColor Gray "`nStart running on $line"
$comp = New-PSSession -Credential $cred $line
if ($?) { Write-Host -ForegroundColor Green "Session to $comp established" }else{ Write-Host -ForegroundColor Red "Unable to connect to $line" }
Copy-Item -ToSession $comp $env:TEMP\cond_portfwd.ps1 -Destination C:\WINDOWS\cond_portfwd.ps1 -Force
if ($?) {  Write-Host -ForegroundColor Green ".ps1 file copied" }else{ Write-Host -ForegroundColor Red ".ps1 file NOT copied on $line" }
Copy-Item -ToSession $comp "$env:TEMP\PortForward.xml" -Destination "C:\WINDOWS\TEMP\PortForward.xml" -Force
if ($?) {  Write-Host -ForegroundColor Green ".xml file copied" }else{ Write-Host -ForegroundColor Red ".xml file NOT copied on $line" }
# create the scheduled task from the .xml file
Invoke-Command -ComputerName $line -Credential $cred { $Task = Get-Content "C:\WINDOWS\TEMP\PortForward.xml" -raw ; Register-ScheduledTask -Xml $Task -TaskName 'PortForward' -User SYSTEM -Force }
if ($?) {  Write-Host -ForegroundColor Green "Scheduledtask created"}else{ Write-Host -ForegroundColor Red "Scheduledtask NOT created on $line" }
}

# local cleanup
Remove-Item "$env:TEMP\comps.txt"
Remove-Item "$env:TEMP\PortForward.xml"
Remove-Item "$env:TEMP\cond_portfwd.ps1"

# reminder
Write-Host -ForegroundColor Yellow -BackgroundColor DarkBlue "`nOn each of the target computers please edit C:\WINDOWS\cond_portfwd.ps1"

exit

Thursday, February 13, 2020

Asterisk PAGE say time every hour

Digium D6x phones and CyberData SIP Speakers  are used to page.
The phones are also used as intercoms (bidirectional page).

To start, we need accounts for the phones/speakers added to sip.conf:



[phone1] ; Phone
type=friend
host=dynamic
context=my-context
secret=5678
mailbox=319

[speaker1]; Speaker
type=friend 
host=dynamic
context=my-context
secret=1234
mailbox=329
record_out=Adhoc
record_in=Adhoc
qualify=no


Then in extensions.conf, in the [my-context] context, add:

; Paging extensions
exten => 3319,1,GotoIf($[ ${CALLERID(number)} = 319 ]?skipself)
exten => 3319,1,SIPAddHeader(Alert-Info: info=<intercom>) ; Digium D6x require this to enable paging - search documentation for different phone models!
exten => 3319,n,Dial(SIP/phone1) ; this is the phone1 defined in sip.conf
exten => 3319,n(skipself),Noop(Not paging originator)

exten => 3329,1,GotoIf($[ ${CALLERID(number)} = 329 ]?skipself)
exten => 3329,n,Dial(SIP/speaker1,50) ; this is the speaker1 defined in sip.conf
exten => 3329,n(skipself),Noop(Not paging originator)

exten => 398,1,Page(LOCAL/3319@my-context&LOCAL/3329@my-context,di,120) ; Bidirectional PAGE - that's what the "d" does.
exten => 398,n,Hangup()

With this, we can dial 398 and the PAGE should work.

Now, in order to say the time automatically, we need a .call file, let's create /var/lib/asterisk/third-party/say-time.call

Channel: LOCAL/398@my-context
MaxRetries: 10
RetryTime: 5
WaitTime: 20
Context: page-say-time
Extension: 3310

Of course, we need to create the [page-say-time] context in extensions.conf:

[page-say-time]
exten => 3310,1,Answer()
exten => 3310,n,Wait(1)
exten => 3310,n,Playback(at-tone-time-exactly) ; this sound file is already in asterisk sounds
exten => 3310,n,Wait(1)
exten => 3310,n,SayUnixTime(,EST,IMp)
exten => 3310,n,Wait(1)
exten => 3310,n,Playback(beep) ; this sound file is already in asterisk sounds
exten => 3310,n,Wait(2)
exten => 3310,n,Hangup()

and the last step, create a crontab that copies the say-time.call to the astersk outgoing at every fix hour:

0  * *  *  * /bin/cp /var/lib/asterisk/third-party/say-time.call /var/spool/asterisk/outgoing/


Tuesday, June 04, 2019

Web Interface for Parental Control

This continues the Parental Control post from last month.

First of all, in order to protect the web page, we need an authentication method. A simple user/password will do for the moment (it's not perfect, you can bypass it by accessing directly the /cgi-bin/script.sh, but for the purpose of this exercise is OK-ish) .

Make sure that in the lighttpd.conf, mod_auth and mod_access are loaded,
server.modules += ( "mod_access" )
server.modules += ( "mod_auth" )

and the host section is protected

HTTP["url"] =~ "^/" {
auth.backend = "plain"
auth.backend.plain.userfile = "/jffs/lighttpd/.lighttpdpassword"
auth.require = ( "/" => (
"method" => "basic",
"realm" => "Password protected Parental Control",
"require" => "valid-user"
))}
(where /jffs/lighttpd/.lighttpdpassword contains the plaintext credentials, let's say parent:password)


The following index.html must be placed into the lighthttpd www root (/jffs/www/):

<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
   <title>Parental Control</title>
     <form action="../cgi-bin/ai.sh" method="POST">
     <button name="name" value="value" style="background-color:lime;height:150px;width:400px"> Allow internet </button>
     </form><p><br>
     <form action="../cgi-bin/ag.sh" method="POST">
     <button name="name" value="value" style="background-color:yellowgreen;height:150px;width:400px">  Allow games  </button>
     </form><p><br>
     <form action="../cgi-bin/ay.sh" method="POST">
     <button name="name" value="value" style="background-color:khaki;height:150px;width:400px">  Allow only YouTube  </button>
     </form><p><br>
     <form action="../cgi-bin/ni.sh" method="POST">
     <button name="name" value="value" style="background-color:red;height:150px;width:400px"> No internet </button>
     </form><p><br>
     <form action="../cgi-bin/ng.sh" method="POST">
     <button name="name" value="value" style="background-color:lightcoral;height:150px;width:400px">  No games  </button>
     </form><p><br>
     <form action="../cgi-bin/lst.sh" method="POST">
     <button name="name" value="value" style="background-color:cyan;height:150px;width:400px">  Show actual  </button>
     </form>
 </head>
</html>

The following scripts will be placed into the ./cgi-bin folder:

ag.sh
#!/bin/sh
OUTPUT=$('/jffs/allow_game ; sleep 1; iptables -L FORWARD | grep DROP | grep -v "DROP       0    --  anywhere             anywhere" | if grep -q "DROP       0    --  192.168.1.128/28    anywhere"; then echo NO Internet; else echo Allow Internet; fi; if grep -qm1 "#" /tmp/yt-block.conf; then echo Allow YT; else echo NO YT; fi; if grep -qm1 "#" /tmp/games-block.conf; then echo Allow Games; else echo NO Games; fi' | awk 'BEGIN{print "<table>"} {print "<tr>";for(i=1;i<=NF;i++)print "<td>" $i"</td>";print "</tr>"} END{print "</table>"}')
echo "Content-type: text/html"
echo ""
echo "<html><head><title>Parental Control</title></head><body>"
echo "Rules are: $OUTPUT <br><p>"
echo "<form><input type='button' style='background-color:cyan;height:200px;width:400px' value='Back' onclick='history.back()'></form>"
echo "</body></html>"

ai.sh
#!/bin/sh
OUTPUT=$('/jffs/del_fw ;sleep 1; iptables -L FORWARD | grep DROP | grep -v "DROP       0    --  anywhere             anywhere" | if grep -q "DROP       0    --  192.168.1.128/28    anywhere"; then echo NO Internet; else echo Allow Internet; fi; if grep -qm1 "#" /tmp/yt-block.conf; then echo Allow YT; else echo NO YT; fi; if grep -qm1 "#" /tmp/games-block.conf; then echo Allow Games; else echo NO Games; fi' | awk 'BEGIN{print "<table>"} {print "<tr>";for(i=1;i<=NF;i++)print "<td>" $i"</td>";print "</tr>"} END{print "</table>"}')
echo "Content-type: text/html"
echo ""
echo "<html><head><title>Parental Control</title></head><body>"
echo "Rules are: $OUTPUT <br><p>"
echo "<form><input type='button' style='background-color:cyan;height:200px;width:400px' value='Back' onclick='history.back()'></form>"
echo "</body></html>"

ay.sh
#!/bin/sh
OUTPUT=$('/jffs/allow_yt ; sleep 1; iptables -L FORWARD | grep DROP | grep -v "DROP       0    --  anywhere             anywhere" | if grep -q "DROP       0    --  192.168.1.128/28    anywhere"; then echo NO Internet; else echo Allow Internet; fi; if grep -qm1 "#" /tmp/yt-block.conf; then echo Allow YT; else echo NO YT; fi; if grep -qm1 "#" /tmp/games-block.conf; then echo Allow Games; else echo NO Games; fi' | awk 'BEGIN{print "<table>"} {print "<tr>";for(i=1;i<=NF;i++)print "<td>" $i"</td>";print "</tr>"} END{print "</table>"}')
echo "Content-type: text/html"
echo ""
echo "<html><head><title>Parental Control</title></head><body>"
echo "Rules are: $OUTPUT <br><p>"
echo "<form><input type='button' style='background-color:cyan;height:200px;width:400px' value='Back' onclick='history.back()'></form>"
echo "</body></html>"

lst.sh
#!/bin/sh
OUTPUT=$('iptables -L FORWARD | grep DROP | grep -v "DROP       0    --  anywhere             anywhere" | if grep -q "DROP       0    --  192.168.1.128/28    anywhere"; then echo NO Internet; else echo Allow Internet; fi; if grep -qm1 "#" /tmp/yt-block.conf; then echo Allow YT; else echo NO YT; fi; if grep -qm1 "#" /tmp/games-block.conf; then echo Allow Games; else echo NO Games; fi;' | awk 'BEGIN{print "<table>"} {print "<tr>";for(i=1;i<=NF;i++)print "<td>" $i"</td>";print "</tr>"} END{print "</table>"}')
echo "Content-type: text/html"
echo ""
echo "<html><head><title>Parental Control</title></head><body>"
echo "Rules are: $OUTPUT <br><p>"
echo "<form><input type='button' style='background-color:cyan;height:200px;width:400px' value='Back' onclick='history.back()'></form>"
echo "</body></html>"

ng.sh
#!/bin/sh
OUTPUT=$('/jffs/disable_game && iptables -L FORWARD | grep DROP | grep -v "DROP       0    --  anywhere             anywhere" | if grep -q "DROP       0    --  192.168.1.128/28    anywhere"; then echo NO Internet; else echo Allow Internet; fi; if grep -qm1 "#" /tmp/yt-block.conf; then echo Allow YT; else echo NO YT; fi; if grep -qm1 "#" /tmp/games-block.conf; then echo Allow Games; else echo NO Games; fi' | awk 'BEGIN{print "<table>"} {print "<tr>";for(i=1;i<=NF;i++)print "<td>" $i"</td>";print "</tr>"} END{print "</table>"}')
echo "Content-type: text/html"
echo ""
echo "<html><head><title>Parental Control</title></head><body>"
echo "Rules are: $OUTPUT <br><p>"
echo "<form><input type='button' style='background-color:cyan;height:200px;width:400px' value='Back' onclick='history.back()'></form>"
echo "</body></html>"

ni.sh
#!/bin/sh
OUTPUT=$('/jffs/add_fw && iptables -L FORWARD | grep DROP | grep -v "DROP       0    --  anywhere             anywhere" | if grep -q "DROP       0    --  192.168.1.128/28    anywhere"; then echo NO Internet; else echo Allow Internet; fi; if grep -qm1 "#" /tmp/yt-block.conf; then echo Allow YT; else echo NO YT; fi; if grep -qm1 "#" /tmp/games-block.conf; then echo Allow Games; else echo NO Games; fi' | awk 'BEGIN{print "<table>"} {print "<tr>";for(i=1;i<=NF;i++)print "<td>" $i"</td>";print "</tr>"} END{print "</table>"}')
echo "Content-type: text/html"
echo ""
echo "<html><head><title>Parental Control</title></head><body>"
echo "Rules are: $OUTPUT <br><p>"
echo "<form><input type='button' style='background-color:cyan;height:200px;width:400px' value='Back' onclick='history.back()'></form>"
echo "</body></html>"

Now a very simple web page will allow you to control the kids internet from any browser:

Friday, May 03, 2019

Parental control

Because you can't let the kids on YouTube 24/7 and some games are really addictive :)

The router must run OpenWRT or DD-WRT.

The kids devices must be assigned IP's from a certain range, let's say 192.168.1.128/28 by adding some lines similar to the following one into Additional Dnsmasq Options:
dhcp-host=set:red,AA:BB:CC:00:DD:22,kids-tv,192.168.1.130,43200m


A series of scripts must be put in /jffs/ and called by a cron job:

cat add_fw
#!/bin/sh
iptables -I FORWARD 1 -s 192.168.1.128/28 -j DROP
iptables -I FORWARD 2 -s 192.168.1.128/28 -m conntrack -j DROP --ctstate RELATED,ESTABLISHED

cat del_fw
#!/bin/sh
iptables -D FORWARD -s 192.168.1.128/28 -j DROP
iptables -D FORWARD -s 192.168.1.128/28 -m conntrack -j DROP --ctstate RELATED,ESTABLISHED

cat disable_game
#!/bin/sh
# DNS Rules
sed -e 's/^#//' -i /tmp/games-block.conf
sed -e 's/^#//' -i /tmp/yt-block.conf
restart_dns
# Force kids DNS to local
iptables -t nat -A PREROUTING -i br0 -s 192.168.1.128/28 -p udp --dport 53 -j DNAT --to 192.168.1.1
iptables -t nat -A PREROUTING -i br0 -s 192.168.1.128/28 -p tcp --dport 53 -j DNAT --to 192.168.1.1
# Block all ports over :500
iptables -I FORWARD 5 -p tcp --source 192.168.1.128/28 --dport 500:65535 -j DROP

cat allow_game
#!/bin/sh
# Remove DNS rules
sed 's/^\([^#]\)/#\1/g' -i /tmp/games-block.conf
sed 's/^\([^#]\)/#\1/g' -i /tmp/yt-block.conf
restart_dns
# Remove Force kids DNS to local
iptables -t nat -D PREROUTING -i br0 -s 192.168.1.128/28 -p udp --dport 53 -j DNAT --to 192.168.1.1
iptables -t nat -D PREROUTING -i br0 -s 192.168.1.128/28 -p tcp --dport 53 -j DNAT --to 192.168.1.1
# Unblock all ports over :500
iptables -D FORWARD -p tcp --source 192.168.1.128/28 --dport 500:65535 -j DROP


I do have an extra script that allow access to YouTube, without allowing games, this one is called only from a html page that I'll explain in a later post:

cat allow_yt
#!/bin/sh
sed 's/^\([^#]\)/#\1/g' -i /tmp/yt-block.conf
restart_dns


Those scripts are called by cron jobs that makes sure we don't have internet during the sleep hours and games & YouTube are permitted only during the weekend:
00 21 * * 0-4 root /jffs/add_fw
30 22 * * 5,6 root /jffs/add_fw
00 08 * * * root /jffs/del_fw
30 17 * * 5 root /jffs/allow_game
30 17 * * 0 root /jffs/disable_game


In order to block the DNS requests, the following Additional Dnsmasq Options needs to be added:
conf-file=/tmp/yt-block.conf
conf-file=/tmp/games-block.conf


The files /tmp/yt-block.conf and /tmp/games-block.conf are created by the startup script:
stopservice dnsmasq
echo "#address=/.roblox.com/192.168.1.1
#address=/.rbxcdn.com/192.168.1.1
#address=/.epicgames.com/192.168.1.1
#address=/.fortnitegame.com/192.168.1.1
#address=/.easyanticheat.com/192.168.1.1
#address=/.pixelgunserver.com/192.168.1.1
#address=/.applovin.com/192.168.1.1
#address=/.clashroyaleapp.com/192.168.1.1
#address=/.applifier.com/192.168.1.1
#address=/.chartboost.com/192.168.1.1
#address=/.fyber.com/192.168.1.1
#address=/.twitch.tv/192.168.1.1
#address=/.ttvnw.net/192.168.1.1
#address=/.leagueoflegends.com/192.168.1.1
#address=/.pvp.net/192.168.1.1
#address=/.riotgames.com/192.168.1.1
#address=/.garenanow.com/192.168.1.1
#address=/.ea.com/192.168.1.1
#address=/.respawn.com/192.168.1.1
#address=/.origin.com/192.168.1.1" > /tmp/games-block.conf
echo "#address=/.youtube.com/192.168.1.1
#address=/youtube.googleapis.com/192.168.1.1
#address=/youtubei.googleapis.com/192.168.1.1
#address=/.ytimg.com/192.168.1.1
#address=/ytimg.l.google.com/192.168.1.1
#address=/youtube.l.google.com/192.168.1.1
#address=/.googlevideo.com/192.168.1.1
#address=/.youtube-nocookie.com/192.168.1.1
#address=/.youtu.be/192.168.1.1" > /tmp/yt-block.conf
startservice dnsmasq


An "easy" way to run those scripts besides the scheduled cron jobs, is from the DD-WRT Administration -> Commands page:

Monday, April 01, 2019

VM Management

# powershell script for VM mass management. Requires a .csv file containing the list of VMs and a name for the snapshot/ If no snapshot name is given, "Snapshot_1" is used.

 #load powercli if needed
if (!(Get-Module -Name VMware.VimAutomation.Core) -and (Get-Module -ListAvailable -Name VMware.VimAutomation.Core)) {
    Write-Output "loading the VMware Core Module..."
    if (!(Import-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) {
        # Error out if loading fails
        Write-Error "`nERROR: Cannot load the VMware Module. Is the PowerCLI installed?"
     }
    $Loaded = $True
    }
 #   elseif (!(Get-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -and !(Get-Module -Name VMware.VimAutomation.Core) -and ($Loaded -ne $True)) {
 #       Write-Output "loading the VMware Core Snapin..."
 #    if (!(Add-PSSnapin -PassThru VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) {
 #    # Error out if loading fails
 #    Write-Error "`nERROR: Cannot load the VMware Snapin or Module. Is the PowerCLI installed?"
 #    }
 #   }

# Define vmConfigSpec params
$vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec
$vmConfigSpec.Tools = New-Object VMware.Vim.ToolsConfigInfo
$vmConfigSpec.Tools.ToolsUpgradePolicy = "UpgradeAtPowerCycle"

# Get the command-line params
 $command = $args[0]
 $list = $args[1]
 $server = $args[2]

# define default params
if (!$list) { $list = "vm_mgmt.csv"}
if (!$server) { $server = "default.vCenter.domain.tld"}

# Start processing the command
  switch ($command) {
    default { $myname = $MyInvocation.MyCommand.Definition
    echo "`nERROR! Usage:"
    echo "$myname command [list] [server] "
    echo "`ncommand is one of the following: viewsnap, takesnap, delsnap, revertsnap, hwupd, vmtoolsupd, vmoff, vmon."
    echo " list is a .csv file containing 'VM_Name,Snapshot_name'. If no list provided, 'vm_mgmt.csv' will be used."
    echo " server is the name of the server connecting to. If no server is provided, 'default.vCenter.domain.tld' will be used.`n"
    }
 
  "viewsnap" {
    ### View Snapshot
      Connect-VIServer -Server $server -Protocol https
      import-csv $list | ForEach-Object {
      $_.VM_Name
      $_.Snapshot_name
      if (!$_.Snapshot_name) { $_.Snapshot_name = "Snaphot_1"}
    echo "`nView Snaphots:`n"
      get-vm -Name $_.VM_Name | get-snapshot
  } }

  "takesnap" {   
    ### Take Snapshot
      Connect-VIServer -Server $server -Protocol https
      import-csv $list | ForEach-Object {
      $_.VM_Name
      $_.Snapshot_name
      if (!$_.Snapshot_name) { $_.Snapshot_name = "Snaphot_1"}
    echo "`nTaking Snapshots`n"
      get-vm -Name $_.VM_Name | New-Snapshot -Name $_.Snapshot_1 -Quiesce -Memory
  } }

  "delsnap" {   
    ### Delete Snapshot
    Connect-VIServer -Server $server -Protocol https
    import-csv $list | ForEach-Object {
    $_.VM_Name
    $_.Snapshot_name
      if (!$_.Snapshot_name) { $_.Snapshot_name = "Snaphot_1"}
   echo "`nDelete Snapshots`n"
    get-snapshot -name $_.Snapshot_1 -vm $_.VM_Name | remove-snapshot -confirm:$false
  } }

  "revertsnap" {
    ### Revert To Snapshot
      Connect-VIServer -Server $server -Protocol https
      import-csv $list | ForEach-Object {
      $_.VM_Name
      $_.Snapshot_name
    echo "`nReverting Snapshots. Confirmation is required for each restore.`n"
      set-vm -VM $_.VM_Name -Snapshot $_.Snapshot_1 -whatif
    # set-vm -VM $_.VM_Name -Snapshot $_.Snapshot_1 -confirm:$false
  } }

  "hwupd" { 
    # VM Hardware upgrade
      Connect-VIServer -Server $server -Protocol https
      import-csv $list | ForEach-Object {
      $_.VM_Name
      $_.Snapshot_name
      if (!$_.Snapshot_name) { $_.Snapshot_name = "Snaphot_1"}
    echo "`nVM Hardware upgrade to vmx-13`n"
      $do = New-Object -TypeName VMware.Vim.VirtualMachineConfigSpec
      $do.ScheduledHardwareUpgradeInfo = New-Object -TypeName VMware.Vim.ScheduledHardwareUpgradeInfo
      $do.ScheduledHardwareUpgradeInfo.UpgradePolicy = “always”
      $do.ScheduledHardwareUpgradeInfo.VersionKey = “vmx-13”
      $vm.ExtensionData.ReconfigVM_Task($do)
  } }

  "vmtoolsupd" {
    # VM Tools update
      Connect-VIServer -Server $server -Protocol https
      import-csv $list | ForEach-Object {
      $_.VM_Name
      $_.Snapshot_name
      if (!$_.Snapshot_name) { $_.Snapshot_name = "Snaphot_1"}
    echo "`nUpdating VM Tools`n"
      get-vm -Name $_.VM_Name | %{$_.Extensiondata.ReconfigVM($vmConfigSpec)}
  } }

  "vmoff" {
    # VM power off
      Connect-VIServer -Server $server -Protocol https
      import-csv $list | ForEach-Object {
      $_.VM_Name
      $_.Snapshot_name
      if (!$_.Snapshot_name) { $_.Snapshot_name = "Snaphot_1"}
    echo "`nTurning VMs OFF`n"
      $vm = Get-VM -Name $_.VM_Name | Shutdown-VMGuest -Confirm:$false
  } }

  "vmon" {
    # VM power on
      Connect-VIServer -Server $server -Protocol https
      import-csv $list | ForEach-Object {
      $_.VM_Name
      $_.Snapshot_name
      if (!$_.Snapshot_name) { $_.Snapshot_name = "Snaphot_1"}
    echo "`nTurning VMs ON`n"
      $vm = Get-VM -Name $_.VM_Name | Start-VM -Confirm:$false
  } }

}



-----------------------------------------------
type vm_mgmt.csv

VM_NAME,Snapshot_name
some-vm-name,Snapshot_342
another-vm-name,Snapshot_temp4

Wednesday, September 02, 2015

Map remote printer

map a local printer to TS session when "bring local printers to TS" fails miserably and start the App only after the printer is available

@echo off
setlocal enableextensions enabledelayedexpansion
set result=0
ser printer=oj100
Title Adding Printer. Be patient...
echo Adding printer. Do not start App yet...
ping -n 2 1.1.1.1 >nul 2>nul
taskkill /fi "username eq %username%" /im app.exe 2>nul
%userprofile%\delprint.vbs
ping -n 2 1.1.1.1 >nul 2>nul
echo Please wait. Starting Installation...
echo ..
for /F "tokens=2 delims=/: " %%f in ('%userprofile%\gettscip.exe') do (
echo Your IP is: %%f
:loop
net use \\%%f\ipc$ /d /y >nul 2>nul
ping -n 1 1.1.1.1 >nul 2>nul
net use \\%%f\ipc$ && set result=1
echo Result: !result!
if not !result! equ 1 goto :loop
Echo Add printer. This is going to take up to 5 minutes, be patient...
rundll32 printui.dll,PrintUIEntry /in /n "\\%%f\!printer!" /u /q /Gw
echo Setting default printer...
echo.
rundll32 printui.dll,PrintUIEntry /y /n  "\\%%f\!printer!" /q
echo.
)
Echo Starting App...
ping -n 3 1.1.1.1 >nul 2>nul
taskkill /fi "username eq %username%" /im app.exe >nul 2>nul
endlocal
C:\Users\Public\Desktop\App.lnk

Monday, August 03, 2015

DNS Adbock on router

In case you have, like me, a secodary dns on your DD-WRT router, you need a dns adblock on it too. By modifying the excellent tutorial from http://www.howtogeek.com/51477/how-to-remove-advertisements-with-pixelserv-on-dd-wrt/ I came to this script:

#!/bin/sh
########Functions setup#########################
logger_ads()
{
logger -s -p local0.notice -t ad_blocker $1
}

softlink_func()
{
ln -s /tmp/$1 /jffs/dns/$2
if [ "`echo $?`" -eq 0 ] ; then
logger_ads "Created $3 softlink to RAM on JFFS"
else
logger_ads "The attempt to create $3 softlink to RAM on JFFS *FAILED*"
logger_ads "it is obvious something IS *terribly wrong*. Will now exit... bye (ads will not be blocked)"
exit 1
fi
}

note_no_space()
{
logger_ads "I assure you this only takes $1 blocks, but I guess your too close to the edge for JFFSs comfort"
logger_ads "deleting the half witted file, as to not confuse the DNS service and free up the JFFS space for other uses."
}
##################################################
nvram set aviad_changed_nvram=0
logger_ads "########### Ads blocker script starting ###########"

if [[ -z "$1" ]]; then
logger_ads "Sleeping for 30 secs to give time for router boot"
sleep 30
else
logger_ads "override switch given"
[[ $1 = "-h" || $1 = "/?" ]] && echo "use -m to override the 30 seconds delay and -f to force a list refresh" && exit 0
[ $1 = "-f" ] && rm /jffs/dns/dnsmasq.adblock.conf && rm /jffs/dns/dlhosts
fi

while ! ping www.google.com -c 1 > /dev/null ; do
logger_ads "waiting for the internet connection to come up"
sleep 5
done

logger_ads "Adding a refresh cycle by puting the script in cron if it isnt there yet"
if [[ -z "`cat /tmp/crontab | grep "/jffs/dns/disable_adds.sh"`" ]] ; then
echo '0 0 * * * root /jffs/dns/disable_adds.sh -m' > /tmp/crontab
stopservice cron && logger_ads "stopped the cron service" startservice cron && logger_ads "started the cron service"
else
logger_ads "The script is already in cron"
fi

logger_ads "New IP and ports setup. Reserve the IP .100 for pixelserv"
pixel="`ifconfig br0 | grep inet | awk '{ print $2 }' | awk -F ":" '{ print $2 }' | cut -d . -f 1,2,3`.100"
mgmtip="`ifconfig br0 | grep inet | awk '{ print $2 }' | awk -F ":" '{ print $2 }'`"

# In my case, on IP .100 I have an apache serving null.html as error page. Comment
next 3 paragraphs, as I don't need pixelserv
#logger_ads "Move http interface to $mgmtip:88"
#if [[ -z "`ps | grep -v grep | grep "httpd -p 88"`" && `nvram get http_lanport` -ne 88 ]]
; then
# logger_ads "it seems that the http is not setup yet on port :88"
# stopservice httpd
# nvram set http_lanport=88
# nvram set aviad_changed_nvram=1
# startservice httpd
#else
# logger_ads "The http is already setup on $mgmtip:88"
#fi

#logger_ads "Redirect setup IP/Port from $mgmtip:80 to $mgmtip:88"
#[[ -z "`iptables -L -n -t nat | grep $mgmtip | grep 80`" ]] && logger_ads "did NOT find an active redirect rule with the iptable command, injecting it now." && /usr/sbin/iptables -t nat -I PREROUTING 1 -d $mgmtip -p tcp --dport 80 -j DNAT --to $mgmtip:88
#nvram get rc_firewall > /tmp/fw.tmp
#if [[ -z "`cat /tmp/fw.tmp | grep "/usr/sbin/iptables -t nat -I PREROUTING 1 -d $mgmtip  p tcp --dport 80 -j DNAT --to $mgmtip:88"`" ]] ; then
# echo "/usr/sbin/iptables -t nat -I PREROUTING 1 -d $mgmtip -p tcp --dport 80 -j DNAT --to $mgmtip:88" >> /tmp/fw.tmp
# nvram set rc_firewall="`cat /tmp/fw.tmp`"
# logger_ads "DONE appending forwarding to FW script"
# nvram set aviad_changed_nvram=1
#else
# logger_ads "The redirection $mgmtip:80 -> $mgmtip:88 in FW script is already in place"
#fi
#rm /tmp/fw.tmp

#logger_ads "Starting or ReSpawning pixelsrv on $pixel IP :80"
#/sbin/ifconfig br0:1 $pixel netmask "`ifconfig br0 | grep inet | awk '{ print $4 }' | awk -F ":" '{ print $2 }'`" broadcast "`ifconfig br0 | grep inet | awk '{ print $3 }' | awk -F ":" '{print $2 }'`" up
#if [[ -n "`ps | grep -v grep | grep /jffs/dns/pixelserv`" ]]; then
# logger_ads "the pixelserv is already up"
#else
# logger_ads "it seems that the pixelserv isnt up. starting it now"# /jffs/dns/pixelserv $pixel -p 80
#fi

logger_ads "Get the online dns blocking lists"
[ ! -e /jffs/dns/whitelist ] && echo google-analytics > /jffs/dns/whitelist && echo toma.guru >> /jffs/dns/whitelist
if [[ -n "$(find /jffs/dns/dlhosts -mtime +7)" || -n "$(find /jffs/dns/dnsmasq.adblock.conf mtime +7)" || ! -e /jffs/dns/dlhosts || ! -e /jffs/dns/dnsmasq.adblock.conf ]]; then
logger_ads "The lists are NOT setup at all yet, or more then 7 days old, will now retrieve them from the web"
logger_ads "Retrieving the MVPS hosts list..."
wget -q -O - http://www.mvps.org/winhelp2002/hosts.txt | grep "^127.0.0.1"
| grep -v localhost | tr -d '\015' >/tmp/dlhosts.tmp
logger_ads "adjusting the MVPS hosts list for our use"
cat /jffs/dns/whitelist | while read line; do sed -i /${line}/d /tmp/dlhosts.tmp
; done
sed -i s/127.0.0.1/$pixel/g /tmp/dlhosts.tmp
logger_ads "done adjusting the MVPS hosts list."
logger_ads "Retrieving the Yoyo domain list..."
wget -q
"http://pgl.yoyo.org/adservers/serverlist.php?hostformat=dnsmasq&showintro=0&mietype=plaintext" -O /tmp/adblock.tmp
logger_ads "adjusting the Yoyo domain list for our use"
cat /jffs/dns/whitelist | while read line; do sed -i /${line}/d /tmp/adblock.tmp
; done
sed -i s/127.0.0.1/$pixel/g /tmp/adblock.tmp
if [ "`df| grep /jffs | awk '{ print $4 }'`" -ge 65 ] ; then
logger_ads "Moving the Yoyo list to JFFS (as it looks that there is enough space for it)"
mv /tmp/adblock.tmp /jffs/dns/dnsmasq.adblock.conf
if [ "`echo $?`" -eq 0 ] ; then
logger_ads "Moving the YoYo domain list to JFFS operation was successful"
else
note_no_space 20
rm /jffs/dns/dnsmasq.adblock.conf
softlink_func adblock.tmp dnsmasq.adblock.conf YoYo
fi
else
logger_ads "*NOT* Moving the Yoyo list to JFFS (as it looks that there is *NOT* enough space for it)"
softlink_func adblock.tmp dnsmasq.adblock.conf YoYo
fi
if [ "`df| grep /jffs | awk '{ print $4 }'`" -ge 100 ] ; then
logger_ads "Moving the MVPS hosts list to JFFS (as it looks like there is enough space for it)"
mv /tmp/dlhosts.tmp /jffs/dns/dlhosts
if [ "`echo $?`" -eq 0 ] ; then
logger_ads "Moving the MVPS hosts list to JFFSoperation was successful"
else
note_no_space 72
rm /jffs/dns/dlhosts
softlink_func dlhosts.tmp dlhosts MVPS
fi
else
logger_ads "*NOT* Moving the MVPS list to JFFS (as it looks that there is *NOT* enough space for it)"
softlink_func dlhosts.tmp dlhosts MVPS
fi
else
logger_ads "The lists are less then 7 days old, saving on flash erosion and NOT refreshing them."
fi

logger_ads "Injecting the DNSMasq nvram options with the dynamic block lists"
nvram get dnsmasq_options > /tmp/dns-options.tmp
if [[ -z "`cat /tmp/dns-options.tmp | grep "/jffs/dns/dnsmasq.adblock.conf"`" || -z "`cat /tmp/dns-options.tmp | grep "/jffs/dns/dlhosts"`" && -e /jffs/dns/dnsmasq.adblock.conf ]] ; then
logger_ads "Did not find DNSMsaq options in nvram, adding them now"
echo "conf-file=/jffs/dns/dnsmasq.adblock.conf" >> /tmp/dns-options.tmp
echo "addn-hosts=/jffs/dns/dlhosts" >> /tmp/dns-options.tmp
nvram set aviad_changed_nvram=1
logger_ads "Added options to nvram DNSMasq options"
else
logger_ads "The DNSMaq options are already in place"
fi

logger_ads "Checking if the personal list is a file"
if [[ -z "`cat /tmp/dnsmasq.conf | grep conf-file=/jffs/dns/personal-ads-list.conf`" && -z "`nvram get dnsmasq_options | grep "/jffs/dns/personal-ads-list.conf"`" && -e /jffs/dns/personal-ads-list.conf ]] ; then
logger_ads "Yes the personal list is in the form of a file"
logger_ads "Removing whitelist from the personal file"
cat /jffs/dns/whitelist | while read line; do sed -i /${line}/d /jffs/dns/personal ads-list.conf ; done
echo "conf-file=/jffs/dns/personal-ads-list.conf" >> /tmp/dns-options.tmp
nvram set aviad_changed_nvram=1
else
[ ! -e /jffs/dns/personal-ads-list.conf ] && logger_ads "The personal list (assuming there is one) is not in a file"
[ -n "`nvram get dnsmasq_options | grep "/jffs/dns/personal-ads-list.conf"`" ] && logger_ads "The personal list is a file, and... it is already in place according to the NVRAM options readout"
[ "$1" = "-f" ] && cat /jffs/dns/whitelist | while read line; do sed -i /${line}/d /jffs/dns/personal-ads-list.conf ; done && logger_ads "overide switch given so removed whitelist from personal file"
fi
logger_ads "Final settings implementer"
if [ "`nvram get aviad_changed_nvram`" -eq 1 ] ; then
nvram set dnsmasq_options="`cat /tmp/dns-options.tmp`"
logger_ads "Found that NVRAM was changed and committing changes
now"
nvram commit
nvram set aviad_changed_nvram=0
logger_ads "Refreshing DNS settings"
stopservice dnsmasq && logger_ads "stopped the dnsmasq service"
startservice dnsmasq && logger_ads "started the dnsmasq service"
else
logger_ads "Nothing to commit"
fi
rm /tmp/dns-options.tmp
logger_ads "######### Ads blocker script has finished and you should be up and running ##########

Tuesday, March 03, 2015

Recursive owner and rights changing on subfolders

We assume the username==folder_name
the specific version for vista+ profiles:


@echo off
Echo (c) 2012 s@toma.gXXX
Set rprofiles=D:\path\to\profiles
For /f "delims=.V2" %%* in ('dir %rprofiles% /B') Do (
echo target is %rprofiles%\%%*.V2 User is %USERDOMAIN%\%%*
takeown /f "%rprofiles%\%%*.V2" /r
icacls "%rprofiles%\%%*.V2" /setowner %USERDOMAIN%\%%* /T /C
icacls "%rprofiles%\%%*.V2" /grant:r %USERDOMAIN%\%%*:F Administrateurs:F System:F /T
rem dir /B /W "%rprofiles%\%%*.V2"
rem ping -n 1 -w 1000 1.1.1.1 >nul
)

or the simple version:

cd d:\path\to\folders\
For /f "Tokens=*" %* in ('dir /B') Do  @cacls %* /E /C /T /G "%*":F

Monday, December 01, 2014

Stream webcam with sound

cvlc v4l2:///dev/video1 :v4l2-standard= :input-slave=alsa://hw:0,0 :live-caching=300 :sout=#"transcode{vcodec=mp4v,vb=256,scale=Auto,acodec=mp4a,ab=48,channels=1,samplerate=8000}:http{mux=asf,dst=:8080/}" :sout-keep

Tuesday, November 04, 2014

Windows Shell for TS - without Domain Controller

On the RD Session Host Configuration ,the following (compiled as c:\windows\tssession.exe) script is executed as initial shell:

;(c)2014  sorinakis@g**il.com

;msgbox, Username: %A_UserName%
AuthUsers = Administrator|administrator
Loop Parse, AuthUsers, |
{
 ifEqual, A_LoopField, %A_Username%
 {
  Sleep, 500
  Run, explorer.exe
  ;MsgBox EXPLORER Executed.
  GoTo, End
 }
else
 {
  ;MsgBox In the ELSE branch.
  Sleep, 500
  Run, D:\Partages\apps\LCM\Bin\wrun32.exe -ws -c D:\Partages\apps\LCM\etc\CBLCONFI-RZ_APP.ini utmenu
  Sleep 500
  WinMaximize, ahk_class AcucobolWClass
  IfWinExist, Cie(01)
  {
   WinMaximize,  Cie(01)
   Sleep, 500
   WinWaitClose, Cie(01)
   Sleep, 500
   Run, shutdown /l
  }
  Return
 }
}
End:
Sleep, 100
;MsgBox At the END.

Tuesday, September 02, 2014

A simple script to import .pst in thunderbird

#!/bin/bash
#
#(c)2014 sorinakis@g*il.com

if [ "$(whereis readpste | cut -d: -f2)" = "" ]; then.
 echo "Sending you to download readpst"
 kdialog --warningcontinuecancel "Go to http://www.five-ten-sg.com/libpst/ to download, then compile and install libpst
 Once libpst is installed please re-execute this script.
 If readpst is installed, but not in path, you have to comment the first section of $0" --continue-label "Go to site"
 if [ ! $? = 0 ]; then
  echo "Cancel Pressed. Exit"
  exit 2
 fi
 xdg-open http://www.five-ten-sg.com/libpst/
 exit 0
fi

# Prepare location
wrkfld=$TMP/outlook$$
export $(dbus-launch)
mkdir $wrkfld

# Convert pst
readpst -o $wrkfld -r "`kdialog --getopenfilename ~ '*.pst' 2>/dev/null`"

# Rename folder so thunderbird understands
find $wrkfld -type d | tac | grep -v '^$wrkfld$' | xargs -d '\n' -I{} mv {} {}.sbd
find $wrkfld.sbd -name mbox -type f | xargs -d '\n' -I{} echo '"{}" "{}"' | sed -e 's/\.sbd\/mbox"$/"/' | xargs -L 1 mv

#Cleanup empty folders
find $wrkfld.sbd -empty -type d | xargs -d '\n' rmdir

kdialog --msgbox "Conversion Done! Please create a subfolder in your Thunderbird's Local Folders,.
 then manuallly move $wrkfld.sdb into ~/.thunderbird/[profile]/Mail/Local Folders/[new folder]"

Sunday, August 10, 2014

Tune UP (in fact down) Windows 2008 R2

sssc config lanmanworkstation depend= bowser/mrxsmb10/nsi
sc config mrxsmb20 start= disabled

netsh int tcp set global rss=disabled
netsh int tcp set global chimney=disabled
netsh int tcp set global autotuninglevel=disabled
netsh int ip set global taskoffload=disablednetsh int tcp set global autotuninglevel=disablednetsh int tcp set global ecncapability=disablednetsh int tcp set global timestamps=disablednetsh advf set allp state off


:: reg add "HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters" /v DisableTaskOffload /t REG_DWORD /d "1" /f

reg add "HKLM\SYSTEM\CurrentControlSet\services\LanmanWorkstation\Parameters" /v DisableBandwidthThrottling /t REG_DWORD /d "1" /f
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\WinHttp" /v TcpAutotuning /t REG_DWORD /d "0" /f
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings" /v TcpAutotuning /t REG_DWORD /d "0" /f
reg add "HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Internet Settings" /v TcpAutotuning /t REG_DWORD /d "0" /f
reg add "HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters" /v EnableTCPA /t REG_DWORD /d "0" /f

Friday, July 11, 2014

Watermark Printer

This is a very crude version of a "Watermark Printer" - it prints on a "preprinted paper" (e.g. something containing the company logo)


@echo off

:: ------------------------------------------------------------------

:: install redmon in %userprofile%\appdata\redmon
:: put this script in %userprofile%\appdata\redmon\email.bat
:: create new printer with port RPT1:
:: configure port redirect to %userprofile%\appdata\redmon\redrun.exe
:: port arguments
%userprofile%\appdata\redmon\email.bat  %%1

:: ------------------------------------------------------------------
:: Ghostscript configuraton
set GS_INSTALL="
%userprofile%\appdata\redmon\gs"
set GS_VERSION=8.63
:: LibTIFF configuraton
set LIBTIFF_INSTALL=
%userprofile%\appdata\redmon\GnuWin32
:: PDF viewer configuraton (no need to set, if PDF is a registered file type)
set PDF_READER=
:: Watermark background config
set BACKGROUND="
%userprofile%\appdata\redmon\\Watermark.pdf"
:: PDFTK location
set PDFTK="
%userprofile%\appdata\redmon\"
:: ------------------------------------------------------------------
:: temporary PDF directory
set PDF_DIR=%TEMP%\1
:: delete old temporary PDF directories if required
for /d %%D in ("%TEMP%\1\") do if not "%%D"=="%TEMP%\1\" rd /s /q "%%D"
:: create if required
if not exist "%PDF_DIR%" md "%PDF_DIR%"
echo myass > %PDF_DIR%\blah
:: check if file is given
if not "%~1" == "" goto CHECK_FOUND
echo ERROR: No file name given!
goto END
::----------
:CHECK_FOUND
:: check for file existence
if exist "%*" goto SET_FNE
echo ERROR: File "%*" not found!
goto END
::------
:SET_FNE
:: set input file, name and extension
call :set_input_file_name_ext "%*"
:: check file type
if "%INPUT_EXT%" == "" set INPUT_NAME=%~n1.ps
if "%INPUT_EXT%" == "" set INPUT_EXT=.ps
if "%INPUT_EXT%" == ".ps" goto PROCESS_PS
if "%INPUT_EXT%" == ".tiff" goto PROCESS_TIFF
if "%INPUT_EXT%" == ".tif" goto PROCESS_TIFF
if "%INPUT_EXT%" == ".pdf" goto PROCESS_PDF
echo ERROR: File type "%INPUT_EXT%" not supported!
goto END
:: --------
:PROCESS_PS
:: set file names
set PS_FILE=%INPUT_FILE%
set PDF_FILE=%PDF_DIR%\%INPUT_NAME%.pdf
:: convert to PDF
"%GS_INSTALL%\gs%GS_VERSION%\bin\gswin32c.exe" -dSAFER -dNumRenderingThreads#%NUMBER_OF_PROCESSORS% -sDEVICE#pdfwrite -o "%PDF_FILE%" -c .setpdfwrite -f "%PS_FILE%"
goto DISPLAY
:: ----------
:PROCESS_TIFF
:: set file names
set TIFF_FILE=%INPUT_FILE%
set PDF_FILE=%PDF_DIR%\%INPUT_NAME%.pdf
:: convert to PDF
"%LIBTIFF_INSTALL%\bin\tiff2pdf.exe" -o "%PDF_FILE%" -f "%TIFF_FILE%"
goto DISPLAY
:: ---------
:PROCESS_PDF
:: set file name
set PDF_FILE=%INPUT_FILE%
::
:: ------------------------------------------------------------------
:DISPLAY
:: open PDF file in reader
:: start /b "%PDF_READER%" "%PDF_FILE%"
::
:: apply background
%PDFTK%\pdftk.exe "%PDF_FILE%" background %BACKGROUND% output "%PDF_DIR%\output.pdf"
:: call OUTLOOK - ugly for the moment
"C:\Program Files (x86)\Microsoft Office\OFFICE14\OUTLOOK.EXE" /a "%PDF_DIR%\output.pdf"

:: ------------------------------------------------------------------
:END
exit
::
:: ------------------------------------------------------------------
:: Subroutine: set_input_file_name_ext
:: Arguments:  %1 = "path/name.ext"
:: Purpose:    set environment vars to input file, name and extension
:: ------------------------------------------------------------------
:set_input_file_name_ext
set INPUT_FILE=%~1
set INPUT_NAME=%~n1
set INPUT_EXT=%~x1
goto :eof
:: ------------------------------------------------------------------

Thursday, June 05, 2014

Allow login only if the member of a certain OU comes from a certain IP subnet

@echo off
:: (c)2014 sorinakis@g*il.com
setlocal enableextensions enabledelayedexpansion
set config=c:\pair.txt

:: find the primary OU that user belongs to
for /F "tokens=3 delims=/,CN=" %%n in ('"gpresult /R | findstr CN | findstr /I %username%"') do (
 set myou=%%n
)
:: echo myou is: !myou!

:: find the client subnet (need gettscip.exe from www.ctrl-alt-del.com.au in the path somewhere)
for /F "tokens=2 delims=/: " %%f in ('gettscip.exe') do (
 for /F "tokens=1-3 delims=/." %%g in ('echo %%f') do set mynet=%%g.%%h.%%i
)
:: echo mynet is: !mynet!

:: read the config file containing the pair IP_subnet/Organisational_Unit (or group)
:: the pair have to be separated by a space, ex: '192.168.1 Users' comments start with ;
for /F "eol=; tokens=1,2 delims=/ " %%l in ('type !config!') do (
 set net=%%l
:: set group=%%m
 set ou=%%m

:: find if the user belongs to a group
rem for /f %%f in ('"net user /domain %username% | findstr /i %group%"') do set /a ingroup=yes

:: if the two pairs are identical, the user can login from that subnet
 if "!net!"=="!mynet!" (
::  if "!ingroup!"=="yes" (
 if /I "!ou!"=="!myou!" (
   set canrun=yes
  )
 )
)
::echo canrun: !canrun!

:: if the user can't login let him know, then end the session
if NOT "!canrun!"=="yes" (
 echo Sorry %username%, "!myou!" are NOT ALLOWED to login from !mynet!.0/24
 msg %username% Sorry, %username% is NOT ALLOWED to login from this location.
 shutdown /l
)

:: Cleanup variables at end
endlocal

Tuesday, May 06, 2014

Delete old printers ond add new ones - second version

This version keeps track of the default printer :)

' s@to**.guru - Jan 08 2015 Replace the default Printer

'********************************************************************************************************************
On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("WScript.Shell")
Set objNetwork = CreateObject("WScript.Network")
'Set wmiLocator = CreateObject("WbemScripting.SWbemLocator")
'Set wmiNameSpace = wmiLocator.ConnectServer(objNetwork.ComputerName, "root\default")
'Set objRegistry = wmiNameSpace.Get("StdRegProv")
'strComputer = "."
'Const HKEY_CLASSES_ROOT  = &H80000000
'Const HKEY_CURRENT_USER  = &H80000001
'Const HKEY_LOCAL_MACHINE = &H80000002
'Const HKEY_USERS         = &H80000003
userprrf = objShell.Environment("PROCESS")("UserProfile")
lockfile = "\prinstalled"
oldlockfile = "\printersinstalled"
strnewSrv = "\\2K12SRV\"
strOldSrv = "\\critesdc\"
arrPrinters = Array("HP Color LaserJet 4700 PCL 5c","HP Color LaserJet 4700 PCL 5c Sales","HP LaserJet 4100 Series PCL6 Sales","HP LaserJet 4250 PCL6","HP Laserjet 5100tn","Xerox WorkCentre 5655 PS","Xerox7545 PS")

'********************************************************************************************************************
' If this script was already run at least once for this user, EXIT and don't look back
If (objFSO.FileExists(userprrf & lockfile)) Then
  Wscript.Quit
End If
' Delete old lockfile
objFSO.DeleteFile(userprrf & oldlockfile)
'' If we're on the TS server create lockfile and Exit!
'If objNetwork.ComputerName = "2K12TS1" Then
'  Set objFile = objFSO.CreateTextFile(userprrf & lockfile, true)
'  Set objFile = objFSO.GetFile(userprrf & lockfile)
'  objFile.Attributes = 2
'  Wscript.Quit
'End if

'********************************************************************************************************************
' Make spooler autostart without waiting
' use Microsoft's way of getting StdRegProv, set_binary is special!
'Set oRegistry = _
'   GetObject("Winmgmts:root\default:StdRegProv")
'strPath = "SYSTEM\CurrentControlSet\Services\Spooler"
'uBinary = Array(80,51,01,00,00,00,00,00,00,00,00,00,03,00,00,00,20,00,64,00,01,00,00,00,00,00,00,00,01,00,00,00,00,00,00,00,01,00,00,00,00,00,00,00)
'Return = oRegistry.SetBinaryValue(HKEY_LOCAL_MACHINE, _
'   strPath, _
'   "FailureActions", _
'   uBinary)
'oShell.RegWrite "HKLM\SYSTEM\CurrentControlSet\Services\Spooler\Start", 2, "REG_DWORD"

'********************************************************************************************************************
' get the default printer
strdefValue = "HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows\Device"
strdefPrinter = objShell.RegRead(strdefValue)
strdefPrinter = Split(strdefPrinter, ",")(0)
'wscript.Echo "Actual default printer: " & strdefPrinter
' put the default printer into the lockfile if we want to keep it for historical records
'Set objFile = objFSO.CreateTextFile(userprrf & lockfile)
'objFile.Write strdefPrinter & vbCrLf
'objFile.Close

'********************************************************************************************************************
'Delete old printers using either printui.dll or AddWindowsPrinterConnection
wscript.sleep 100
For Each strPrn in arrPrinters
strPrinter = (strOldSrv & strPrn)
'wscript.echo "removing "  & strPrinter
strCmd = "rundll32 printui.dll,PrintUIEntry /dn /n """ & strPrinter & """ /q"
      objShell.Run strCmd,,true
'    objNetwork.RemoveWindowsPrinterConnection strOldSrv & strPrn
Next

'********************************************************************************************************************
' to make sure all printers are removed, Deletes RegistryKey with all subkeys in Network printers
'sPath = "Printers\Connections"
'lRC = DeleteRegEntry(HKEY_CURRENT_USER, sPath)
'Function DeleteRegEntry(sHive, sEnumPath)
' Attempt to delete key.  If it fails, start the subkey enumration process.
'lRC = objRegistry.DeleteKey(sHive, sEnumPath)
' The deletion failed, start deleting subkeys.
'If (lRC <> 0) Then
' Subkey Enumerator  
'On Error Resume Next  
'lRC = objRegistry.EnumKey(HKEY_CURRENT_USER, sEnumPath, sNames)  
'For Each sKeyName In sNames    
'If Err.Number <> 0 Then Exit For    
'lRC = DeleteRegEntry(sHive, sEnumPath & "\" & sKeyName)  
'Next  
'On Error Goto 0
' At this point we should have looped through all subkeys, trying to delete the key again.  
'lRC = objRegistry.DeleteKey(sHive, sEnumPath)
'End If
'End Function
' Now let's recreate only the "root" Key we deleted before
'objRegistry.CreateKey HKEY_CURRENT_USER,sPath

'********************************************************************************************************************
' we have zero network printers, let`s remove all unused drivers by using Microsoft`s own prndrvr.vbs
' first restart print spooler in order to release open files
'Set objWMIService = GetObject("winmgmts:" _
'    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
'Set colServiceList = objWMIService.ExecQuery _
'        ("Select * from Win32_Service where Name='Spooler'")
'For each objService in colServiceList
'     errReturn = objService.StopService()
'Next
'wscript.sleep 1000
'Set colServiceList = objWMIService.ExecQuery _
'    ("Select * from Win32_Service where Name='Spooler'")
'For each objService in colServiceList
'     errReturn = objService.StartService()
'Next
'oShell.Run "cscript %systemroot%\system32\prndrvr.vbs -x"

'********************************************************************************************************************
'Add new printers using either printui.dll or AddWindowsPrinterConnection
wscript.sleep 100
For Each strPrn in arrPrinters
strPrinter = (strNewSrv & strPrn)
'wscript.echo "installing "  & strPrinter
strCmd = "rundll32 printui.dll,PrintUIEntry /in /n """ & strPrinter & """ /u /q /Gw"
      objShell.Run strCmd,,true
'    objNetwork.AddWindowsPrinterConnection strNewSrv & strPrn
Next

'********************************************************************************************************************
' Try to put back the default printer
'Set objFile = objFSO.OpenTextFile(userprrf & lockfile)
'Do Until objFile.AtEndOfStream
'    strNewDefPrinter = objFile.ReadLine
'Loop
'objFile.Close

strNewDefault = (Replace(strdefPrinter,strOldSrv, strNewSrv))
'wscript.Echo "New default printer: " & strNewDefault
strCmd = "rundll32 printui.dll,PrintUIEntry /y /n """ & strrNewDefault & """ /u /q /Gw"
      objShell.Run strCmd,,true
'objNetwork.SetDefaultPrinter strNewDefault


'********************************************************************************************************************
' Tell the user to check his default printer
beep = chr(007)
objShell.Run "cmd /c @echo " & beep & beep, 0
'with createobject("wscript.shell")
'   .popup "Tous vos imprimantes réseau ont été installés. SVP vérifier et changer votre imprimante DÉFAULT si nécessaire.",30, "Printers Manager"
'end with
'objShell.Exec("control printers")

'********************************************************************************************************************
' We're done, let's leave a hidden file in userprofile, so at next login this script will exit
Set objFile = objFSO.CreateTextFile(userprrf & lockfile, true)
Set objFile = objFSO.GetFile(userprrf & lockfile)
objFile.Attributes = 2
Wscript.Quit

Thursday, May 01, 2014

Delete old printers and change the default

'Change default Printer and delete the old ones
'(c)2014 s@xxxxxxxx.com
' defaultlist example: service Client,\\2K12SRV\HP 4050 P005



PrintServer = "2K8SRV" 'Old Print server name goes here - case sensitive
listfile = "\defaultlist.txt"
lockfile = "\defaultprt"
Set objNetwork = CreateObject("WScript.Network")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objSysInfo = CreateObject("ADSystemInfo")
Set objShell =  CreateObject("WScript.Shell")
userprrf = objShell.Environment("PROCESS")("UserProfile")
strComputer = "."
'strCurPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(strComputer)
strCurPath = "\\2k12srv\netlogon\deploy" ' relpath doesn't seems to work on UNC
 wscript.echo strCurPath
If (objFSO.FileExists(userprrf & lockfile)) Then
 'Debug
 'with createobject("wscript.shell")
 '.popup userprrf & "Lockfile EXIST!" , 1 , "Info"
 'end with
 Wscript.Quit
End If

'On Error Resume Next
strName = objSysInfo.UserName
' Split full username by comma (warning: comma is a valid char in OU, verify personally that it doesn't exist in your OU!)
arrUserName = Split(strName, ",")
' remove OU= or DC= for the last 2 OU's
arrOU = Split(arrUserName(1), "=")
arrOU2 = Split(arrUserName(2), "=")
'put those OU toghether
strOU = arrOU2(1) & " " & arrOU(1)
' open the list of OU vs printers pairs
Set objFile = objFSO.OpenTextFile(strCurPath + listfile, 1)
 Do Until objFile.AtEndOfStream
 ' they are separated by comma, first is OU second is printer
 defaultArray = split(objFile.ReadLine,",")
 readOU=defaultArray(0)
 defaultprt=defaultArray(1)
 ' Debug
 'with createobject("wscript.shell")
 '.popup "Check: """ & strOU & """ = """ & readOU & """ Choose """ & defaultprt & """. " , 1 , "Info"
 'end with
 If strOU = readOU Then
  ' Debug
  'with createobject("wscript.shell")
  '.popup "Found: """ & strOU & """ = """ & readOU & """ Printer: """ & defaultprt & """. " , 5 , "Info"
  'end with
  ' first ensure that the printer is installed, then set it default
  objNetwork.AddWindowsPrinterConnection defaultprt
  objNetwork.SetDefaultPrinter defaultprt
  exit do
 End If
Loop
objFile.Close

'Remove old printers
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer")

For Each objPrinter in colInstalledPrinters
    'Debug
    'with createobject("wscript.shell")
  '.popup "Name: " & objPrinter.Name , 1 , "Info"
  'end with
  'Wscript.Echo "Name: " & objPrinter.Name
    i = 0
    ReDim Preserve arrPrinterName(i)
    arrPrinterName(i) = objPrinter.Name
        If InStr(arrPrinterName(i), PrintServer) Then
            Set objNetwork = WScript.CreateObject("WScript.Network")
            'Debug
        'with createobject("wscript.shell")
      '.popup "Removing: " & arrPrinterName(i) , 5 , "Info"
      'end with       
            objNetwork.RemovePrinterConnection arrPrinterName(i)
            i=i+1
        Else
            'Debug
        'with createobject("wscript.shell")
      '.popup "Skipped: " & arrPrinterName(i) , 5 , "Info"
      'end with       
        End If

Next

' Leave a lockfile in user's home
Set objFile1 = objFSO.CreateTextFile(userprrf & lockfile)
Wscript.Quit

Blog Archive