I'm trying to use Plink to connect to a remote UNIX server, su
to another user (without password) and finally execute some commands.
$commands = @(
"su - $UNIXUSER;",
"id"
)
echo y | plink -ssh $SERVER -l $USER -pw $PWD $commands
When I execute the code above using PowerShell I get a message saying he was able to change the user, but when I execute the command id
he returns the id I logged in in the first place, not the su
user.
How can I execute commands using Plink within a su
user?
This cannot work.
I'm surprised that you even get the id
executed.
The PowerShell effectively executes this.
plink -ssh $SERVER -l $USER -pw $PWD "su - $UNIXUSER;" id
First that's a wrong syntax.
An even it were correct, you can provide only a single command string on plink
command line. While you can combine multiple shell commands using ;
or &
to a simple command string, that cannot work with su
. The second command, the ls
is not command of the main shell anymore. That's an inner command of the su
, i.e. a complete different stream/input/whatever you call it.
What you need to do is to emulate user typing the commands, so that the first command gets processed by the main shell and the second command by the su
executed from the main shell. You can do that via an input redirection only.
You can do:
"su - $UNIXUSER`nid`nexit`nexit`n" | plink -ssh $SERVER -l $USER -pw $PWD -T
The -T
was added to disable pty allocation (i.e. to get a non-interactive shell), to get the behavior of -m
(which implies the -T
).
(I do not do PowerShell. There's probably a more elegant way to present the commands than using the string.)