Acrobat X – Bulk Printing and Custom Header

Every year we need to print off hundreds of enrolment forms to verify details of new students and current students. Each of these forms is pre-filled with students details and there is a separate PDF for each student.

Previously I used Multiple PDF Printer but this no longer works with Acrobat X. Instead I created an Action Wizard that allows you to select the folder with all the PDFs and it will print them all to your default printer with the default settings.

I then added another step to the action that uses Javascript to extract the student’s name from the file name and added it as a header to each page of that file. Finally this was modified so that the name is always on the outer edge, when it is printed back to back and stapled on the left.

To create this you can follow the following directions or import the attached action.

  Print Ghost Enrolment Forms with Header (960 bytes, 2,338 hits)

Acrobat X - Edit Action

In Acrobat X:

  1. File -> Action Wizard -> Create New Action
  2. Click More Tools and then click Execute JavaScript and then click Print.
  3. Change Start with to Ask when Action is Started
  4. Click on the Options button for JavaScript and paste in the following:
var strFilename = this.documentFileName;
// A regular expression to acquire the base name of the file
// Removes everything before last underscore for Ghosted_EnrolmentForm_
var re = /.*\/|.*_|\.pdf$/ig;
// Get student name by stripping path and everything to left of underscore
var strFilename = strFilename.replace(re,"").replace(",",", ");
var pageAmount = this.numPages; // Finds the length of the PDF

