ssh to another server with different username

17,422

Solution 1

You want to use key-authentication http://ornellas.apanela.com/dokuwiki/pub:ssh_key_auth

  1. Generate your keys ssh-keygen
  2. Copy the keys to your new box ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
  3. ssh to other host without password ssh [email protected]

Solution 2

You can use expect to wrap ssh, but it's pretty hectic, and fails easily when there are network errors, so test it well or use a script specifically designed for wrapping ssh passwords. Key based authentication is better.

You can prevent interactive sessions by redirecting standard input from the null device, ie.

ssh me@destination destination-command < /dev/null

About placing the script in the source server, if the script you are running is local, rather than remote, then you can pass the script on standard input, rather than the command line:

cat bashscript.sh | ssh me@destination 

Solution 3

You can install the sshpass program, which lets you write a script like

#!/bin/bash

sshpass -p bob123 ssh [email protected]

Solution 4

The answer is that you can't as OpenSSH actively prevent headless password-based authentication. Use key-based authentication.

You may be able to fork the OpenSSH client code and patch it, but I think that is a bit excessive.

Share:
17,422
Utsav
Author by

Utsav

Vector Programmer. Python, kdb+/q, Java, SQL. AI/ML/Deep Learning - Time-series, Recommendation Systems, NLP.

Updated on June 29, 2022

Comments

  • Utsav
    Utsav almost 2 years

    I have to write a shell script which ssh to another server with other username without actually asking for a password from the user? Due to constraints I cannot use key based authentication. let, Source Server -- abc.efg.com Source UserName -- tom Source Password -- tom123

    Destination Server -- xyz.efc.com Destination UserName -- bob destination Password -- bob123

    I have to place the bash script in source server. Please let me know if something could be done using expect tool and/or sshpass.

    It is okay for me to hardcode the password for destination server in the bash script but I cannot bear an interactive session, simply when I run he script, I want to see the destination server logged in with another username.

    Thanks in Advance.

  • Utsav
    Utsav about 11 years
    Can you tell me the script with key based authentication.
  • DeFazer
    DeFazer over 8 years
    He said: 'Due to constraints I cannot use key based authentication'.