Advertisement
swaggboi

cpcodes.pl

Feb 3rd, 2020
1,143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 2.01 KB | None | 0 0
  1. #!/usr/bin/env perl
  2.  
  3. # Daniel Bowling <dbowling@akamai.com>
  4. # Feb 2020
  5. # version 0.11 - update $ver @ line 50
  6.  
  7. use strict;
  8. use warnings;
  9. use Net::HTTP;
  10. use Getopt::Long qw(:config no_ignore_case);
  11.  
  12. sub get_cp {
  13.     # make the request
  14.     my $s = Net::HTTP->new(
  15.         'Host'   => "@_"
  16.         ) || die $@;
  17.     $s->write_request(
  18.         'HEAD'   => "/",
  19.         'Pragma' => "akamai-x-get-cache-key"
  20.         );
  21.  
  22.     # read the headers
  23.     my @ckey;
  24.     while (my $line = <$s>) {
  25.         # find the cache key header
  26.         if ($line =~ /X-Cache-Key:/) {
  27.             @ckey = split(/\//, $line); # Split ckey by forward-slash
  28.             last;                       # Break out of loop after split
  29.         }
  30.     }
  31.  
  32.     # return cache key or question mark if error
  33.     if (@ckey) {
  34.         return $ckey[3]
  35.     } else {
  36.         return "?"
  37.     }
  38. }
  39.  
  40. # Parse options
  41. GetOptions(
  42.     'delimiter|d=s' => \my $sep,
  43.     'header|H'      => \my $head,
  44.     'help|h',       # technically does nothing right now
  45.     'version|v'     => \my $ver
  46.     );
  47.  
  48. # Version info option
  49. if ($ver) {
  50.     $ver = '0.11';
  51.     print "$ver\n";
  52.     exit;
  53. }
  54.  
  55. # Choose what to do given args, STDIN, or null
  56. if (@ARGV) {
  57.     @_ = @ARGV                           # use args or...
  58. } elsif (! -t STDIN) {
  59.     chomp (@_ = <STDIN>)                 # use STDIN or...
  60. } else {
  61.     print "Usage: $0 <HOSTNAME(S)>\n\n"; # null, print help
  62.     die <<'OPTIONS';
  63. Find CP code from hostnames provided as arguments or STDIN.
  64.     -d, --delimiter=DELIM   Change delimiting character (default is TAB)
  65.     -H, --header            Print header with output lines
  66.     -h, --help              Print this help message
  67.     -v, --version           Print version
  68. OPTIONS
  69. }
  70.  
  71. # Delimiter character
  72. $sep = "\t" if ! $sep;
  73.  
  74. # Print header if -H|--header is specified
  75. print "Hostname${sep}CP Code\n" if $head;
  76.  
  77. # Begin parsing hostnames
  78. for (@_) {
  79.     # print hostname, delimiter, CP code and newline
  80.     print $_ . $sep . get_cp($_) . "\n";
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement