Linux Shell Skripte mit ssh und scp ohne Passworteingabe

Aus Wikizone
Wechseln zu: Navigation, Suche

http://www.hostingrails.com/HowTo-SSH-SCP-without-a-password (Zugriff am 8.2.)

HowTo SSH/SCP without a password.


This is a wiki article created by HostingRails users. Please login or signup to make edits.


This small HowTo will explain how to setup key-based authentication for password-less SSH and SCP usage.

This HowTo does assume the reader has some basic knowledge of ssh and a terminal, and is using an operating system that implements SSH. If you're using a Windows OS and want to use SSH, try PuTTY. For Putty, see key-based auth with Putty.

In the examples that follow please substitute 'servername' , 'ipaddress' and 'username' with the proper information for your setup. I have included a list of weblinks for the words in italic at the end of this document.


Step 1. Verify Connection[Bearbeiten]

Verify that you can connect normally (using a password) to the server you intend to setup keys for:

Examples

user@homebox ~ $ ssh username@'servername'

Or:

user@homebox ~ $ ssh username@'ipaddress'

If your username is the same on both the client ('homebox') and the server ('servername'):

user@homebox ~ $ ssh 'servername'

Or:

user@homebox ~ $ ssh 'ipaddress'

If this is your first time connecting to 'servername' (or 'ipaddress'), upon establishing a connection with the server you'll be asked if you want to add the servers fingerprint to the known_hosts file on your computer.

Press 'enter' to add the fingerprint.

Step 2[Bearbeiten]

Now that you're connected to the server and verified that you have everything you need for access (hopefully), disconnect by typing 'exit' . ==

Examples

user@servername ~ $ exit

  1. You should be back at:

user@homebox ~ $


Step 3. Generate and Use Key[Bearbeiten]

The next step is to copy a unique key generated on your 'homebox' to the server you are connecting too. First, before you generate a new key, check to see if you already have a key:

Example

user@homebox ~ $ ls -l ~/.ssh
total 20
-rwx--xr-x 1 user user  601 Feb  2 01:58 authorized_keys
-rwx--xr-x 1 user user  668 Jan  1 19:26 id_dsa
-rwx--xr-x 1 user user  599 Jan  1 19:26 id_dsa.pub
-rwx--xr-x 1 user user 6257 Feb  2 21:04 known_hosts

The file we need to copy to the server is named id_dsa.pub. As you can see above, the file needed exists. You may or may not have other files in ~/.ssh as I do. If the key doesn't exist, however, you can make one as follows:

Example

user@homebox ~ $ ssh-keygen -t dsa

Generating public/private dsa key pair. Enter file in which to save the key (/home/user/.ssh/id_dsa): # Press 'enter' here

Enter passphrase (empty for no passphrase):     # Press 'enter' here
Enter same passphrase again:     # Press 'enter' here
Your identification has been saved in /home/user/.ssh/id_dsa.
Your public key has been saved in /home/user/.ssh/id_dsa.pub.
The key fingerprint is:
6f:c3:cb:50:e6:e9:90:f0:0f:68:d2:10:56:eb:1d:91 user@host
  1. Entering a password when asked during the key generation processes when prompted would require you to enter a password each time you SSH/SCP to the server which defeats the purpose of this document.


Step 4. Copy the Key[Bearbeiten]

Regardless whether you had a key ready to go or if you had to generate a new key, the next step is the same in either case. Now you're ready to copy the key to the server. Do so like this:

Example

user@homebox ~ $ ssh-copy-id -i ~/.ssh/id_dsa.pub user@'servername' (or 'ipaddress')
  1. If you are asked weather or not you wish to continue, say yes.


Step 5. Test[Bearbeiten]

Now it's time to test the setup. To do that, try to ssh to the server:

Example

user@homebox ~ $ ssh 'servername' (or 'ipaddress')
  1. You should log in to the remote host without being asked for a password.


Step 6. Protect Keys[Bearbeiten]

You can now SSH or SCP to the remote host without having to enter a password at each connection. To make sure your public key stays secure from prying eyes, do the following to change permissions and restrict access on 'homebox' and also on 'servername' to ~/.ssh:

