Zerto Virtual Replication APIs : Session API : Code Examples
  
Code Examples
For complete code examples, see Code Samples.
Python Code Examples
The following code samples are extracts from the fuller code example, Python Code.
Starting a Session with VMware vCenter Server or Microsoft SCVMM Credentials
The following code sample shows how to start a session with VMware vCenter Server or Microsoft SCVMM authentication, using the Requests library for making the REST call and the base64 library for password encryption.
import requests
import base64
 
def GenerateZertoRestSession_VcenterAuthentication(zvmIp, user, password):
  credStr = user + ":" + password
  encodedCredStr = "Basic " + base64.b64encode(credStr)
  print encodedCredStr
 
  payload = {"AuthenticationMethod": 1}
  dataval = json.dumps(payload)
  print (dataval)
 
  headers = {'Authorization': encodedCredStr, 'content-type': 'application/json'}
  url = "https://" + zvmIp + ":9669/v1/session/add"
  r = requests.post(url, data=dataval, headers=headers, verify=False)
  print r.status_code
  if(r.status_code != requests.codes.ok):
  raise Exception("Failed authenticating to ZVM")
  res = r.headers.get('x-zerto-session')
  print "session = " + res
  return res
Starting a Session with Windows Credentials
The following code sample shows how to start a session with Windows authentication, which is the default, using the Requests library for making the REST call and the base64 library for password encryption.
import requests
import base64
 
def GenerateZertoRestSession_WindowsAuthentication(zvmIp, user, password):
  credStr = user + ":" + password
  encodedCredStr = "Basic " + base64.b64encode(credStr)
  print encodedCredStr
 
  headers = {'Authorization': encodedCredStr}
  url = "https://" + zvmIp + ":9669/v1/session/add"
  r = requests.post(url, headers=headers, verify=False)
  print r.status_code
  if(r.status_code != requests.codes.ok):
    raise Exception("Failed authenticating to ZVM")
  res = r.headers.get('x-zerto-session')
  print "session = " + res
  return res
Ending a Session
The following code sample shows how to end a session.
import requests
 
def EndZertoRestSession(zvmIp, sessionId):
  url = "https://" + zvmIp + ":9669/v1/session"
  headers = {'x-zerto-session': sessionId, 'content-type': 'application/json'}
  r = requests.delete(url, headers=headers, verify=False)
  print r.status_codes
PowerShell Samples
Starting a Session with VMware vCenter Server or Microsoft SCVMM Credentials
The following code sample shows how to start a session with VMware vCenter Server or Microsoft SCVMM authentication.
$strZVMIP = "{ZVM IP}"
$strZVMPort = "{ZVM HTTPS port}"
$strZVMUser = "{ZVM user}"
$strZVMPwd = "{ZVM user password}"
## Perform authentication so that Zerto APIs can run. Return a session identifier that needs to be inserted in the header for subsequent requests.
function getxZertoSession ($userName, $password){
  $baseURL = "https://" + $strZVMIP + ":"+$strZVMPort
  $xZertoSessionURI = $baseURL +"/v1/session/add"
  $authInfo = ("{0}:{1}" -f $userName,$password)
  $authInfo = [System.Text.Encoding]::UTF8.GetBytes($authInfo)
  $authInfo = [System.Convert]::ToBase64String($authInfo)
  $headers = @{Authorization=("Basic {0}" -f $authInfo)}
  $body = '{"AuthenticationMethod": "1"}'
  $contentType = "application/json"
  $xZertoSessionResponse = Invoke-WebRequest -Uri $xZertoSessionURI -Headers $headers -Method POST -Body $body -ContentType $contentType
 
    #$xZertoSessionResponse = Invoke-WebRequest -Uri $xZertoSessionURI -Headers $headers -Body $body -Method POST
    return $xZertoSessionResponse.headers.get_item("x-zerto-session")
}
 
#Extract x-zerto-session from the response, and add it to the actual API:
$xZertoSession = getxZertoSession $strZVMUser $strZVMPwd
$zertoSessionHeader = @{"x-zerto-session"=$xZertoSession}
Starting a Session with Windows Credentials
To start a session with Windows authentication, replace the line in the above code:
$body = '{"AuthenticationMethod": "1"}'
with:
$body = '{"AuthenticationMethod": "0"}'
C# Code Samples
Starting a Session with VMware vCenter Server or Microsoft SCVMM Credentials
The code sample is extracted from the fuller code example, C# Code. The following code sample shows how to start a session with VMware vCenter Server or Microsoft SCVMM authentication:
...
string zvmip = args[0];
string zvmport = args[1];
string username = args[2];
string password = args[3];
string loginType = args.Length > 4 ? args[4] : "1";
string baseAddress = "https://" + zvmip + ":" + zvmport + "/v1/"
 
string addSessionUri = baseAddress + "/session/add";
HttpWebRequest request = WebRequest.Create(addSessionUri) as HttpWebRequest;
 
//logging-in is about ADDING a session with the POST http command
request.Method = "POST";
request.Timeout = 10000;
request.ContentLength = 0;
 
string prepareUserNamePassword = string.Format("{0}:{1}", username, password);
byte[] credentialsBytes = Encoding.ASCII.GetBytes(prepareUserNamePassword);
string encodedBasicAuthentication = Convert.ToBase64String(credentialsBytes);
string encodedCredentialsInBasicAuthenticationFormat = "Basic " + encodedBasicAuthentication;
 
byte[] byte1 = new ASCIIEncoding().GetBytes("{\"AuthenticationMethod\":"+ loginType + "}");
request.ContentLength = byte1.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(byte1, 0, byte1.Length);
 
HttpWebResponse httpResponse = request.GetResponse() as HttpWebResponse;
 
if (httpResponse.StatusCode == HttpStatusCode.OK) {
  //After a successful login your session-id is returned in the 'x-zerto-session' header
  m_sessionId = httpResponse.Headers.Get(c_authorizationHeader);
}
else {
  Console.WriteLine("request {0} failed with code: {1}, {2}", request, httpResponse.StatusCode, httpResponse.StatusDescription);
}
...
Starting a Session with Windows Credentials
To start a session with Windows authentication, replace the line in the above code:
string loginType = args.Length > 4 ? args[4] : "1";
with:
string loginType = args.Length > 4 ? args[4] : "0";
Ending a Session
The following code sample shows how to end a session:
private void LogOut() {
  string addSessionUri = m_baseAddress + "/session";
  HttpWebRequest request = WebRequest.Create(addSessionUri) as HttpWebRequest;
 
  //logging-out is about DELETING a session, with the DELETE http command
  request.Method = "DELETE";
  request.Timeout = 10000;
 
  //you need to set the id of the session to be deleted --> logged-out
  request.Headers.Add(c_authorizationHeader, m_sessionId);
 
  HttpWebResponse httpResponse = request.GetResponse() as HttpWebResponse;
 
  if (httpResponse.StatusCode == HttpStatusCode.OK) {
    m_sessionId = string.Empty;
    Console.WriteLine("\nLogged out - by deleting the session");
  }
  else {
    Console.WriteLine("Request {0} failed with code: {1}, {2}", request, httpResponse.StatusCode, httpResponse.StatusDescription);
  }
}