More.pm 36 KB

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