More.pm 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. package Net::OpenSSH::More;
  2. use strict;
  3. use warnings;
  4. use parent 'Net::OpenSSH';
  5. use Data::UUID ();
  6. use Expect ();
  7. use File::HomeDir ();
  8. use File::Temp ();
  9. use Fcntl ();
  10. use IO::Pty ();
  11. use IO::Socket::INET ();
  12. use IO::Socket::INET6 ();
  13. use IO::Stty ();
  14. use List::Util qw{first};
  15. use Net::DNS::Resolver ();
  16. use Net::IP ();
  17. use Time::HiRes ();
  18. use Term::ANSIColor ();
  19. =head1 NAME
  20. Net::OpenSSH::More
  21. =head1 DESCRIPTION
  22. Submodule of Net::OpenSSH that contains many methods that were
  23. otherwise left "as an exercise to the reader" in the parent module.
  24. Highlights:
  25. * Persistent terminal via expect for very fast execution, less forking.
  26. * Usage of File::Temp and auto-cleanup to prevent lingering ctl_path cruft.
  27. * Ability to manipulate incoming text while streaming the output of commands.
  28. * Run perl subroutine refs you write locally but execute remotely.
  29. * Many shortcut methods for common system administration tasks
  30. * Registration method for commands to run upon DESTROY/before disconnect.
  31. * Automatic reconnection ability upon connection loss
  32. =head1 SYNOPSIS
  33. use Net::OpenSSH::More;
  34. my $ssh = Net::OpenSSH::More->new(
  35. 'host' => 'some.host.test',
  36. 'port' => 69420,
  37. 'user' => 'azurediamond',
  38. 'password' => 'hunter2',
  39. );
  40. ...
  41. =head1 SEE ALSO
  42. Net::OpenSSH
  43. Net::OpenSSH::More::Linux
  44. =cut
  45. my %defaults = (
  46. 'user' => $ENV{'USER'} || getpwuid($>),
  47. 'port' => 22,
  48. 'use_persistent_shell' => 0,
  49. 'output_prefix' => '',
  50. 'home' => File::HomeDir->my_home,
  51. 'retry_interval' => 6,
  52. 'retry_max' => 10,
  53. );
  54. our %cache;
  55. our $disable_destructor = 0;
  56. ###################
  57. # PRIVATE METHODS #
  58. ###################
  59. my $die_no_trace = sub {
  60. my ( $full_msg, $summary ) = @_;
  61. $summary ||= 'FATAL';
  62. my $carp = $INC{'Carp/Always.pm'} ? '' : ' - Use Carp::Always for full trace.';
  63. die "[$summary] ${full_msg}${carp}";
  64. };
  65. my $check_local_perms = sub {
  66. my ( $path, $expected_mode, $is_dir ) = @_;
  67. $is_dir //= 0;
  68. my @stat = stat($path);
  69. $die_no_trace->(qq{"$path" must be a directory that exists}) unless !$is_dir ^ -d _;
  70. $die_no_trace->(qq{"$path" must be a file that exists}) unless $is_dir ^ -f _;
  71. $die_no_trace->(qq{"$path" could not be read}) unless -r _;
  72. my $actual_mode = $stat[2] & 07777;
  73. $die_no_trace->( sprintf( qq{Permissions on "$path" are not correct: got=0%o, expected=0%o}, $actual_mode, $expected_mode ) ) unless $expected_mode eq $actual_mode;
  74. return 1;
  75. };
  76. my $resolve_login_method = sub {
  77. my ($opts) = @_;
  78. my $chosen = first { $opts->{$_} } qw{key_path password};
  79. $chosen //= '';
  80. undef $chosen if $chosen eq 'key_path' && !$check_local_perms->( $opts->{'key_path'}, 0600 );
  81. return $chosen if $chosen;
  82. return 'SSH_AUTH_SOCK' if $ENV{'SSH_AUTH_SOCK'};
  83. my $fallback_path = "$opts->{'home'}/.ssh/id";
  84. ( $opts->{'key_path'} ) = map { "${fallback_path}_$_" } ( first { -s "${fallback_path}_$_" } qw{dsa rsa ecdsa} );
  85. $die_no_trace->('No key_path or password specified and no active SSH agent; cannot connect') if !$opts->{'key_path'};
  86. $check_local_perms->( $opts->{'key_path'}, 0600 ) if $opts->{'key_path'};
  87. return $opts->{'key_path'};
  88. };
  89. my $get_dns_record_from_hostname = sub {
  90. my ( $hostname, $record_type ) = @_;
  91. $record_type ||= 'A';
  92. my $reply = Net::DNS::Resolver->new()->search( $hostname, $record_type );
  93. return unless $reply;
  94. return { map { $_->type() => $_->address() } grep { $_->type eq $record_type } ( $reply->answer() ) };
  95. };
  96. # Knock on the server till it responds, or doesn't. Try both ipv4 and ipv6.
  97. my $ping = sub {
  98. my ($opts) = @_;
  99. my $timeout = 30;
  100. my ( $host_info, $ip, $r_type );
  101. if ( my $ip_obj = Net::IP->new( $opts->{'host'} ) ) {
  102. $r_type = $ip_obj->ip_is_ipv4 ? 'A' : 'AAAA';
  103. $ip = $opts->{'host'};
  104. }
  105. else {
  106. my $host_info = first { $get_dns_record_from_hostname->( $opts->{'host'}, $_ ) } qw{A AAAA};
  107. ($r_type) = keys(%$host_info);
  108. if ( !$host_info->{$r_type} ) {
  109. require Data::Dumper;
  110. die "Can't determine IP type. " . Data::Dumper::Dumper($host_info);
  111. }
  112. $ip = $host_info->{$r_type};
  113. }
  114. my %family_map = ( 'A' => 'INET', 'AAAA' => 'INET6' );
  115. my $start = time;
  116. while ( ( time - $start ) <= $timeout ) {
  117. return 1 if "IO::Socket::$family_map{$r_type}"->new(
  118. 'PeerAddr' => $ip,
  119. 'PeerPort' => $opts->{'port'},
  120. 'Proto' => 'tcp',
  121. 'Timeout' => $timeout,
  122. );
  123. diag( { '_opts' => $opts }, "[DEBUG] Waiting for response on $ip:$opts->{'port'} ($r_type)..." ) if $opts->{'debug'};
  124. select undef, undef, undef, 0.5; # there's no need to try more than 2 times per second
  125. }
  126. return 0;
  127. };
  128. my $init_ssh = sub {
  129. my ( $class, $opts ) = @_;
  130. # Always clear the cache if possible when we get here.
  131. if ( $opts->{'_cache_index'} ) {
  132. local $disable_destructor = 1;
  133. undef $cache{ $opts->{'_cache_index'} };
  134. }
  135. # Try not to have disallowed ENV chars. For now just transliterate . into _
  136. # XXX TODO This will be bad with some usernames/domains.
  137. # Maybe need to run host through punycode decoder, etc.?
  138. if ( !$opts->{'_host_sock_key'} ) {
  139. $opts->{'_host_sock_key'} = "NET_OPENSSH_MASTER_$opts->{'host'}_$opts->{'user'}";
  140. $opts->{'_host_sock_key'} =~ tr/./_/;
  141. }
  142. # Make temp dir go out of scope with this object for ctl paths, etc.
  143. # Leave no trace!
  144. $opts->{'_tmp_obj'} = File::Temp->newdir() if !$opts->{'_tmp_obj'};
  145. my $tmp_dir = $opts->{'_tmp_obj'}->dirname();
  146. diag( { '_opts' => $opts }, "Temp dir: $tmp_dir" ) if $opts->{'debug'};
  147. my $temp_fh;
  148. # Use an existing connection if possible, otherwise make one
  149. if ( $ENV{ $opts->{'_host_sock_key'} } && -e $ENV{ $opts->{'_host_sock_key'} } ) {
  150. $opts->{'external_master'} = 1;
  151. $opts->{'ctl_path'} = $ENV{ $opts->{'_host_sock_key'} };
  152. }
  153. else {
  154. if ( !$opts->{'debug'} ) {
  155. open( $temp_fh, ">", "$tmp_dir/STDERR" ) or $die_no_trace->("Can't open $tmp_dir/STDERR for writing: $!");
  156. $opts->{'master_stderr_fh'} = $temp_fh;
  157. }
  158. $opts->{'ctl_dir'} = $tmp_dir;
  159. $opts->{'strict_mode'} = 0;
  160. $opts->{'master_opts'} = [
  161. '-o' => 'StrictHostKeyChecking=no',
  162. '-o' => 'GSSAPIAuthentication=no',
  163. '-o' => 'UserKnownHostsFile=/dev/null',
  164. '-o' => 'ConnectTimeout=180',
  165. '-o' => 'TCPKeepAlive=no',
  166. ];
  167. push @{ $opts->{'master_opts'} }, '-v' if $opts->{'debug'};
  168. if ( $opts->{'key_path'} ) {
  169. push @{ $opts->{'master_opts'} }, '-o', 'IdentityAgent=none';
  170. }
  171. # Attempt to use the SSH agent if possible. This won't hurt if you use -k or -P.
  172. # Even if your sock doesn't work to get you in, you may want it to do something on the remote host.
  173. # Of course, you may want to disable this with no_agent if your system is stupidly configured
  174. # with lockout after 3 tries and you have 4 keys in agent.
  175. # Anyways, don't just kill the sock for your bash session, restore it in DESTROY
  176. $opts->{'_restore_auth_sock'} = delete $ENV{SSH_AUTH_SOCK} if $opts->{'no_agent'};
  177. $opts->{'forward_agent'} = 1 if $ENV{'SSH_AUTH_SOCK'};
  178. }
  179. my $status = 0;
  180. my $self;
  181. foreach my $attempt ( 1 .. $opts->{'retry_max'} ) {
  182. local $@;
  183. my $up = $ping->($opts);
  184. if ( !$up ) {
  185. $die_no_trace->("$opts->{'host'} is down!") if $opts->{die_on_drop};
  186. diag( { '_opts' => $opts }, "Waiting for host to bring up sshd, attempt $attempt..." );
  187. next;
  188. }
  189. # Now, per the POD of Net::OpenSSH, new will NEVER DIE, so just trust it.
  190. my @base_module_opts =
  191. qw{host user port password passphrase key_path gateway proxy_command batch_mode ctl_dir ctl_path ssh_cmd scp_cmd rsync_cmd remote_shell timeout kill_ssh_on_timeout strict_mode async connect master_opts default_ssh_opts forward_agent forward_X11 default_stdin_fh default_stdout_fh default_stderr_fh default_stdin_file default_stdout_file default_stderr_file master_stdout_fh master_sdterr_fh master_stdout_discard master_stderr_discard expand_vars vars external_master default_encoding default_stream_encoding default_argument_encoding password_prompt login_handler master_setpgrp master_pty_force};
  192. my $class4super = "Net::OpenSSH::More";
  193. # Subclassing here is a bit tricky, especially *after* you have gone down more than one layer.
  194. # Ultimately we only ever want the constructor for Net::OpenSSH, so start there and then
  195. # Re-bless into subclass if that's relevant.
  196. $self = $class4super->SUPER::new( map { $_ => $opts->{$_} } grep { $opts->{$_} } @base_module_opts );
  197. my $error = $self->error;
  198. next unless ref $self eq 'Net::OpenSSH::More' && !$error;
  199. bless $self, $class if ref $self ne $class;
  200. if ( $temp_fh && -s $temp_fh ) {
  201. seek( $temp_fh, 0, Fcntl::SEEK_SET );
  202. local $/;
  203. $error .= " " . readline($temp_fh);
  204. }
  205. if ($error) {
  206. $die_no_trace->("Bad password passed, will not retry SSH connection: $error.") if ( $error =~ m{bad password} && $opts->{'password'} );
  207. $die_no_trace->("Bad key, will not retry SSH connection: $error.") if ( $error =~ m{master process exited unexpectedly} && $opts->{'key_path'} );
  208. $die_no_trace->("Bad credentials, will not retry SSH connection: $error.") if ( $error =~ m{Permission denied} );
  209. }
  210. if ( defined $self->error && $self->error ne "0" && $attempt == 1 ) {
  211. $self->diag( "SSH Connection could not be established to " . $self->{'host'} . " with the error:", $error, 'Will Retry 10 times.' );
  212. }
  213. if ( $status = $self->check_master() ) {
  214. $self->diag( "Successfully established connection to " . $self->{'host'} . " on attempt #$attempt." ) if $attempt gt 1;
  215. last;
  216. }
  217. sleep $opts->{'retry_interval'};
  218. }
  219. $die_no_trace->("Failed to establish SSH connection after $opts->{'retry_max'} attempts. Stopping here.") if ( !$status );
  220. # Setup connection caching if needed
  221. if ( !$opts->{'no_cache'} && !$opts->{'_host_sock_key'} ) {
  222. $self->{'master_pid'} = $self->disown_master();
  223. $ENV{ $opts->{'_host_sock_key'} } = $self->get_ctl_path();
  224. }
  225. #Allow the user to unlink the host sock if we need to pop the cache for some reason
  226. $self->{'host_sock'} = $ENV{ $opts->{'_host_sock_key'} };
  227. return $self;
  228. };
  229. my $connection_check = sub {
  230. my ($self) = @_;
  231. return 1 if $self->check_master;
  232. local $@;
  233. local $disable_destructor = 1;
  234. eval { $self = $init_ssh->( __PACKAGE__, $self->{'_opts'} ) };
  235. return $@ ? 0 : 1;
  236. };
  237. # Try calling the function.
  238. # If it fails, then call $connection_check to reconnect if needed.
  239. #
  240. # The goal is to avoid calling $connection_check
  241. # unless something goes wrong since it adds about
  242. # 450ms to each ssh command.
  243. #
  244. # If the control socket has gone away, call
  245. # $connection_check ahead of time to reconnect it.
  246. my $call_ssh_reinit_if_check_fails = sub {
  247. my ( $self, $func, @args ) = @_;
  248. $connection_check->($self) if !-S $self->{'_ctl_path'};
  249. local $@;
  250. my @ret = eval { $self->$func(@args) };
  251. my $ssh_error = $@ || $self->error;
  252. warn "[WARN] $ssh_error" if $ssh_error;
  253. return @ret if !$ssh_error;
  254. $connection_check->($self);
  255. return ( $self->$func(@args) );
  256. };
  257. my $post_connect = sub {
  258. my ( $self, $opts ) = @_;
  259. $self->{'persistent_shell'}->close() if $self->{'persistent_shell'};
  260. undef $self->{'persistent_shell'};
  261. return;
  262. };
  263. my $trim = sub {
  264. my ($string) = @_;
  265. return '' unless length $string;
  266. $string =~ s/^\s+//;
  267. $string =~ s/\s+$//;
  268. return $string;
  269. };
  270. my $send = sub {
  271. my ( $self, $line_reader, @command ) = @_;
  272. $self->diag( "[DEBUG][$self->{'_opts'}{'host'}] EXEC " . join( " ", @command ) ) if $self->{'_opts'}{'debug'};
  273. my ( $pty, $err, $pid ) = $call_ssh_reinit_if_check_fails->( $self, 'open3pty', @command );
  274. $die_no_trace->("Net::OpenSSH::open3pty failed: $err") if ( !defined $pid || $self->error() );
  275. $self->{'_out'} = "";
  276. $line_reader = sub {
  277. my ( $self, $out, $stash_param ) = @_;
  278. $out =~ s/[\r\n]{1,2}$//;
  279. $self->{$stash_param} .= "$out\n";
  280. return;
  281. }
  282. if ref $line_reader ne 'CODE';
  283. # TODO make this async so you can stream STDERR *in order*
  284. # with STDOUT as well
  285. # That said, most only care about error if command fails, so...
  286. my $out;
  287. $line_reader->( $self, $out, '_out' ) while $out = $pty->getline;
  288. $pty->close;
  289. # only populate error if there's an error #
  290. $self->{'_err'} = '';
  291. $line_reader->( $self, $out, '_err' ) while $out = $err->getline;
  292. $err->close;
  293. waitpid( $pid, 0 );
  294. return $? >> 8;
  295. };
  296. my $TERMINATOR = "\r\n";
  297. my $send_persistent_cmd = sub {
  298. my ( $self, $command, $uuid ) = @_;
  299. $uuid //= Data::UUID->new()->create_str();
  300. $command = join( ' ', @$command );
  301. my $actual_cmd = "UUID='$uuid'; echo \"BEGIN \$UUID\"; $command; echo \"___\$?___\"; echo; echo \"EOF \$UUID\"";
  302. $self->diag("[DEBUG][$self->{'_opts'}{'host'}] EXEC $actual_cmd") if $self->{'_opts'}{'debug'};
  303. #Use command on bash to ignore stuff like aliases so that we have a minimum level of PEBKAC errors due to aliasing cp to cp -i, etc.
  304. $self->{'expect'}->print("${actual_cmd}${TERMINATOR}");
  305. # Rather than take the approach of cPanel, which commands then polls async,
  306. # it is more straightforward to echo unique strings before and after the command.
  307. # This made getting the return code somewhat more complicated, as you can see below.
  308. # That said, it also makes you not have to worry about doing things asynchronously.
  309. $self->{'expect'}->expect( $self->{'_opts'}{'expect_timeout'}, '-re', qr/BEGIN $uuid/m );
  310. $self->{'expect'}->expect( $self->{'_opts'}{'expect_timeout'}, '-re', qr/EOF $uuid/m ); # If nothing is printed in timeout, give up
  311. # Get the actual output, remove terminal grunk
  312. my $message = $trim->( $self->{'expect'}->before() );
  313. $message =~ s/[\r\n]{1,2}$//; # Remove 'secret newline' control chars
  314. $message =~ s/\x{d}//g; # More control chars
  315. $message = Term::ANSIColor::colorstrip($message); # Strip colors
  316. # Find the exit code
  317. my ($code) = $message =~ m/___(\d*)___$/;
  318. unless ( defined $code ) {
  319. # Tell the user if they've made a boo-boo
  320. my $possible_err = $trim->( $self->{'expect'}->before() );
  321. $possible_err =~ s/\s//g;
  322. $die_no_trace->("Runaway multi-line string detected. Please adjust the command passed.") if $possible_err =~ m/\>/;
  323. $die_no_trace->(
  324. "Could not determine exit code!
  325. It timed out (went $self->{'_opts'}{'expect_timeout'}s without printing anything).
  326. Run command outside of the persistent terminal please."
  327. );
  328. }
  329. $message =~ s/___(\d*)___$//g;
  330. return ( $message, $code );
  331. };
  332. my $do_persistent_command = sub {
  333. my ( $self, $command, $no_stderr ) = @_;
  334. if ( !$self->{'persistent_shell'} ) {
  335. my ( $pty, $pid ) = $call_ssh_reinit_if_check_fails->( $self, 'open2pty', $self->{'_remote_shell'} );
  336. die "Got no pty back from open2pty: " . $self->error if !$pty;
  337. # You might think that the below settings are important.
  338. # In most cases, they are not.
  339. $pty->set_raw();
  340. $pty->stty( 'raw', 'icrnl', '-echo' );
  341. $pty->slave->stty( 'raw', 'icrnl', '-echo' );
  342. #Hook in expect
  343. $self->diag("[DEBUG][$self->{'_opts'}{'host'}] INIT expect on for PTY with pid $pid") if $self->{'_opts'}{'debug'};
  344. $self->{'expect'} = Expect->init($pty);
  345. $self->{'expect'}->restart_timeout_upon_receive(1); #Logabandon by default
  346. # XXX WARNING bashisms. That said, I'm not sure how to better do this yet portably.
  347. my $expect_env_cmd = "export PS1=''; export TERM='dumb'; unset HISTFILE; export FOE='configured'; stty raw icrnl -echo; unalias -a; echo \"EOF=\$FOE\"";
  348. $self->diag("[DEBUG][$self->{'_opts'}{'host'}] EXEC $expect_env_cmd") if $self->{'_opts'}{'debug'};
  349. $self->{'expect'}->print("${expect_env_cmd}${TERMINATOR}");
  350. $self->{'expect'}->expect( $self->{'_opts'}{'expect_timeout'}, '-re', qr/EOF=configured/ );
  351. $self->{'expect'}->clear_accum();
  352. #cache
  353. $self->{'persistent_shell'} = $pty;
  354. $self->{'persistent_pid'} = $pid;
  355. }
  356. #execute the command
  357. my $uuid = Data::UUID->new()->create_str();
  358. push @$command, '2>', "/tmp/stderr_$uuid.out" unless $no_stderr;
  359. my ( $oot, $code ) = $send_persistent_cmd->( $self, $command, $uuid );
  360. $self->{'_out'} = $oot;
  361. unless ($no_stderr) {
  362. #Grab stderr
  363. ( $self->{'_err'} ) = $send_persistent_cmd->( $self, [ '/usr/bin/cat', "/tmp/stderr_$uuid.out" ] );
  364. #Clean up
  365. $send_persistent_cmd->( $self, [ '/usr/bin/rm', '-f', "/tmp/stderr_$uuid.out" ] );
  366. }
  367. return int($code);
  368. };
  369. #######################
  370. # END PRIVATE METHODS #
  371. #######################
  372. =head1 METHODS
  373. =head2 new
  374. Instantiate the object, establish the connection. Note here that I'm not allowing
  375. a connection string like the parent module, and instead exploding these out into
  376. opts to pass to the constructor. This is because we want to index certain things
  377. under the hood by user, etc. and I *do not* want to use a regexp to pick out
  378. your username, host, port, etc. when this problem is solved much more easily
  379. by forcing that separation on the caller's end.
  380. ACCEPTS:
  381. * %opts - <HASH> A hash of key value pairs corresponding to the what you would normally pass in to Net::OpenSSH,
  382. along with the following keys:
  383. * use_persistent_shell - Whether or not to setup Expect to watch a persistent TTY. Less stable, but faster.
  384. * expect_timeout - When the above is active, how long should we wait before your program prints something
  385. before bailing out?
  386. * no_agent - Pass in a truthy value to disable the SSH agent. By default the agent is enabled.
  387. * die_on_drop - If, for some reason, the connection drops, just die instead of attempting reconnection.
  388. * output_prefix - If given, is what we will tack onto the beginning of any output via diag method.
  389. useful for streaming output to say, a TAP consumer (test) via passing in '# ' as prefix.
  390. * debug - Pass in a truthy value to enable certain diag statements I've added in the module and pass -v to ssh.
  391. * home - STRING corresponding to an absolute path to something that "looks like" a homedir. Defaults to the user's homedir.
  392. useful in cases where you say, want to load SSH keys from a different path without changing assumptions about where
  393. keys exist in a homedir on your average OpenSSH using system.
  394. * no_cache - Pass in a truthy value to disable caching the connection and object, indexed by host string.
  395. useful if for some reason you need many separate connections to test something. Make sure your MAX_SESSIONS is set sanely
  396. in sshd_config if you use this extensively.
  397. * retry_interval - In the case that sshd is not up on the remote host, how long to wait while before reattempting connection.
  398. defaults to 6s. We retry $RETRY_MAX times, so this means waiting a little over a minute for SSH to come up by default.
  399. If your situation requires longer intervals, pass in something longer.
  400. * retry_max - Number of times to retry when a connection fails. Defaults to 10.
  401. RETURNS a Net::OpenSSH::More object.
  402. =head3 A note on Authentication order
  403. We attempt to authenticate using the following details, and in this order:
  404. 1) Use supplied key_path.
  405. 2) Use supplied password.
  406. 3) Use existing SSH agent (SSH_AUTH_SOCK environment variable)
  407. 4) Use keys that may exist in $HOME/.ssh - id_rsa, id_dsa and id_ecdsa (in that order).
  408. If all methods therein fail, we will die, as nothing will likely work at that point.
  409. It is important to be aware of this if your remove host has something like fail2ban or cPHulkd
  410. enabled which monitors and blocks access based on failed login attempts. If this is you,
  411. ensure that you have not configured things in a way as to accidentally lock yourself out
  412. of the remote host just because you fatfingered a connection detail in the constructor.
  413. =cut
  414. sub new {
  415. my ( $class, %opts ) = @_;
  416. $opts{'host'} = '127.0.0.1' if !$opts{'host'} || $opts{'host'} eq 'localhost';
  417. $opts{'remote_shell'} ||= 'bash'; # prevent stupid defaults
  418. $opts{'expect_timeout'} //= 30; # If your program goes over 30s without printing...
  419. # Set defaults, check if we can return early
  420. %opts = ( %defaults, %opts );
  421. $opts{'_cache_index'} = "$opts{'user'}_$opts{'host'}_$opts{'port'}";
  422. return $cache{ $opts{'_cache_index'} } unless $opts{'no_cache'} || !$cache{ $opts{'_cache_index'} };
  423. # Figure out how we're gonna login
  424. $opts{'_login_method'} = $resolve_login_method->( \%opts );
  425. # check permissions on base files if we got here
  426. $check_local_perms->( "$opts{'home'}/.ssh", 0700, 1 ) if -e "$opts{'home'}/.ssh";
  427. $check_local_perms->( "$opts{'home'}/.ssh/config", 0600 ) if -e "$opts{'home'}/.ssh/config";
  428. # Make the connection
  429. my $self = $init_ssh->( $class, \%opts );
  430. $cache{ $opts{'_cache_index'} } = $self unless $opts{'no_cache'};
  431. # Stash opts for later
  432. $self->{'_opts'} = \%opts;
  433. # Establish persistent shell, etc.
  434. $post_connect->( $self, \%opts );
  435. return $self;
  436. }
  437. =head2 use_persistent_shell
  438. Pass "defined but falsy/truthy" to this to enable using the persistent shell or deactivate its' use.
  439. Returns either the value you just set or the value it last had (if arg is not defined).
  440. =cut
  441. sub use_persistent_shell {
  442. my ( $self, $use_shell ) = @_;
  443. return $self->{'_opts'}{'use_persistent_shell'} if !defined($use_shell);
  444. return $self->{'_opts'}{'use_persistent_shell'} = $use_shell;
  445. }
  446. =head2 copy
  447. Copies $SOURCE file on the remote machine to $DEST on the remote machine.
  448. If you want to sync/copy files from remote to local or vice/versa, use
  449. the sftp accessor (Net::SFTP::Foreign) instead.
  450. Dies in this module, as this varies on different platforms (GNU/LINUX, Windows, etc.)
  451. =cut
  452. sub copy {
  453. die "Unimplemented, use a subclass of this perhaps?";
  454. }
  455. =head2 B<backup_files (FILES)>
  456. Backs up files which you wish to later restore to their original state. If the file does
  457. not currently exist then the method will still store a reference for later file deletion.
  458. This may seem strange at first, but think of it in the context of preserving 'state' before
  459. a test or scripted action is run. If no file existed prior to action, the way to restore
  460. that state would be to delete the added file(s).
  461. NOTE: Since copying files on the remote system to another location on the remote system
  462. is in fact not something implemented by Net::SFTP::Foreign, this is necessarily going
  463. to be a "non-portable" method -- use the Linux.pm subclass of this if you want to be able
  464. to actually backup files without dying, or subclass your own for Windows, however they
  465. choose to implement `copy` with their newfangled(?) SSH daemon.
  466. C<FILES> - LIST - File(s) to backup.
  467. C<STASH> - BOOL - mv files on backup instead of cp. This will make sure FILES arg path no
  468. longer exists at all so a fresh FILE can be written during run.
  469. my $file = '/path/to/file.txt';
  470. $ssh->backup_files($file);
  471. my @files = ( '/path/to/file.txt', '/path/to/file2.txt' );
  472. $ssh->backup_files(@files);
  473. =cut
  474. sub backup_files {
  475. my ( $self, @files ) = @_;
  476. # For each file passed in
  477. foreach my $file (@files) {
  478. # If the file hasn't already been backed up
  479. if ( !defined $self->{'file_backups'}{$file} ) {
  480. # and the file exists
  481. if ( $self->sftp->test_e($file) ) {
  482. # then back it up
  483. $self->{'file_backups'}{$file} = time;
  484. my $bkup = $file . '.' . $self->{'file_backups'}{$file};
  485. $self->diag("[INFO] Backing up '$file' to '$bkup'");
  486. $self->copy( $file, $bkup ); # XXX Probably not that portable, maybe move to Linux.pm somehow?
  487. # otherwise if the file to be backed up doesn't exist
  488. }
  489. else {
  490. # then just note that a file may need to be deleted later
  491. $self->{'file_backups'}{$file} = '';
  492. }
  493. }
  494. }
  495. return;
  496. }
  497. =head2 B<restore_files (FILES)>
  498. Restores specific file(s) backed up using backup_files(), or all the backup files if none
  499. are specified, to their previous state.
  500. If the file in question DID NOT exist when backup_files was last invoked for the file,
  501. then the file will instead be deleted, as that was the state of the file previous to
  502. actions taken in your test or script.
  503. C<FILES> - (Optional) - LIST - File(s) to restore.
  504. my $file = '/path/to/file.txt';
  505. $ssh->backup_files($file);
  506. $ssh->restore_files();
  507. =cut
  508. sub restore_files {
  509. my ( $self, @files ) = @_;
  510. # If no files were passed in then grab all files that have been backed up
  511. @files = keys( %{ $self->{'file_backups'} } ) if !@files;
  512. # foreach file
  513. foreach my $file (@files) {
  514. # that has been marked as modified
  515. if ( defined $self->{'file_backups'}{$file} ) {
  516. # if a backup exists
  517. if ( $self->{'file_backups'}{$file} ) {
  518. # then restore the backup
  519. my $bkup = $file . '.' . $self->{'file_backups'}{$file};
  520. if ( $self->sftp->test_e($bkup) ) {
  521. $self->diag("[INFO] Restoring backup '$file' from '$bkup'");
  522. $self->sftp->rename( $bkup, $file, 'overwrite' => 1 );
  523. }
  524. # otherwise no backup exists we just need to delete the modified file
  525. }
  526. else {
  527. $self->diag("[INFO] Deleting '$file' to restore system state (beforehand the file didn't exist)");
  528. $self->sftp->remove($file);
  529. }
  530. }
  531. delete $self->{'file_backups'}{$file};
  532. }
  533. return;
  534. }
  535. =head2 DESTROY
  536. Noted in POD only because of some behavior differences between the
  537. parent module and this. The following actions are taken *before*
  538. the parent's destructor kicks in:
  539. * Return early if you aren't the PID which created the object.
  540. * Restore any files backed up with backup_files earlier.
  541. =cut
  542. sub DESTROY {
  543. my ($self) = @_;
  544. return if !$self->{'_perl_pid'} || $$ != $self->{'_perl_pid'} || $disable_destructor;
  545. $self->restore_files();
  546. $ENV{SSH_AUTH_SOCK} = $self->{'_opts'}{'_restore_auth_sock'} if $self->{'_opts'}{'_restore_auth_sock'};
  547. $self->{'persistent_shell'}->close() if $self->{'persistent_shell'};
  548. return $self->SUPER::DESTROY();
  549. }
  550. =head2 diag
  551. Print a diagnostic message to STDOUT.
  552. Optionally prefixed by what you passed in as $opts{'output_prefix'} in the constructor.
  553. I use this in several places when $opts{'debug'} is passed to the constructor.
  554. ACCEPTS LIST of messages.
  555. RETURNS undef.
  556. =cut
  557. sub diag {
  558. my ( $self, @msgs ) = @_;
  559. print STDOUT "$self->{'_opts'}{'output_prefix'}$_\n" for @msgs;
  560. return;
  561. }
  562. =head2 cmd
  563. Execute specified command via SSH. If first arg is HASHREF, then it uses that as options.
  564. Command is specifed as a LIST, as that's the easiest way to ensure escaping is done correctly.
  565. $opts HASHREF:
  566. C<no_stderr> - Boolean - Whether or not to discard STDERR.
  567. C<use_operistent_shell> - Boolean - Whether or not to use the persistent shell.
  568. C<command> - LIST of components combined together to make a shell command.
  569. Returns LIST STDOUT, STDERR, and exit code from executed command.
  570. my ($out,$err,$ret) = $ssh->cmd(qw{ip addr show});
  571. If use_persistent_shell was truthy in the constructor (or you override via opts HR),
  572. then commands are executed in a persistent Expect session to cut down on forks,
  573. and in general be more efficient.
  574. However, some things can hang this up.
  575. Unterminated Heredoc & strings, for instance.
  576. Also, long running commands that emit no output will time out.
  577. Also, be careful with changing directory;
  578. this can cause unexpected side-effects in your code.
  579. Changing shell with chsh will also be ignored;
  580. the persistent shell is what you started with no matter what.
  581. In those cases, use_persistent_shell should be called to disable that before calling this.
  582. Also note that persistent mode basically *requires* you to use bash.
  583. I am not yet aware of how to make this better yet.
  584. If the 'debug' opt to the constructor is set, every command executed hereby will be printed.
  585. If no_stderr is passed, stderr will not be gathered (it takes writing/reading to a file, which is additional time cost).
  586. BUGS:
  587. In no_persist mode, stderr and stdout are merged, making the $err parameter returned less than useful.
  588. =cut
  589. sub cmd {
  590. my ($self) = shift;
  591. my $opts = ref $_[0] eq 'HASH' ? shift : {};
  592. my @command = @_;
  593. $die_no_trace->( 'No command specified', 'PEBCAK' ) if !@command;
  594. my $ret;
  595. $opts->{'use_persistent_shell'} = $self->{'_opts'}{'use_persistent_shell'} if !exists $opts->{'use_persistent_shell'};
  596. if ( $opts->{'use_persistent_shell'} ) {
  597. $ret = $do_persistent_command->( $self, \@command, $opts->{'no_stderr'} );
  598. }
  599. else {
  600. $ret = $send->( $self, undef, @command );
  601. }
  602. chomp( my $out = $self->{'_out'} );
  603. my $err = $self->error || '';
  604. $self->{'last_exit_code'} = $ret;
  605. return ( $out, $err, $ret );
  606. }
  607. =head2 cmd_exit_code
  608. Same thing as cmd but only returns the exit code.
  609. =cut
  610. sub cmd_exit_code {
  611. my ( $self, @args ) = @_;
  612. return ( $self->cmd(@args) )[2];
  613. }
  614. sub sftp {
  615. my ($self) = @_;
  616. unless ( defined $self->{'_sftp'} ) {
  617. $self->{'_sftp'} = $self->SUPER::sftp();
  618. die 'Unable to establish SFTP connection to remote host: ' . $self->error() unless defined $self->{'_sftp'};
  619. }
  620. return $self->{'_sftp'};
  621. }
  622. =head3 B<write (FILE,CONTENT,[MOD],[OWN])>
  623. Write a file.
  624. C<FILE> - Absolute path to file.
  625. C<CONTENT> - Content to write to file.
  626. C<MOD> - File mode.
  627. C<OWN> - File owner. Defaults to the user you connected as.
  628. C<GRP> - File group. Defaults to OWN.
  629. Returns true if all actions are successful, otherwise warn/die about the error.
  630. $ssh->write($filename,$content,'600','root');
  631. =cut
  632. sub write {
  633. my ( $self, $file, $content, $mode, $owner, $group ) = @_;
  634. die '[PARAMETER] No file specified' if !defined $file;
  635. die '[PARAMETER] File content not specified' if !defined $content;
  636. my %opts;
  637. $opts{'perm'} = $mode if $mode;
  638. my $ret = $self->sftp()->put_content( $content, $file, %opts );
  639. warn "[WARN] Write failed: " . $self->sftp()->error() if !$ret;
  640. if ( defined $owner || defined $group ) {
  641. $owner //= $self->{'_opts'}{'user'};
  642. $group //= $owner;
  643. $ret = $self->sftp()->chown( $file, $owner, $group );
  644. warn "[WARN] Couldn't chown $file" if $ret;
  645. }
  646. return $ret;
  647. }
  648. =head3 B<eval_full( options )>
  649. Run Perl code on the remote system and return the results.
  650. interpreter defaults to /usr/bin/perl.
  651. B<Input>
  652. Input options are supplied as a hash with the following keys:
  653. code - A coderef or string to execute on the remote system.
  654. args - An optional arrayref of arguments to the code.
  655. exe - Path to perl executable. Optional.
  656. B<Output>
  657. The output from eval_full() is based on the return value of the input
  658. coderef. Return context is preserved for the coderef.
  659. All error states will generate exceptions.
  660. B<Caveats>
  661. A coderef supplied to this function will be serialized by B::Deparse
  662. and recreated on the remote server. This method of moving the code does
  663. not support closing over variables, and any needed modules must
  664. be loaded inside the coderef with C<require>.
  665. B<Example>
  666. my $greeting_message = $ssh->eval_full( code => sub { return "Hello $_[0]";}, args => [$name] );
  667. =cut
  668. sub eval_full {
  669. my ( $self, %options ) = @_;
  670. my $code = $options{code};
  671. my $args = $options{args} // [];
  672. my $exe = $options{exe} || '/usr/bin/perl';
  673. require Storable;
  674. local $Storable::Deparse = 1;
  675. my ( $in_fh, $out_fh, undef, $pid ) = $call_ssh_reinit_if_check_fails->(
  676. $self,
  677. 'open_ex',
  678. { stdin_pipe => 1, stdout_pipe => 1, stderr_to_stdout => 1 },
  679. q{export PERLCODE='use Storable;$Storable::Eval=1;my $input;while ($input .= <STDIN>) { if ($input =~ /\d+START_STORABLE(.*)STOP_STORABLE\d+/) { my @result = eval { my $in_hr = Storable::thaw(pack("H*", $1)); if ( ref $in_hr->{code} ) { return $in_hr->{wantarray} ? $in_hr->{code}->(@{$in_hr->{args}}) : scalar $in_hr->{code}->(@{$in_hr->{args}});} return $in_hr->{wantarray} ? eval $in_hr->{code} : scalar eval $in_hr->{code};}; print $$ . "START_STORABLE" . unpack("H*", Storable::freeze( { data => \@result, error => "$@" })) . "STOP_STORABLE" . $$ . "\n";exit;}}'; }
  680. . $exe
  681. . q{ -e "$PERLCODE";}
  682. );
  683. die "Failed to connect: $!" unless ($pid);
  684. print $in_fh $$ . "START_STORABLE" . unpack( "H*", Storable::freeze( { code => $code, args => $args, wantarray => wantarray() } ) ) . "STOP_STORABLE" . $$ . "\n";
  685. close $in_fh;
  686. my $output = '';
  687. while ( $out_fh->sysread( $output, 4096, length($output) ) > 0 ) {
  688. 1;
  689. }
  690. close $out_fh;
  691. waitpid( $pid, 0 );
  692. my $result = { error => "Unable to deserialize output from remote_eval: $output" };
  693. if ( $output =~ /\d+START_STORABLE(.*)STOP_STORABLE\d+/ ) {
  694. $result = Storable::thaw( pack( "H*", $1 ) );
  695. }
  696. die $result->{error} if ( $result->{error} );
  697. return wantarray ? @{ $result->{data} } : $result->{data}[0];
  698. }
  699. =head3 cmd_stream
  700. Pretty much the same as running cmd() with one important caveat --
  701. all output is formatted with the configured prefix and *streams* to STDOUT.
  702. Useful for remote test harness building.
  703. Returns (exit_code), as in this context that should be all you care about.
  704. You may be asking, "well then why not use system?" That does not support
  705. the prefixing I'm doing here. Essentially we provide a custom line reader
  706. to 'send' which sends the output to STDOUT via 'diag' as well as doing
  707. the "default" behavior (append the line to the relevant output vars).
  708. NOTE: This uses send() exclusively, and will never invoke the persistent shell,
  709. so if you want that, don't use this.
  710. =cut
  711. sub cmd_stream {
  712. my ( $self, @cmd ) = @_;
  713. my $line_reader = sub {
  714. my ( $self, $out, $stash_param ) = @_;
  715. $out =~ s/[\r\n]{1,2}$//;
  716. $self->diag($out);
  717. $self->{$stash_param} .= "$out\n";
  718. return;
  719. };
  720. return $send->( $self, $line_reader, @cmd );
  721. }
  722. =head1 AUTHORS
  723. Thomas Andrew "Andy" Baugh <andy@troglodyne.net>
  724. George S. Baugh <george@troglodyne.net>
  725. =head1 SPECIAL THANKS
  726. cPanel, L.L.C. - in particularly the QA department (which the authors once were in).
  727. Many of the ideas for this module originated out of lessons learned from our time
  728. writing a ssh based remote teststuite for testing cPanel & WHM.
  729. Chris Eades - For the original module this evolved from at cPanel over the years.
  730. bdraco (Nick Koston) - For optimization ideas and the general process needed for expect & persistent shell.
  731. J.D. Lightsey - For the somewhat crazy looking but nonetheless very useful eval_full subroutine used
  732. to execute subroutine references from the orchestrating server on the remote host's perl.
  733. Brian M. Carlson - For the highly useful sftp shortcut method that caches Net::SFTP::Foreign.
  734. Rikus Goodell - For shell escaping expertise
  735. =head1 IN MEMORY OF
  736. Paul Trost
  737. Dan Stewart
  738. =cut
  739. 1;