2
2
# This script can be used as a "remote shell" command that is only
3
3
# capable of pretending to connect to "localhost". This is useful
4
4
# for testing or for running a local copy where the sender and the
5
5
# receiver needs to use different options (e.g. --fake-super). If
6
# we get a -l USER option, we try to use "sudo -u USER" to run the
10
do_cd=y # Default path is user's home dir, just like ssh.
14
-l) user="$2"; shift; shift ;;
15
-l*) user=`echo "$1" | sed 's/^-l//'`; shift ;;
16
--no-cd) do_cd=n; shift ;;
18
localhost) shift; break ;;
19
*) echo "lsh: unable to connect to host $1" 1>&2; exit 1 ;;
25
if [ $do_cd = y ]; then
26
home=`perl -e "print((getpwnam('$user'))[7])"`
29
sudo -H -u "$user" sh -c "$prefix $*"
6
# we get -l USER, we try to become the USER, either directly (must
7
# be root) or by using "sudo -H -u USER" (requires --sudo option).
12
use English '-no_match_vars';
14
&Getopt::Long::Configure('bundling');
15
&Getopt::Long::Configure('require_order');
17
'l=s' => \( my $login_name ),
18
'1|2|4|6|A|a|C|f|g|k|M|N|n|q|s|T|t|V|v|X|x|Y' => sub { }, # Ignore
19
'b|c|D|e|F|i|L|m|O|o|p|R|S|w=s' => sub { }, # Ignore
20
'no-cd' => \( my $no_chdir ),
21
'sudo' => \( my $use_sudo ),
23
&usage unless @ARGV > 1;
26
if ($host =~ s/^([^@]+)\@//) {
29
if ($host ne 'localhost') {
30
die "lsh: unable to connect to host $host\n";
36
if ($login_name =~ /\D/) {
37
$uid = getpwnam($login_name);
38
die "Unknown user: $login_name\n" unless defined $uid;
42
($login_name, $gid, $home_dir) = (getpwuid($uid))[0,3,7];
44
unshift @ARGV, "cd '$home_dir' &&" unless $no_chdir;
45
unshift @cmd, qw( sudo -H -u ), $login_name;
48
my $groups = "$gid $gid";
49
while (my ($grgid, $grmembers) = (getgrent)[2,3]) {
50
if ($grgid != $gid && $grmembers =~ /(^|\s)\Q$login_name\E(\s|$)/o) {
55
my ($ruid, $euid) = ($UID, $EUID);
56
$GID = $EGID = $groups;
58
die "Cannot set ruid: $! (use --sudo?)\n" if $UID == $ruid && $ruid != $uid;
59
die "Cannot set euid: $! (use --sudo?)\n" if $EUID == $euid && $euid != $uid;
61
$ENV{USER} = $ENV{USERNAME} = $login_name;
62
$ENV{HOME} = $home_dir;
65
$home_dir = (getpwuid($UID))[7];
69
chdir $home_dir or die "Unable to chdir to $home_dir: $!\n";
72
push @cmd, '/bin/sh', '-c', "@ARGV";
74
die "Failed to exec: $!\n";
79
Usage: lsh [-l user] [--sudo] [--no-cd] localhost COMMAND [...]