Search code examples
shellunixsshsudosu

How to ssh/sudo su - oracle/run some commands


I have already looked at the following links but didn't managed to make it work:

SSH to server, Sudo su - then run commands in bash

Can I ssh somewhere, run some commands, and then leave myself a prompt?

Run ssh and immediately execute command

I'm trying to automate the following sequence to log in to the database

$ ssh <myserver>
me@myserver$ sudo su - oracle
<enter password>
oracle@myserver$ bash
oracle@myserver$ export ORAENV_ASK=NO
oracle@myserver$ export ORACLE_SID=ORACLEDB
oracle@myserver$ . oraenv
oracle@myserver$ echo $ORACLE_HOME

I tried the command (based on the links above) but that does not work :

ssh -t myserver "echo password | sudo -S su - oracle ; bash ; export ORAENV_ASK=NO"

How can I combine thoses commands in a shell script (or even perl one), execute it and then leave myself at a prompt so I can run sqlplus after? Is that even possible?

Note: ssh does not need password because we use authorized_keys, BUT Password-less sudo is not an option nor using su directly (I'm not root and cannot change that), the command needs to be "sudo su - oracle" exactly.

Thanks


Solution

  • You can't do that in shell, but you can do it with expect (apt-get install expect if on Debian variants).

    This is a very simple expect file. You need to do some research to make it work in your environment but this gives the general idea.

    spawn ssh foo@x.x.x.x
    expect "~$"
    send "sudo bash\r"
    expect {
           password {send "foobar\r";exp_continue}
           "#"
    }
    
    send "id\r"
    expect "root"
    

    You would run this as expect /path/to/your/expectfile.

    This will log in, do sudo with password "foobar", execute id and exit. Would this be of any help?

    Hannu