example2.pl: add a second example
[pve-apiclient.git] / examples / example2.pl
1 #!/usr/bin/perl
2
3 # NOTE: you need to run this on a PVE host, or modify the source to
4 # provide username/password/hostname from somewhere else.
5
6 use strict;
7 use warnings;
8
9 use PVE::APIClient::LWP;
10
11 use PVE::AccessControl;
12 use PVE::INotify;
13 use JSON;
14
15 # normally you use username/password,
16 # but we can simply create a ticket and CRSF token if we are root
17 # running on a pve host
18
19 my $hostname = PVE::INotify::read_file("hostname");
20
21 my $ticket = PVE::AccessControl::assemble_ticket('root@pam');
22 my $csrftoken = PVE::AccessControl::assemble_csrf_prevention_token('root@pam');
23
24 sub get_local_cert_fingerprint {
25 my ($node) = @_;
26
27 my $cert_path = "/etc/pve/nodes/$node/pve-ssl.pem";
28 my $custom_cert_path = "/etc/pve/nodes/$node/pveproxy-ssl.pem";
29
30 $cert_path = $custom_cert_path if -f $custom_cert_path;
31
32 my $bio = Net::SSLeay::BIO_new_file($cert_path, 'r');
33 my $cert = Net::SSLeay::PEM_read_bio_X509($bio);
34 Net::SSLeay::BIO_free($bio);
35
36 my $fp = Net::SSLeay::X509_get_fingerprint($cert, 'sha256');
37 die "got empty fingerprint" if !defined($fp) || ($fp eq '');
38
39 return $fp;
40 }
41
42 my $local_fingerprint = get_local_cert_fingerprint($hostname);
43
44 my $conn = PVE::APIClient::LWP->new(
45 #username => 'root@pam',
46 #password => 'yourpassword',
47 ticket => $ticket,
48 csrftoken => $csrftoken,
49 host => $hostname,
50 # add local hosts cert fingerprint
51 cached_fingerprints => {
52 $local_fingerprint => 1,
53 });
54
55 my $res = $conn->get("api2/json/access/domains", {});
56 print to_json($res, { pretty => 1, canonical => 1});