EN
Bash - run remote command as superuser using ssh connection with plink command
6 points
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:
xxxxxxxxxx
1
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 ofssh
command is the possibility to pass the password as a parameter (-pw
parameter).
In this example, all parameters are stored in variables (username and password as a variable in the script).
xxxxxxxxxx
1
2
3
SERVER_HOST='88.77.55.44'
4
SERVER_PORT=22
5
6
USER_NAME='john'
7
USER_PASSWORD='secret_john_password'
8
ADMIN_NAME='root'
9
ADMIN_PASSWORD='secret_root_password'
10
11
REMOTE_COMMAND='ls -al /'
12
13
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:
- get a connection with the server as a normal user,
- run
su
command executing some another command, - inject superuser password with
<<<
, - ignore
Password:
prompt with2> /dev/null
- we want to see executed command output only.
Under Windows, you can use putty installer (go to MSI (‘Windows Installer’) section).
Under Debian based Linux run:
xxxxxxxxxx
1
sudo apt-get update
2
sudo apt-get install plink