for (i = 0; i 	{
	if (i % 2 == 0) {
		// Odd
		this.addWatermarkFromText({
			cText: strFilename,
			nStart: i,
			nEnd: i,
			nFontSize: 11,
			nTextAlign: app.constants.align.right,
			nHorizAlign: app.constants.align.right,
			nVertAlign: app.constants.align.top,
			nHorizValue: -28, nVertValue: -10
		});
	}	else  {
		// Even
		this.addWatermarkFromText({
			cText: strFilename,
			nStart: i,
			nEnd: i,
			nFontSize: 11,
			nTextAlign: app.constants.align.left,
			nHorizAlign: app.constants.align.left,
			nVertAlign: app.constants.align.top,
			nHorizValue: 28, nVertValue: -10
		});
	}
}
  1. Click OK. Then click Saveand type in a name for the action and a description.

    Add Folders or Files

  2. Set your default printer and printer settings to how you want your documents to print (e.g. Double sided, Stapled).
  3. File -> Action Wizard -> <Your new action>
  4. Click Next on summary screen. You may tick Don’t show again box if you wish.
  5. Click Add Files… drop down and choose Add Folders… and select the folder holding the PDFs.
  6. Click Next and it will start adding the header and printing the files.

Useful Links:

  • Base for the JavaScript header is from Steve Wareham’s block post on Adding a Dynamic Stamp to a PDF.
  • The code to extract file name is from Adobe JavaScript Reference
Posted in Windows | Tagged , , , , , , | Leave a comment

Bulk Converting Global Groups to Universal and Mail Enabling

We have started trying to better organise our groups into a more role based system, so that membership of one group is based on a role rather than a person. That way if the person holding a position changes (holiday, retirement, etc) we just make one change and the replacement user gets all the correct rights. e.g. <user> -> HT Subject -> Executive, rather than <user> -> Executive.

The problem with this is when an email is sent to a mail enabled group, all the member groups of that group must be mail enabled for their members to receive the email. So I needed to bulk mail enable a container of groups, and also hide these new groups from the Address Book as they don’t need to be visible to staff.

Exchange 2010 only allows you to mail enable a group if it is a Universal group, and then only one at a time from the EMC. To convert all the Global groups in a particular container to universal groups, I used the following Power Shell command.

Import-Module ActiveDirectory
# List Tables
Get-ADGroup -SearchScope Subtree -SearchBase "OU=StaffGroups,OU=Staff,DC=win" -Filter {GroupCategory -eq "Security" -and GroupScope -eq "Global"}  | Format-Table

# Convert Global groups to Universal
Get-ADGroup -SearchScope Subtree -SearchBase "<code>OU=StaffGroups,OU=Staff,DC=win</code>" -Filter {GroupCategory -eq "Security" -and GroupScope -eq "Global"}  | Set-ADGroup -GroupScope Universal

Once converted to Universal groups I wanted to Enable the Groups as Distribution groups in Exchange and hide them from the global Address Book. These groups are role based and need to exist for group expansion in Exchange, but I don’t want them visible to everyone.

# Load AD Modules
Import-Module ActiveDirectory

# Load Exchange Snapins
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
. $env:ExchangeInstallPath\bin\RemoteExchange.ps1
Connect-ExchangeServer -auto

# Get list of Groups not Mail Enabled
$b = Get-ADGroup -SearchScope Subtree -SearchBase "OU=StaffGroups,OU=Staff,DC=win" -Filter {GroupCategory -eq "Security" -and GroupScope -eq "Universal" -and mail -notlike "*"}

# Enable email for each group, use the Group name without spaces as Alias
$b | ForEach-Object { Enable-DistributionGroup -Identity $_.DistinguishedName -Alias ($_.Name -replace '\s|,|\.') }

# Hide the newly created groups from Global Address book
$b | ForEach-Object { Set-DistributionGroup -Identity $_.DistinguishedName -HiddenFromAddressListsEnabled $true}
 

Notes:

  • Details on replacing letters for alias is from here.
  • Mike Pfeiffer’s blog had great instructions on how to load Exchange snap-ins into a normal PowerShell session, such as in ISE.
  • I found a few sites that mentioned using get-group instead of get-adgroup. Not sure why the wrong command is given. Petri
Posted in Active Directory, Exchange | Tagged , , , , , , , | Leave a comment

Encrypt Offline Files – Access Denied

On a Windows 7 laptop I was trying to set up Offline Files with encryption enabled. After syncing the files and going into Manage Offline Files -> Encryption -> Encrypt everything seemed to go OK, but it would then keep reporting Access Denied when it tried to sync any new files.
After some searching I found this post which mentioned an expired Recovery Key in Group Policy. After checking the Group Policy object on the server I discovered there was an old Recovery Key stored in the EFS policy from when it was first set up. After regenerating the key and importing into policy, a gpupdate /force on laptop and reboot fixed the issue.

Posted in Windows | Tagged , , , , , , , | Leave a comment

Fuji-Xerox Network Scanning: Error 027-516

As part of a test for removing legacy protocols from the network I disabled NetBIOS over TCP/IP to see if any system would be adversely affected.

Disabled NetBIOS

After disabling NetBIOS for the server used by our Fuji-Xeros ApeosPort-II 4000 Photocopier, the Network Scanning feature was unable to upload the scanned file to the SMB server. Instead it would return a 027-516 error code.

To verify the problem I Enabled NetBIOS and it immediately started working again.

I contacted Fuji-Xerox to check if they had a fix for the problem. I was advised that this can only be changed in newer versions, ApeosPort >=3, and that is was considered a “Feature”. The only way for an AP-II device to work with a server with NetBIOS disabled is to use the FTP transmit method.

AP-III NetBIOS Setting

After checking on one of our ApeosPort-III C3300, I found the page mentioned that allows the setting to be changed.

It appears that the use of NetBIOS by the APII is hardcoded and although it has DNS settings set, they are ignored for server name resolution. Considering this Photocopier is still being produced and sold I find it interesting that it relies on outdated protocols like NetBIOS. (ApeosPort-II 3000, 4000, 5010, 6000, 7000 are the main black and white photocopiers available to DET NSW Schools)

Posted in Windows | Tagged , , , , , , | 1 Comment

Papercut

I have received a few questions asking about Papercut so here are some of the details about it and what we use it for.

Papercut can run on a Windows Server (2003, 2008 or 2008 R2) using windows print queues or a Novell Linux OES server with iPrint (CUPS & SAMBA), it is written in Java with some wrappers for the OS in use.

We originally ran it on a Server 2003 R2 (x86) but have recently updated to a Windows 2008 R2 (x64)print server. The main reason for the upgrade was to provide up to date drivers for Windows 7 32 & 64bit. We also run the Papercut MF version which costs A LOT more, but allows you to use it with external devices, such as photocopiers.

Papercut has some really useful features, Card recharge allows you to generate top up cards and print them out yourself. Then you just cut them up and given them to the office (or canteen) to sell to the students. Makes recharging much easier and no need for office staff to login to an admin console to top up accounts.

We recently had a student laptop roll-out (NSW DER), these laptops are not on our domain so needed an alternative way to print. Papercut has a feature called WebPrint which allows students to upload MS office or PDF files to a website and have them printed to the chosen printer. You need to run software for it on a windows pc (server or client) which automatically opens the document and prints it to the chosen printer. As our Print server is running Windows and is a virtual machine we just configured it to auto-login as a limited user we created and installed Office, and Acrobat.

We use the reports function for auditing staff accounts and charging printer usage back to faculties. Staff are automatically added to different charge accounts based on their AD group membership.

We have just started using Advanced Scripting to charge staff different prices than students on shared copiers and printers.
The following script is what we use, as it is based on how faculties are invoiced at the end of each term. It is based on the Papercut recipe “Discount for staff” with a few changes.

/*
* Change Pricing for staff
*
* Staff are charged based on cost to school.
*
*/
function printJobHook(inputs, actions) {

var DISCOUNT_GROUP   = "Staff-All";
var COST_COLOUR  = 0.07; // Click Rate of Colour
var COST_BW  = 0.02;  // Click Rate of B/W
var COST_A4  = 0.01;  // Price per page of A4
var COST_A3  = 0.03;  // Price per page of A3

/*
* This print hook will need access to all job details
* so return if full job analysis is not yet complete.
* The only job details that are available before analysis
* are metadata such as username, printer name, and date.
*
* See reference documentation for full explanation.
*/

if (!inputs.job.isAnalysisComplete) {
	// No job details yet so return.
	return;
}

if (inputs.user.isInGroup(DISCOUNT_GROUP)) {
	// Debug messages are written to [install-path]/server/logs/server.log
	actions.log.debug("Cost before discount: " + inputs.job.cost);

	// Initial 0
	var newCost = 0;

	// Includes Duplex
	if (inputs.job.paperSizeName == "A4") {
		newCost = inputs.job.totalSheets * COST_A4;
	}
	else {
		newCost = inputs.job.totalSheets * COST_A3 ;
	}

	newCost += inputs.job.totalGrayscalePages * COST_BW;
	newCost += inputs.job.totalColorPages * COST_COLOUR;

	 actions.job.setCost(newCost);

	actions.log.debug("Staff Pricing on " + inputs.job.printerName + " For " + inputs.job.totalSheets +
		" sheets had " + inputs.job.totalGrayscalePages + " B/W & " +
		inputs.job.totalColorPages + " Colour, Cost after discount: " + newCost);

	// Record that as discount was applied in the job comment.
	actions.job.addComment("Staff Pricing applied. Had " + inputs.job.totalGrayscalePages + " B/W & " +
	inputs.job.totalColorPages + " Colour");
	}
}

Other useful features:

  • Students and staff see a summary of how many pages they are going to print, which helps reduce accidental printing of entire chapters of text instead of just a few pages.
  • Logs and statistics show which printers are getting used, how much is getting printed, and who printed the document but didn’t collect it.
  • Great support. I have contacted them over a number of issues and they have always gotten back quickly with good ideas, or have added features in later versions.

Downsides:

  • Although the price for education version of Papercut NG is not too bad, to get the MF version which supports copiers it costs around twice as much. Also you then need cost recovery devices for the copiers ~AUD$1,800 each, and there are annual support and maintenance costs ~AUD$1,000/year.

If you want to get an idea of how much printing your staff and students or just want to keep a record of who is printing what (like you could do easily with iPrint)  try the free Papercut Print Logger.

Posted in Linux, Novell, Utilities, Windows | Tagged , , , , , , , , , | 1 Comment

Pre-populate Users names and email address in Office and Acrobat

Often you would like some personal information filled in for the user before they start the application. E.g. Why have Office or Acrobat ask for the users name when it is already stored in active directory?

Here are some simple VBScripts that can be added to a log on script or similar to pre-fill these for the user. Once you know the registry location where the identity information is stored it is quite easy to fill those values as part of a login script.

Microsoft Office

' Original MS Office script written by David Isaacs
Set oShell = CreateObject("WScript.Shell")

On Error Resume Next

strUsername = oShell.ExpandEnvironmentStrings("%USERNAME%")
strUserdomain = oShell.ExpandEnvironmentStrings("%USERDOMAIN%")

Set oUser = GetObject("WinNT://" & strUserdomain & "/" & strUsername & ",user")

oShell.RegWrite "HKCU\Software\Microsoft\Office\Common\UserInfo\UserInitials", strUsername
oShell.RegWrite "HKCU\Software\Microsoft\Office\Common\UserInfo\UserName", oUser.Fullname

Adobe Acrobat Pro and Reader

This will set the full name, office, email address and your company for multiple versions of Acrobat and Acrobat reader. You can add even more versions by adding extra lines to the array.

Also if you modified Acrobat to install with Acrobat.com disabled, but now wish to enable it this will enable it. We originally had it disabled, but found email and network form submission did not work properly until it was enabled.

The method for accessing the AD User object was posted by Mike Walker in this thread.

' Configure Adobe Acrobat default settings
' Written by James Rudd
Set oShell = CreateObject("WScript.Shell")
Set oFso = CreateObject("Scripting.FileSystemObject")

' Set the different registry paths for Acrobat
Dim regPaths(2)
regPaths(0) = "HKEY_CURRENT_USER\Software\Adobe\Adobe Acrobat\9.0\"  'For Acrobat Pro 9
regPaths(1) = "HKEY_CURRENT_USER\Software\Adobe\Acrobat Reader\9.0\"  'For Acrobat Reader 9
regPaths(2) = "HKEY_CURRENT_USER\Software\Adobe\Acrobat Reader\8.0\"  'Same for Acrobat Reader 8

On Error Resume Next

' Create the ADSystem Information Object
Set objADSystemInfo = CreateObject("ADSystemInfo")
' Get the current information into a new Object
Set objUser = GetObject("LDAP://" & objADSystemInfo.UserName)

For Each regPath In regPaths
 'Enable Acrobat.com by deleting key that contains disabling entries.
 oShell.regdelete regPath & "Workflows\"

 'Set Acrobat Identity Info
 oShell.RegWrite regPath & "Identity\tEMail", objUser.mail, "REG_SZ"
 oShell.RegWrite regPath & "Identity\tName", objUser.givenName & " " & objUser.sn, "REG_SZ"
 oShell.RegWrite regPath & "Identity\tFirstName", objUser.givenName, "REG_SZ"
 oShell.RegWrite regPath & "Identity\tLastName", objUser.sn, "REG_SZ"
 oShell.RegWrite regPath & "Identity\tCorporation", "Your Company Name", "REG_SZ"
 oShell.RegWrite regPath & "Identity\tDepartment", objUser.physicalDeliveryOfficeName, "REG_SZ"

 'Set Default Acrobat Collaboration details
 oShell.RegWrite regPath & "ShareIdentity\tEMail", objUser.mail, "REG_SZ"
 oShell.RegWrite regPath & "ShareIdentity\tFullName", objUser.givenName & " " & objUser.sn, "REG_SZ"
 oShell.RegWrite regPath & "ShareIdentity\tCorporation", "Your Company Name", "REG_SZ"
 oShell.RegWrite regPath & "ShareIdentity\tDepartment", objUser.physicalDeliveryOfficeName, "REG_SZ"
Next

Combined

The following script combines both Office and Acrobat data in to one, and reuses the same data objects rather than use two different connection techniques.

' Configure Adobe Acrobat and MS Office user settings
' Written by James Rudd

Const strCompanyName = "Your School Name"

Set oShell = CreateObject("WScript.Shell")
Set oFso = CreateObject("Scripting.FileSystemObject")

' Create the ADSystem Information Object
Set objADSystemInfo = CreateObject("ADSystemInfo")
' Get the current information into a new Object
Set objUser = GetObject("LDAP://" & objADSystemInfo.UserName)

On Error Resume Next

'Office Details
oShell.RegWrite "HKCU\Software\Microsoft\Office\Common\UserInfo\UserInitials", objUser.sAMAccountName, "REG_SZ"
oShell.RegWrite "HKCU\Software\Microsoft\Office\Common\UserInfo\UserName", objUser.givenName & " " & objUser.sn, "REG_SZ"
' If set by installer Company Name is overidden on load.
oShell.RegWrite "HKCU\Software\Microsoft\Office\Common\UserInfo\Company", strCompanyName, "REG_SZ"

' Set the different registry paths for Acrobat
Dim regPaths(2)
regPaths(0) = "HKEY_CURRENT_USER\Software\Adobe\Adobe Acrobat\9.0\"  'For Acrobat Pro 9
regPaths(1) = "HKEY_CURRENT_USER\Software\Adobe\Acrobat Reader\9.0\"  'For Acrobat Reader 9
regPaths(2) = "HKEY_CURRENT_USER\Software\Adobe\Acrobat Reader\8.0\"  'Same for Acrobat Reader 8

For Each regPath In regPaths
 'Enable Acrobat.com by deleting key that contains disabling entries.
 oShell.regdelete regPath & "Workflows\"

 'Set Acrobat Identity Info
 oShell.RegWrite regPath & "Identity\tEMail", objUser.mail, "REG_SZ"
 oShell.RegWrite regPath & "Identity\tName", objUser.givenName & " " & objUser.sn, "REG_SZ"
 oShell.RegWrite regPath & "Identity\tFirstName", objUser.givenName, "REG_SZ"
 oShell.RegWrite regPath & "Identity\tLastName", objUser.sn, "REG_SZ"
 oShell.RegWrite regPath & "Identity\tCorporation", "Your Company Name", "REG_SZ"
 oShell.RegWrite regPath & "Identity\tDepartment", objUser.physicalDeliveryOfficeName, "REG_SZ"

 'Set Default Acrobat Collaboration details
 oShell.RegWrite regPath & "ShareIdentity\tEMail", objUser.mail, "REG_SZ"
 oShell.RegWrite regPath & "ShareIdentity\tFullName", objUser.givenName & " " & objUser.sn, "REG_SZ"
 oShell.RegWrite regPath & "ShareIdentity\tCorporation", strCompanyName, "REG_SZ"
 oShell.RegWrite regPath & "ShareIdentity\tDepartment", objUser.physicalDeliveryOfficeName, "REG_SZ"
Next
Posted in Windows | Tagged , , , , , , | Leave a comment

Using BackupPC with DiskShadow to backup open files

Introduction

This post is to assist in the setup of a BackupPC system able to backup in use files by using MS volume snapshots. It also has the benefit of only having the RSync daemon running during the backup which increases security.

This method is based on some other posts I have seen using VShadow, Backing Up Open Files on Windows with Rsync, and some suggestions on DiskShadow but goes further in using RSync as a system service giving full access to files, and removing the need to use winexe.

General Outline

  1. Create a new user backuppc (try to match case of the user on Linux). Very limited rights
  2. Install Cygwin with RSync, OpenSSH and configure them
  3. Create a scheduled task to run as SYSTEM when triggered by a certain event
  4. Set BackupPC server for passwordless login to host and modify Pre/Post Dump Cmds

Overview

In Windows 7 and Server 2008 R2 elevation is required to create snapshots. As a remote SSH connection cannot bypass UAC a way is needed to create the snapshot, bypassing the elevation prompt. I also wished to run the Rsync Daemon as SYSTEM user so it has rights to view all files.

To do this I moved all the elevated tasks into a Task Scheduler item that is set to run as SYSTEM, and is triggered by an Event log event.

  1. BackupPC performs a password-less key SSH logon to client
  2. It runs a script which creates an event log entry and then waits for RSync to start before returning to BackupPC and starting the backup.
  3. Task scheduler is triggered by Event Log and starts DiskShadow as SYSTEM.
  4. Disk shadow creates a shadow of any chosen volumes, mounts them and then starts RSync.
    It then waits for a file to be created by BackupPC at the end of the backup telling it to stop RSync and delete the snaphots.

Flow and triggers

BackupPC Server Host PC
backuppc User backuppc User SYSTEM
Start Backup
SSH to Host PC
Log Event Diskshadow: Snaphsot
Start Rsync
Close and return
Begin Backup
Finish Backup
SSH to Host PC
Create a Wake.up file
Stop Rsync
Delete Snaphost

Host PC

Create a new user, backuppc, you can limit this account further in Security policy after everything is configured.

Create a BackupPC folder and add the following scripts to it. These are also available in a zip file.

  BackupPC Config Files (4.2 KiB, 1,966 hits)

You will need to modify paths depending on where you create the folder. I used C:\cygwin\BackupPC but a better location may be C:\cygwin\usr\share\BackupPC

Most of these scripts are just modified versions of the ones written for VShadow, changed to work with DiskShadow and Task Scheduler.

pre-cmd.vbs

' This file starts the commands
' It will start the snapshot process and quite once RSync is running

Const Rsync = "C:\cygwin\var\run\rsyncd.pid"
Const Flag = "C:\cygwin\var\run\wake.up"
Set fso = CreateObject("Scripting.FileSystemObject")
'
' Pid file shouldn't be there already
' Check /stop service , still there delete
'
If DoesFileExist(Rsync)=0 Then
	fso.DeleteFile(Rsync)
End If
'
' Nor should "wake.up"
'
If DoesFileExist(Flag)=0 Then
   fso.DeleteFile(Flag)
End If

Set objShell = CreateObject("WScript.Shell")
' objShell.Exec "C:\BackupPC\backuppc.cmd > " & Log

' This writes event log entry that triggers task scheduler to start system process
' that takes snapshot and starts RSync
objShell.Exec "Logevent.exe -r ""BackupPC"" -e 10 -s S ""Backup Start"" "
Wscript.Echo "Sent BackupPC Event Log Trigger"

'
' Just sleep until the file "rsyncd.pid" appears
'

While DoesFileExist(Rsync)
   wscript.sleep 10000
Wend

' functions

function DoesFileExist(FilePath)
Dim fso
	Set fso = CreateObject("Scripting.FileSystemObject")
	if not fso.FileExists(FilePath) then
		DoesFileExist = -1
	else
		DoesFileExist = 0
	end if
	Set fso = Nothing

end function

backuppc.cmd

c:
cd C:\cygwin\BackupPC
diskshadow /s DiskShadowScript.txt /l C:\cygwin\var\log\diskshadow.log
del C:\cygwin\var\tmp\*.cab /q
c:cd C:\cygwin\BackupPCdiskshadow /s DiskShadowScript.txt /l C:\cygwin\var\log\diskshadow.log
del C:\cygwin\var\tmp\*.cab /q

DiskShadowScript.txt

#DiskShadow script file

#Make shadows persistent, No writers as data volume

# If backing up C: and any app files (ntds, database, etc) use writers

#SET CONTEXT PERSISTENT NOWRITERS

SET CONTEXT PERSISTENT

#Cab location for process

SET METADATA C:\cygwin\var\tmp\backup.cab

SET VERBOSE ON

BEGIN BACKUP

#Alias volume with alias

ADD VOLUME C: ALIAS SystemData

ADD VOLUME F: ALIAS UserData

#Create Snapshot

CREATE

#Expose the volume and run command file then unexpose

EXPOSE %UserData% B:

EXPOSE %SystemData% T:

EXEC C:\cygwin\BackupPC\Serverbackup.cmd

UNEXPOSE B:

UNEXPOSE T:

END BACKUP

#Delete the shadow copy

DELETE SHADOWS SET %VSS_SHADOW_SET%

#End of script

Serverbackup.cmd

REM Start RSync now that Snapshots are created

net start rsyncd

REM Need to wait until backup completed

cscript "C:\cygwin\BackupPC\sleep.vbs"

Logevent.exe -r "BackupPC" -e 20 -s S "Backup Completed"

sleep.vbs

Const Rsync = "C:\cygwin\var\run\rsyncd.pid"
Const Flag = "C:\cygwin\var\run\wake.up"
Set fso = CreateObject("Scripting.FileSystemObject")

' Just sleep until the file "rsyncd.pid" appears
While DoesFileExist(Rsync)
   wscript.sleep 10000
Wend

' Now sleep until the file "wake.up" appears
While DoesFileExist(Flag)
   wscript.sleep 10000
Wend

fso.DeleteFile(Flag)

' It's time to kill Rsync
'Stop Service
strServiceName = "rsyncd"
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery("Select * from Win32_Service Where Name ='" & strServiceName & "'")
For Each objService in colListOfServices
    objService.StopService()
	Wscript.Echo "RSyncD Stopped"
Next

' Wait for Rsync to let go
wscript.sleep 5000

' Delete PID file
If DoesFileExist(Rsync)=0 Then
   fso.DeleteFile(Rsync)
End If

' functions
function DoesFileExist(FilePath)
Dim fso
	Set fso = CreateObject("Scripting.FileSystemObject")
	if not fso.FileExists(FilePath) then
		DoesFileExist = -1
	else
		DoesFileExist = 0
	end if
	Set fso = Nothing

end function

Cygwin

Install Cygwin and choose to install packages RSync and OpenSSH

Start an elevated Cygwin (Run as an Administrator )

Config

Cygwin 1.7 changes the way to ignore NT Security from the nontsec environment to modifying fstab file.

In your prefered editor modify /etc/fstab and uncomment the bottom line and add noacl as below, this tells it to ignore security :

none /cygdrive cygdrive binary,noacl,posix=0,user 0 0

Run following to update group and user lists (if on a domain only add the users you want)

[bashlight=1]mkpasswd –l >/etc/passwd
mkgroup –l /etc/group[/bash]

OpenSSH

Configure Open SSH using ssh-host-config, create both the accounts it suggests for privilege isolation and running the service (cyg_service & sshd).
This should also automatically add the Firewall Exceptions (SSHD).

Setting up Keyless

Login as backuppc user.
Use

runas /user:backuppc cmd

Or

runas /user:domain\backuppc cmd

Run c:\cygwin\Cygwin.bat to start Cygwin as BackupPC user

You need to add the id_rsa.pub file from the BackupPC user on BackupPC server to C:\cygwin\home\backuppc\.ssh\authorized_keys If you have not already created one follow the instructions below in BackupPC – SSH section.

RSync

To install RSync as a system service use:

C:\cygwin\bin\cygrunsrv.exe -I rsyncd -d "RSync Daemon" -O --type manual -p /bin/rsync.exe -f "Used by BackupPC to remotely access files for backup" -a " --config=/etc/rsyncd.conf --daemon --no-detach"

Modify the /etc/rsyncd.conf file to reflect what drives you want to backup. It is better to edit this file later after you have modified the DiskShadowScript.txt and changed which drive letter it exposes shadows as.

Add a RSync exception to the firewall.

Open Windows Firewall with Advanced Security and choose Inbound Rules, New Rule, Program,  Next

Browse to C:\cygwin\bin\rsync.exe and then choose your options and name the rule

When finished open the rule, click Scope tab and add a Remote IP, that of the BackupPC server. This restricts RSync to only be accessible from BackupPC. You may also wish to similarly modify SSHD to only allow SSH access from BackupPC server.

DiskShadow

If you are backing up a windows Server 2008 or 2008 R2 host you already have DiskShadow installed. However, if you are running Windows 7 or Vista you will need to grab a copy from an equivalent server (x86 or x64). It is located in the System32 directory and you will also need the language file from the en-US folder.

I have zipped the files needed for x86 and x64 if you do not have immediate access to a Server.

  DiskShadow (362.0 KiB, 2,933 hits)

 (The x86 files are from Server 2008 and x64 are from 2008 R2)

Copy the files from your architecture to the system32 directory and en-US subdirectory.

LogEvent

To generate the custom event log entry a tool from the Windows 2000 Resource kit is used, LogEvent, (Download). This needs to be either placed in the Path (e.g. Windows dir) or scripts need to directly call it.

Task Scheduler

The easiest way to configure this is to manually run LogEvent once to generate an event in the log.

Logevent.exe -r "BackupPC" -e 10 -s S "Backup Start"

Then open Event Viewer, Select the new BackupPC event and choose Attach Task to this Event, and in the wizard click next until it asks for the program, then give it C:\cygwin\BackupPC\backuppc.cmd

On Final page choose to Open Properties when you click Finish

Click the Change User or Group button and type in System as the user  and click OK. Also tick the Run with highest privileges box

BackupPC Server

SSH

This section is only needed if you do not already have keys generated for the backuppc user.

Login as backuppc user, either with password or simply “su – backuppc” from root

Generate SSH Keys, ssh-keygen –t rsa, do not set a password. Copy id_rsa.pub into C:\cygwin\home\backuppc\.ssh \authorized_keys

Test by running ssh -v backuppc@host to test the connection

BackupPC Host File

In the web interface change the following for the host.

DumpPreUserCmd:  $sshPath -q -x -l backuppc $host cscript "C:\cygwin\BackupPC\pre-cmd.vbs"
 DumpPostUserCmd: $sshPath -q -x -l backuppc $host echo "Complete: $xferOK" > /var/run/wake.up

Test Run

If you have existing backups from a previous RSync config, it is a good idea to run a full backup to ensure any in use files are part of the base. In my case I also changed the noacl flag which affected the file attributes RSync sees.

Tips

Set your antivirus to exclude the exposed drives. As they are read only it just slows down the reading of files by RSync.

Downloads

  DiskShadow (362.0 KiB, 2,933 hits)

  BackupPC Config Files (4.2 KiB, 1,966 hits)

Updates

  • While writing this up I found a good alternative way of using VShadow with SSH to backup in use files, that uses the AT command instead of task scheduler to get around UAC, BackupPC with ssh/rsync/VSS on Windows Server. The only down side to this method is the SSH connection requires an Admin account, but if configured securely this should be fine. It also a lot simpler to configure as it does not require configuring Task Scheduler.
  • There is a great script for managing VSS by Mark Baggett and Tim “LaNMaSteR53” Tomes VSSOwn.vbs which was discussed in one of their security blog posts, Safely Dumping Hashes from Live Domain Controllers
Posted in Linux, Utilities, Windows | Tagged , , , , , , , , , , , , , , | 8 Comments