My problem is similar to this one , I am trying to automate the portion where I can access the remote machine and run a command as super user. It works fine till it logs-in , like from here :-

$ ssh-keygen -t rsa -b 2048


$ ssh-copy-id id@server
id@server's password:
$ ssh id@server

The overhead for me is that I can ask user for remote machine's password only once (while generating ssh keys), and after that while running a command as super user it shouldn't ask for password again i.e It shouldn't need a command like below:-

sudo su

Is there any way I can do it? because I tried saving the password as variable and then substituting the value like :-

echo -n "Enter password > "
read passwd
sshpass -p $username ssh -o StrictHostKeyChecking=no $username@$server sudo some_application &

It will prompt for the password where I cannot substitute the value of the variable I declared.

  • You are better off using a tool like fabric for this task fabfile.org
    – Mike
    Apr 14, 2016 at 12:29
  • Or setting up sudo properly on the target machine, and not su'ing to root
    – tgharold
    Apr 14, 2016 at 13:16

2 Answers 2


Have you tried using expect?

Simple login script writen in expect:

set timeout 9
set username [lindex $argv 0]
set password [lindex $argv 1]
set hostname [lindex $argv 2]
log_user 0

if {[llength $argv] == 0} {
  send_user "Usage: scriptname username \'password\' hostname\n"
  exit 1

send_user "\n#####\n# $hostname\n#####\n"

spawn ssh -q -o StrictHostKeyChecking=no $username@$hostname

expect {
  timeout { send_user "\nFailed to get password prompt\n"; exit 1 }
  eof { send_user "\nSSH failure for $hostname\n"; exit 1 }

send "$password\r"

expect {
  timeout { send_user "\nLogin failed. Password incorrect.\n"; exit 1}
  "*\$ "

send_user "\nPassword is correct\n"
send "exit\r"

Example of use:

./script_name user_foo pass_bar hostname.com

It would only try to log you in and give any error message in case something went wrong and, if not, it would say "Password is correct" and then exit the session.

Some of the parameters will deppend on the system you are conecting to. Also, using expect means you know what the output will be when logging in and executing commands.

This tutorial will cover your needs


Did you actually copy your pub key to root's .ssh/authorized_keys file? I always do "chmod -R go= /root/.ssh" afterwards, also check ownership.

If you've got selinux running, you'll have to "restorecon" on the authorized_keys file and the .ssh dir too.

And if you want to ssh in as root, you need to check /etc/ssh/sshd_config and reload sshd.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.