-my $shell_client = <<__SHELL_CLIENT__;
-#!/bin/sh
-echo \$USER/\$SUDO_USER `hostname -s` `pwd` \$* | nc $server_ip 9001
-__SHELL_CLIENT__
+# parse ssh config
+my $ssh_tunnel;
+open(my $ssh_fd, '<', "$ENV{HOME}/.ssh/config");
+my $host;
+while(<$ssh_fd>) {
+ chomp;
+ next unless length($_) > 0;
+ next if m/^\s*#/;
+
+ if ( /^Host\s+(.+)/i ) {
+ $host = $1;
+ } elsif ( /^\s+(\S+)\s+(.+)/ ) {
+ $ssh_tunnel->{$host}++ if lc($1) eq 'remoteforward' && $2 =~ m/9001/;
+ } else {
+ die "can't parse $_";
+ }
+}
+
+sub shell_client {
+ my ( $hostname ) = @_;
+ my $path = '/tmp/bak';
+ my $server = $server_ip;
+ $server = '127.0.0.1' if $ssh_tunnel->{$hostname};
+warn "# ssh_client $hostname $server";
+ open(my $fh, '>', $path);
+ print $fh "#!/bin/sh\n";
+ print $fh "echo \$USER/\$SUDO_USER $hostname `pwd` \$* | nc $server 9001\n";
+ close($fh);
+ chmod 0755, $path;
+ return $path;
+}
+
+sub _kill_ssh {
+ while ( my($host,$pid) = each %$ssh_tunnel ) {
+ warn "$host kill TERM $pid";
+ kill 15, $pid; # TERM
+ }
+}
+
+#$SIG{INT};
+$SIG{TERM} = &_kill_ssh;