About the Author

Source Code

Important Note:
This script has not been checked by Spiceworks. Please understand the risks before using it.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

'User configurable variables'Server names must be seperated by a comma. Names are case sensitive so you have to get the'name of your server PERFECT!strServers="ServerName,ServerName2"strUser="root"strpw="mypassword"strXenServer="XenServer IP Address or hostname"strBackupPath="d:\xsbackups"'Make sure to use the short file name formatstrXenCenterPath="C:\Progra~1\Citrix\XenCenter\"'Set to TRUE if you want to send a status emailbinSendEmail=TRUEstrSMTPFrom="XSLiveBackup@mycompany.com"strSMTPTo="spiceworkshelpdesk@mycompany.com"strSMTPRelay="smtp relay IP address or host name"'Number of days to keep the logs and backup filesnumKeepLogs=10numKeepBackups=5'************************************************************************************************'Do not edit beyond this point'************************************************************************************************DimerrStatus,strLogNameDimfs,logFileIfRight(strBackupPath,1)="\"ThenstrBackupPath=Left(strBackupPath,Len(strBackupPath)-1)EndIfIfRight(strXenCenterPath,1)<>"\"ThenstrXenCenterPath=strXenCenterPath&"\"EndIfstrRunXE=strXenCenterPath&"xe.exe -s "&strXenServer&" -u "&strUser&" -pw "&strpw&" "arrBackups=Split(strServers,",")constForAppending=8errStatus=0'Set some global objectsSetWshShell=CreateObject("Wscript.shell")'Create the log file and introduction information into log fileCalllogSetup'Check if XenCenter Path is correctIffs.FileExists(strXenCenterPath&"xe.exe")Then'Loop through all selected servers and back them upForiServers=0toUBound(arrBackups)CallbackupVM(Trim(arrBackups(iServers)))NextElsewriteLog("XenCenter not found, aborting backup!")errStatus=UBound(arrBackups)+2EndIf'Finish up the log fileCalllogClose'Send status message via emailCallsendMsg'Script completed -- REM line below out if you want to run this in a scheduled taskwscript.echo"Done!"SubbackupVM(strServer)'First, check that the VM exists, and get UUID and name-label information. It is possible to 'name a snapshot as a backup source, but this script does not allow it, so checking for that tooSetobjExec=WSHshell.Exec(strRunXE&"vm-list params=uuid,name-label,is-a-snapshot name-label="&strServer)strStatus="Not Found"DoWhileNotobjExec.StdOut.AtEndOfStreamstrStatus="Found"strUUID=stripValue(objExec.StdOut.ReadLine())strVM=stripValue(objExec.StdOut.ReadLine())strSnapShot=stripValue(objExec.StdOut.ReadLine())strTemp=objExec.StdOut.ReadLine()strTemp=objExec.StdOut.ReadLine()IfstrSnapShot="false"andstrVM<>"Control domain on host"ThenstrStatus="Good"EndIfLoopIfstrStatus="Not Found"ThenstrResult=SetErrorStatus("Add")writeLog("No VM by that name: "&strServer)ExitSubElseIfstrStatus="Found"ThenstrResult=SetErrorStatus("Add")writeLog("VM is a Snapshot or Template, no backup performed: "&strServer)ExitSubElsewriteLog("VM Found: "&strServer)EndIf'Remove old backupswriteLog("Cleaning up old backup files")SetoFolder=fs.GetFolder(strBackupPath)SetoAllFiles=oFolder.FilesnumDM=0ForEachoFileinoAllFilesIfLeft(oFile.Name,7)="Backup-"andDateDiff("d",NOW,oFile.DateLastModified)>numKeepBackupsThennumDM=numDM+1ReDimPreservearrFileName(numDM)arrFileName(numDM)=oFile.Namefs.DeleteFileoFile.PathEndIfNextwriteLog(numDM&" files deleted")Forx=1tonumDMwriteLog(" "&arrFileName(x))Next'Snapshot the VMwriteLog("Snapshoting server: "&strServer)SetobjExec=WSHshell.Exec(strRunXE&"vm-snapshot new-name-label="&strServer&"-XenServer-Live-Backup uuid="&strUUID)strSSID=objExec.StdOut.ReadLine()strResult=strSSIDDoWhileNotobjExec.StdOut.AtEndOfStreamstrTemp=objExec.StdOut.ReadLine()writeLog(strTemp)strResult=strResult&":"&strTempLoopIfInStr(UCase(strResult),"ERROR")ThenwriteLog("Error creating snapshot, see above")ExitSubEndIf'Set snapshot to NOT be a templatewriteLog("Setting snapshot status...")SetobjExec=WSHshell.Exec(strRunXE&"template-param-set is-a-template=false uuid="&strSSID)DoWhileNotobjExec.StdOut.AtEndOfStreamwriteLog(objExec.StdOut.ReadLine())Loop'Export to backup destinationstrTime=Replace(Now(),"/","-")strTime=Replace(strTime," ","-")strTime=Replace(strTime,":","-")strName="Backup-"&strServer&"-"&strTime&".xva"writeLog("Backup filename: "&strName)SetobjExec=WSHshell.Exec(strRunXE&"vm-export vm="&strSSID&" filename="&strBackupPath&"\"&strName)strResult=""DoWhileNotobjExec.StdOut.AtEndOfStreamstrTemp=objExec.StdOut.ReadLine()writeLog(strTemp)strResult=strResult&":"&strTempLoopIfInStr(UCase(strResult),"SUCCEEDED")=0ThenstrResult=SetErrorStatus("Add")writeLog("************** Error during backup of "&strServer&" **************")EndIf'Remove the snapshotSetobjExec=WSHshell.Exec(strRunXE&"vm-uninstall uuid="&strSSID&" force=true")strResult=""DoWhileNotobjExec.StdOut.AtEndOfStreamstrTemp=objExec.StdOut.ReadLine()writeLog(strTemp)strResult=strResult&" "&strTempLoopIfInStr(strResult,"All objects destroyed")=0ThenstrResult=SetErrorStatus("Add")writeLog("**************Error deleting snapshot for "&strServer&" **************")EndIfEndSubFunctionstripValue(strValue)arrStrip=Split(strValue,":")stripValue=Trim(arrStrip(1))EndFunctionSubwriteLog(strText)logFile.WriteLineNow()&": "&strTextEndSubFunctionSetErrorStatus(strTask)IfstrTask="Add"ThenerrStatus=errStatus+1SetErrorStatus=errStatusElsenumServers=UBound(arrBackups)+1IferrStatus=0ThenSetErrorStatus="Success"ElseIferrStatus>=numServersThenSetErrorStatus="Failed"ElseSetErrorStatus="Partial Failure"EndIfEndIfEndFunctionSublogSetupSetfs=CreateObject("Scripting.FileSystemObject")IfNotfs.FolderExists(strBackupPath)Thenfs.CreateFolder(strBackupPath)EndIfSetoFolder=fs.GetFolder(strBackupPath)SetoAllFiles=oFolder.FilesForEachoFileinoAllFilesIfLeft(oFile.Name,16)="XenServerBackups"andDateDiff("d",NOW,oFile.DateLastModified)>numKeepLogsThenfs.DeleteFileoFile.PathEndIfNextstrLogName="XenServerBackups-"&Replace(Date,"/","-")&".log"SetlogFile=fs.OpenTextFile(strBackupPath&"\"&strLogName,ForAppending,True)logFile.WriteLine"=========================================================================================================="logFile.WriteLine"Backup for: "&Now()logFile.WriteLine"=========================================================================================================="Forx=0toUBound(arrBackups)Ifx=0ThenlogFile.WriteLine"Servers targeted for backup: "&arrBackups(x)ElselogFile.WriteLine" "&arrBackups(x)EndIfNextlogFile.WriteLine"Backup User : "&strUserlogFile.WriteLine"Password : *********"logFile.WriteLine"Xen Server : "&strXenServerlogFile.WriteLine"Backup Destination : "&strBackupPathlogFile.WriteLineEndSubSublogClose'Finish up the log filelogFile.WriteLinestrStatus=SetErrorStatus("Read")logFile.WriteLine"Backup completed on "&Now()logFile.WriteLine"Backup Status: "&strStatuslogFile.WriteLinelogFile.WriteLinelogFile.CloseEndSubSubsendMsg'Send status message via emailIfbinSendEmail=FalseThenExitSubEndIfSetoMessage=CreateObject("CDO.Message")oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing")=2oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver")=strSMTPRelayoMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25oMessage.Configuration.Fields.UpdatestrStatus=SetErrorStatus("Read")oMessage.Subject="XenServer Backup Completed. Status: "&strStatus&". Date: "&Now()oMessage.From=strSMTPFromoMessage.To=strSMTPTostrText=vbCRLF&"XenServer Backup Completed. "&vbCRLF&vbCRLFstrText=strText&"Backup User : "&strUser&vbCRLFstrText=strText&"Password : *********"&vbCRLFstrText=strText&"Xen Server : "&strXenServer&vbCRLFstrText=strText&"Backup Destination : "&strBackupPath&vbCRLFstrText=strText&vbCRLFstrText=strText&"Backup Status : "&strStatusoMessage.TextBody=strTextoMessage.AddAttachmentstrBackupPath&"\"&strLogNameoMessage.SendEndSub

