would like to ssh into other client servers in the same subnet using a cleartext password then sudo to root to turn off commands and reboot. I am purposely not adding the ssh key. I've tried

ssh -tt [username]@[host] "sudo su -; service snmpd stop; reboot ";

How would I pass in the password at the login for both the username and the sudo?

  • Is there a particular reason you want to do this in the manner that most completely defies best practice? – DopeGhoti Jul 20 '17 at 20:29
  • 2
    Sounds like a task more suited for Ansible. – Deathgrip Jul 20 '17 at 20:30
  • 1
    I agree, but that's an even heavier lift than ssh-keygen && ssh-copy-id, so.. – DopeGhoti Jul 20 '17 at 20:31
  • True, but I have fallen in love with Ansible. And the more I use it and discover features, the more I like it. – Deathgrip Jul 20 '17 at 20:34
  • 1
    Once you work out the password issue, you will want to change the sudo command to sudo -s /bin/bash -c "service snmpd stop; reboot". – Deathgrip Jul 20 '17 at 20:59

Try using a program called sshpass to pass your ssh password. It can be used like this:


sshpass -e ssh user@host <'EOF'
su -
echo "$remoterootpass"
service snmpd stop

You could also put your remote commands in a shell script and call it like this:

cat myscript.sh | sshpass -e ssh user@host
  • 1
    And then your root password for the remote host in in plaintext in a file on disk, which is a fantastically terrible idea. – DopeGhoti Jul 20 '17 at 20:34
  • 1
    Yea the whole thing is a bad idea though. To fix that issue though he could just allow his ssh user to sudo without a password. – Jesse_b Jul 20 '17 at 20:35

Note: The answer being provided here should work. However, violates best practices. This answer also assumes that sshpass is available on the host where the command will be initiated. The user has noted it is going to be used one time, then removed.

sshpass -pPASSWORD ssh -tt [username]@[host] 'echo PASSWORD | sudo -S -s /bin/bash -c "service snmpd stop; reboot"'

At the very least, the user should be using key exchange for the ssh login, and allow the use to execute the desired commands via sudo with no password.

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.