Example

user@homebox ~ $ chmod 600 ~/.ssh/id_dsa ~/.ssh/id_dsa.pub

Verify the permissions on the files[Bearbeiten]

Example

user@homebox ~ $ ls -l ~/.ssh
-rw-------  1 user user  668 Feb  4 19:26 id_dsa
-rw-------  1 user user  599 Feb  4 19:26 id_dsa.pub


Links[Bearbeiten]

1. OpenSSH

2. known_hosts

3. fingerprint


Comments[Bearbeiten]

Nice post!

I've noticed that I don't have the command ssh-copy-id on my OS X machine (I didn't even know one existed!). To achieve the same effect I usually do the following:

user@homebox ~ $ scp ~/.ssh/id_dsa.pub user@'servername':.ssh/authorized_keys

This is assuming you've already created a .ssh directory on your server 'servername' (just ssh in as normal and `mkdir .ssh`). This also assumes that you don't already have an `authorized_keys` file in the .ssh directory on your server. If you do just copy (scp) the id_dsa.pub file to a temporary file in your server's home directory and then

user@homebox ~ $ scp .ssh/id_dsa.pub user@servername:homebox_dsa.pub
user@homebox ~ $ ssh user@servername
user@servername ~ $ cat homebox_dsa.pub >> .ssh/authorized_keys
user@servername ~ $ rm homebox_dsa.pub 

If you've got it, the ssh-copy-id way is clearly a lot easier!

~ Mark

Hi Mark. Thanks for adding that bit. I don't have access to a Mac (new one anyway) so that's very nice to know.

Seth

Seth, I liked this post a lot, but felt the formatting and wording can be improved. I've made a few changes to the introduction.

Xin (I wish I had used my name for my username now!)


I found an elegant way of creating a new, or adding to an existing authorized_keys file with a single command:

ssh username@somedomain.com -n "echo `cat ~/.ssh/id_dsa.pub` >> ~/.ssh/authorized_keys"

-

I think it *is* a good practice to use pass phrases when using ssh keys. You can use ssh-agent on Linux and SSH Agent or SSHKeychain on Mac OS X, to avoid you to type your pass phrase everytime you access a remote host. Also, you can forward your keys using 'ssh -A' if you need to hop onto some host in the middle.

-- Igor"


I'm using PUTTY (pageant) on a XP and on Vista. I use 2048 RSA private key that is password protected. I typically use PUTTY to connect, fyi: my purpose is really to be able to use git (which uses SSH) without having to log in every time I commit. Assuming you are too and have a key generated already...

load key into PuttyGen (enter password for the key) in the window copy the "public key for pasting into OpenSSH..." append this to the ~/.ssh/authorized_keys.

One comment: when I used the append from above aka the elegant code, it did not add a \n at the end of the line aka didn't work. I vi'd the file added a new line.

--Eric

Deutsche Anleitung[Bearbeiten]

SSH ohne Passwort -- Kurze Anleitung zur Nutzung

Auf einfachen Wunsch ... eine unvollständige Anleitung, wie immer hilft das Manual (man ssh) weiter.

Die SSH ist Ersatz für rsh, rlogin, rcp, ... und bietet

   * mehr Sicherheit bei der Authentisierung/Authorisierung
   * verschlüsselte Sessions
   * einfachen transparenten Zugriff auf fremde Rechner
   * ad-hoc VPN (über tun-Devices) 

ssh/slogin/scp kann als Ersatz für rsh/rlogin/rcp genutzt werden. Bei vorhandener .rhosts auf dem Zielrechner kann sie sich wie die r* commands verhalten. Sollten dann doch Passwörter übertragen werden, sind diese verschlüsselt. Bei der Nutzung von .rhosts ist die Authentisierung nicht sonderlich sicher, das Paar aus `host' und `user' ist doch ziemlich leicht durch Fremde zu nachzuempfinden. Sie beruhen ausschliesslich auf Vertrauen gegenüber dem DNS und dem fremden Host. Die ssh nutzt host- und userspezifische Keys zur Authentisierung. Spoofing wird damit schwerer.

Für die Nutzung der ssh als Ersatz für telnet und rlogin sind folgende Dinge zu tun:

$ ssh-keygen -t rsa1 # für Protokol 1 (!! nicht mehr verwenden !!)

       $ ssh-keygen -t rsa	  # für Protokol 2
       $ ssh-keygen -t dsa	  # für Protokol 2

Damit werden eigene Schlüsselpaare erzeugt. (Für Protokol 2 gibt es RSA und DSA Keys, eigentlich reicht normalerweise einer von beiden.) Die Passphrase sollte nicht zu lang sein, denn sie wird doch das eine oder andere Mal abgefragt. Zeitweise wurden DSA-Keys für unsicher gehalten, da wohl der Algorithmus schlecht implementiert war.

Es entstehen Dateien mit den Schlüsselpaaren: Für Protokoll 1 (RSA1) ~/.ssh/identity und ~/.ssh/identity.pub, für Protokoll 2 (RSA, DSA) ~/.ssh/id_{rsa,dsa} und ~/.ssh/id_{rsa,dsa}.pub.

Die *.pub-Dateien können nun auf den Zielhost kopiert werden und dort an ~/.ssh/authorized_keys angehängt werden:

       $ ssh-copy-id user@remote-system
       $ ssh-copy-id -i ~/.ssh/id_rsa.pub user@remote-system
       $ ssh-copy-id -i ~/.ssh/id_dsa.pub user@remote-system

Oder, wenn ssh-copy-id nicht vorhanden ist:

       $ cat ~/.ssh/*.pub | ssh user@remote-system 'umask 077; cat >>.ssh/authorized_keys'

Sonst ist das andere Theater witzlos.

Nutzt man nun slogin, ssh, oder scp, will der Server auf der anderen Seite den Beweis, daß man zu einem der dort in der authorized_keys liegenden öffentlichen Schlüssel den privaten Teil hat.

Der lokale Client verlangt also nach der Passphrase, um den (lokal in id_{dsa,rsa}) gespeicherten privaten Schlüssel zu "aktivieren".

Passen beide Schlüssel zusammen, ist der Server davon überzeugt, daß wir einer derjenigen sind, die Zugang erhalten sollen.

Um das beständige Nachfragen nach der Passphrase zu unterdrücken, ist es möglich, einen ssh-agent beim Login zu starten. Dieser Agent bekommt die Passphrase übergeben, kann den privaten Schlüssel aktivieren und in Zukunft alle Fragen nach diesem Schlüssel stellvertretend beantworten.

Für normale Konsolen-Logins geht das etwa so: (in der .profile oder wie immer die heißt) -- meine Login-Shell ist eine Bash.

     test "$SSH_AUTH_SOCK" || exec ssh-agent $SHELL -c "ssh-add; exec $SHELL -login"

Für X11-Nutzer: in meiner .xsession findet sich z.B. folgendes:

test "$SSH_AUTH_SOCK" || exec ssh-agent $SHELL -c "ssh-add </dev/null; exec fvwm2" exec fvwm2

(Achtung, SuSE: Offenbar wird bei SuSE (9.2) nach dem Anmelden am KDM schon irgendwo eine login-Shell gestartet, oder wenigstens wird die ~/.profile (oder ~/.bash_profile oder ~/.bash_login) abgearbeitet, mit dem Effekt, dass der Key erfragt wird und anschließend der ganze xinit-Prozess durcheinander kommt. Dort habe ich ein if test -z "$DISPLAY"; then ... um diese Zeilen, damit sie eben nur aktiv send, wenn es nicht als Teil der X11-Initialisierung getan wird.

Natürlich gibt's noch die "classic-Variante" mit eval `ssh-agent` und einem anschließenden ssh-add. Aber es bleiben dann Probleme beim Killen der nach Sessionende übrigbleibenden Agents. Immer noch Probleme?

Nun kann es sein, daß es trotzdem noch nicht paßwortfrei funktionert, was könnte alles geprüft werden?

   * Ist der ssh-Zugriff überhaupt möglich? (Ein beliebtes Problem ist ... key_exchange ... connection closed by foreign host. Das liegt dann meist daran, daß die Reverse-Auflösung der eigenen IP-Adresse nicht mit dem Namen für den eigenen Host übereinstimmt.
     Auf der anderen Seite in /etc/hosts.deny die ALL: PARANOID Zeile auskommentieren. Oder DNS in Ordnung bringen!
   * Passwort wird verlangt. Meistens ein Problem der Permissions auf der eigenen und/oder der anderen Seite: Das Verzeichnis .ssh/ und die die Datei .ssh/authorized_keys darf nur für den Eigentümer, der auch der "angepeilte" Nutzer sein muß, schreibbar sein. Auch das Home-Verzeichnis des angepeilten Nutzers darf ausschließlich für den Eigenümer beschreibbar sein.
     ssh -v ... hilft, diese Art von Problemen zu diagnostizieren.
   * Die SSH2 verlangt die Keys in ~/.ssh/authorized_keys2. M.W. ist die SSH2 auf Debian/GNU-Linux gepatcht und sucht die wie gehabt in ~/.ssh/authorized_keys, aber u.a. auf SuSE-Systemen habe ich schon gesehen, daß eben diese 2 angehängt werden muß. 

Erzwingen der Verwendung von Schlüsseln Wenn das jetzt alles so schön funktioniert, wollen wir ja auch die Anmeldung mit den Schlüsseln erzwingen. Wenn es nur den Root-Account betrifft, ist das relativ einfach:

   # /etc/ssh/sshd_config
   ...
   PermitRootLogin without-password
   ...

Wenn auch andere Nutzer von der Schlüsselnutzung überzeugt werden sollen, dann sieht es etwas komplexer aus:

   # /etc/ssh/sshd_config
   ...
   PasswordAuthentication no
   ChallengeResponseAuthentication no
   UsePAM yes
   ...

Wenn eine schlüsselfreie Anmeldung erkannt wird, versucht die SSH zuerst, PAM zu nutzen (UsePAM und ChallengeResponseAuthentication), zu erkennen am Passwort-Prompt Password:. Wenn das nicht funktioniert, versucht die SSH anschließend noch mal selbst, das Passwort zu prüfen (PasswordAuthentication), der Passwort-Prompt ändert sich zu user@host's password:. PAM auszuschalten wäre auch möglicht, ist aber nicht nützlich, weil dann z.B. Session-Management über PAM nicht mehr funktioniert, einige Umgebungsvariablen nicht gesetzt werden usw. usf. Waren die oben angegebenen Manipulationen erfolgreich, so darf keinesfalls nach einem Passwort, sondern nur nach einer Passphrase (das ist dann die für den privaten Schlüssel) gefragt werden. Natürlich muss für derlei Versuche der SSH-Agent ausgeschaltet, oder wenigstens "gelähmt" sein (ssh-add -x). Ist das alles?

Nein, natürlich nicht. Wenn nun mehrere Leute auf den den selben Account (z.B. root) einer Maschine zugreifen müssen und es sollen noch personenspezifische Dinge (History, Begrüßung, ... ) in z.B. der .bash_profile veranstaltet werden, dann gibt es eine ziemlich clevere Lösung:

An den Anfang der dem Nutzer entsprechenden Zeile in .ssh/authorized_keys wird eine Option eingetragen. Diese Zeile sieht dann etwa so aus:

enviroment="REMOTE_USER=heinz" 1024 37 1452609839509....

Diese Umgebungsvariable läßt sich dann prima auswerten und alles andere muß vielleicht nicht mehr erklärt werden ;-) (Übrigens: in der Manualseite zum sshd steht das alles beschrieben.)

Achtung: Bei neueren SSH (was ist neu? Neuer als 3.4) muß in der Konfiguration extra erlaubt werden, daß Environment-Variablen gesetzt werden dürfen. Sosnt werden die betroffenen Zeilen der authorized_keys einfach ignoriert. Die entsprechende Option heißt PermitUserEnvironment.

Vielen Dank an: Arthur Vollmer, Marcel Lauber und Axel Freund für Ergänzungen bzw. Korrekturen.