Interesting, looks like there's a problem between discovering the UUID of the server (8:23:31) and then backing it up (8:23:33)...
Not sure what's happening, but are the 2 hosts running the same version of XenServer? Also, are you running the script from the same server (same version of XenCenter?)
I've updated the script to do some logging of the snapshot information to see if something funky is happening... I have a possible fix but wanted to see the log beforehand. Just download the new version, set it up and run and post the log again.
Thanks!

Programer: If you look at the first log entry at 10:21:51 AM you'll see the error you're getting. Looks like your Storage Pool doesn't have enough space to support a snapshot of the server.
I've gone ahead and modified the script to give it some error code handling for the snapshot section.

Hello Martin,
Nice script, just a few questions:
1. how can i overwrite the last backup instead of add another one next to it (if i set the numKeepBackups = 0, nothing happens)?
2. it doesn't work with two or more VM's, it just backups 1 VM, the first in the list......

Ok, have a good holiday and i'll do some testing also
PS: after some testing it looks like the script backs up the first and the last server in the list (one one host) if in the list:
strServers = "srv1,srv2,srv3"
numKeepLogs = 1
numKeepBackups = 1
then only srv1 and srv3 are backed up, and the last server in the list keeps backing up (loop)

Hi Loenatic, no sorry I haven't had any time to work on it. Maybe later this week and I'm traveling next week so might be a little while. Sorry!
Part of the problem is my XenServer setup is only 1 server, so I have to build at least 2 morethen start testing so will take awhile to get this going...