Languages
[Edit]
EN

Bash - run remote command as superuser using ssh connection with plink command

6 points
Created by:
Khloe-Kaiser
458

In this short article, we would like to show how to run some command as a superuser on remote host, using ssh connection with plink command in Bash.

Quick solution:

plink -pw user_password user@$my-domain.com "su - root -c 'ls -al /root' <<< 'root_password'" 2> /dev/null

Note: motivation to use plink command instead of ssh command is the possibility to pass the password as a parameter (-pw parameter).

 

Practical example

In this example, all parameters are stored in variables (username and password as a variable in the script).

#!/bin/bash

SERVER_HOST='88.77.55.44'
SERVER_PORT=22

USER_NAME='john'
USER_PASSWORD='secret_john_password'
ADMIN_NAME='root'
ADMIN_PASSWORD='secret_root_password'

REMOTE_COMMAND='ls -al /'

plink -P "${SERVER_PORT}" -pw "${USER_PASSWORD}" "${USER_NAME}@${SERVER_HOST}" "su - '$ADMIN_NAME' -c '${REMOTE_COMMAND}' <<< '${ADMIN_PASSWORD}'" 2> /dev/null

Where main concept is to:

  1. get a connection with the server as a normal user,
  2. run su command executing some another command,
  3. inject superuser password with <<<,
  4. ignore Password: prompt with 2> /dev/null - we want to see executed command output only.

 

plink installation

Under Windows, you can use putty installer¬†(go to MSI (‚ÄėWindows Installer‚Äô) section).

Under Debian based Linux run:

sudo apt-get update
sudo apt-get install plink
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
ūüöÄ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

‚̧ԳŹūüíĽ ūüôā

Join