Ssh login as user and change to root, without sudo

sshsu

I have the following task:

  • the command has to be run as root on server remotely in bash script over ssh and the command output has to be fetched in variable.
  • logging over ssh as root is disabled.
  • sudo on server is disabled, so I have to use su.
  • EDIT: since I want to make it as automated as possible in bash, the password has to be stored inside command

I have Googled for days, but it seems that I cannot find a solution for this.

Solution proposed here: ssh to server and switch user and change a directory

    ssh -t username@hostname "sudo su - otheruser -c \"cd /path/to/directory && command\""

does not work because sudo is disabled on server:

Does anyone have a solution to this?

Best Answer

Perhaps somewhat off topic but this could be achieved with Python and the paramiko module:

#!/usr/bin/python2
import time
import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('127.0.0.1', port=22, username='user', password='pass')

stdin, stdout, stderr = ssh.exec_command('su')
time.sleep(0.1) # some enviroment maybe need this.
stdin.write('root_password_goes_here\n')

[ add extra code here to execute a command ]

stdin.flush()
print (stdout.readlines())
ssh.close()

It should be noted that storing passwords in script generally is a bad idea from a security perspective. Make sure you have proper permissions set to the script (e.g. chmod 740)

Related Question