unixssh

SSH With Remote Login/Commands


How can I use SSH to send multiple commands to a networked system, logging in as root, and providing a password?

I know you can do:

ssh -l <username> target_host

to login, but I'm not sure how to provide the password and a command so it all gets executed in one line. I'm looking to make a script with many one-liner commands to the networked system that can be run as a one-off from another computer.


Solution

  • ssh root@host "command"

    ie: ssh root@192.168.1.1 "cat /etc/fstab"

    If you are trying to execute multiple commands, I would suggest looking into some form of Expect scripting. I personally am a fan of Pexpect (Python).

    Using keys to circumvent password prompt (from man ssh):

    The file ~/.ssh/authorized_keys lists the public keys that are permitted for logging in. When the user logs in, the ssh program tells the server which key pair it would like to use for authentication. The client proves that it has access to the private key and the server checks that the corresponding public key is authorized to accept the account.

    The user creates his/her key pair by running ssh-keygen(1). This stores the private key in ~/.ssh/identity (protocol 1), ~/.ssh/id_dsa (protocol 2 DSA), or ~/.ssh/id_rsa (protocol 2 RSA) and stores the public key in ~/.ssh/identity.pub (protocol 1), ~/.ssh/id_dsa.pub (protocol 2 DSA), or ~/.ssh/id_rsa.pub (protocol 2 RSA) in the user's home directory. The user should then copy the public key to ~/.ssh/authorized_keys in his/her home directory on the remote machine. The authorized_keys file corre‐ sponds to the conventional ~/.rhosts file, and has one key per line, though the lines can be very long. After this, the user can log in with‐ out giving the password.