aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/scripts/astcli
blob: 635de5841749d4caf3438d14e16d9f1e29bae108 (plain)
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
#!/usr/bin/perl -w

use strict;
use Net::Telnet;
use Getopt::Long;

# Created by: David Van Ginneken
# Bird's the Word Technologies
# davevg@btwtech.com
#
# And distributed under the terms of the GPL
#
my ($user, $pw, $host, $port) = (undef, undef, 'localhost', 5038);

process_credentials('/etc/astcli.conf');
process_credentials("$ENV{HOME}/.astcli");
GetOptions("username=s" => \$user, "secret=s" => \$pw, "host=s" => \$host, "port=s" => \$port);

my $action = join(" ", @ARGV);

&usage if (!defined $user || !defined $pw);

my $tc = new Net::Telnet (Timeout => 10,
    Errmode => "die",
    Host    => $host,
    Port    => $port);
# Login with our username and secret.
$tc->open  ();
$tc->print ("Action: Login");
$tc->print ("Username: $user");
$tc->print ("Secret: $pw");
$tc->print ("Events: off");
$tc->print (""); 
# Check for login success.
my ($pre, $match) = $tc->waitfor ("/Message: .*/");
unless (($pre =~ m/Success/) && ($match =~ m/Authentication/)) {
  print "Server Authentication failed.\n";
  exit;
}

# Send a single command to the manager connection handle (global $tc).
# Assumes things always work well :-)
sub send_command($) {
	my $command = shift;

	$tc->print ("Action: Command");
	$tc->print ("Command: $command");
	$tc->print ("");
	my ($pre, undef) = $tc->waitfor ("/--END COMMAND--.*/");
	$pre =~ s/^\n\n//g;
	$pre =~ s/Privilege: Command\n//;
	$pre =~ s/Response: Follows\n//;
	print $pre;
}

# If the user asked to send commands from standard input:
if ($action eq '-') {
	while (<>) {
		chomp;
		send_command($_)
	}
	exit 0;
}

# Otherwise just send the command:
send_command($action);

# parses a configuration file into the global $user and $pw.
sub process_credentials {
	# Process the credentials found..
	my $file = shift;

	# silently fail if we can't read the file:
	return unless (-r $file);
	open (my $fh, "<$file") or return;
	while (<$fh>) {
		chomp;
		(undef,$user) = split(/[,=]/, $_) if $_ =~ /user(name)?[,=]/i;
		(undef,$pw) = split(/[,=]/, $_) if $_ =~ /(secret|passw(or)?d|pwd?)[,=]/i;
		(undef,$host) = split(/[,=]/, $_) if $_ =~ /host(name)?[,=]/i;
		(undef,$port) = split(/[,=]/, $_) if $_ =~ /port(num|no)?[,=]/i;
	}
}

sub usage {
	print STDERR "astcli [-u <username> -s <passwd>] [-h host] [-p port] <cli-command>\n";
	print STDERR "       (command '-' - take commands from input)\n";
	exit;
}