#!/usr/bin/perl
use strict;
use warnings;
use LWP::UserAgent;
use LWP::Protocol::https;
use HTTP::Cookies;
use Cwd 'abs_path';
my $USERNAME='mylogin@pam';
my $PASSWORD='mypsw';
my $VMID=100;
my $NODE='svc3';
my $PROXY='10.0.0.222';
my $FPATH = "spiceproxy";
my $PPATH = 'C:\Program Files\VirtViewer\bin';
my $DATA = api_req($PROXY, '/api2/json/access/ticket', 'username='.$USERNAME.'&password='.$PASSWORD);
my ($TICKET) = $DATA =~ /\"ticket\"\:\"(.*?)\"/;
my ($CSRF) = $DATA =~ /\"CSRFPreventionToken\"\:\"(.*?)\"/;
$DATA = api_req($PROXY, '/api2/spiceconfig/nodes/'.$NODE.'/qemu/'.$VMID.'/spiceproxy', 'proxy='.$PROXY, ['CSRFPreventionToken',$CSRF], [['PVEAuthCookie',$TICKET]]);
open(my $fh, '>', $FPATH);
print $fh $DATA;
close $fh;
my $abs_path = abs_path($FPATH);
chdir($PPATH) or die("Can't change to dir $PPATH: $!\n");;
exec("remote-viewer.exe", $abs_path);
sub api_req
{
my ($prx, $url, $data, $head, $cook) = @_;
my $ua = LWP::UserAgent->new(ssl_opts => { verify_hostname => 0 },);
# Create a request
my $req = HTTP::Request->new(POST => 'https://'.$prx.':8006'.$url);
$req->content_type('application/x-www-form-urlencoded');
$req->content($data);
$req->header($head->[0], $head->[1]) if(defined($head));
print $req->headers->as_string."\n";
if(defined($cook))
{
my $cookie_jar = HTTP::Cookies->new();
foreach my $c (@$cook)
{
$cookie_jar->set_cookie(0,$c->[0], $c->[1],'/',$prx,8006,0,0,86400,0);
}
$ua->cookie_jar($cookie_jar);
}
my $res = $ua->request($req);
# Check the outcome of the response
if ($res->is_success)
{
return $res->decoded_content;
}
else
{
die $res->status_line, "\n";
}
}