Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1327676
  • 博文数量: 281
  • 博客积分: 8800
  • 博客等级: 中将
  • 技术积分: 3345
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-17 22:31
文章分类

全部博文(281)

文章存档

2013年(1)

2012年(18)

2011年(16)

2010年(44)

2009年(86)

2008年(41)

2007年(10)

2006年(65)

我的朋友

分类: LINUX

2009-09-02 21:56:34

SSH - How to arrange to log in without typing a password

If you want to automate an unattended process (e.g. cron or batch jobs) with SSH, you may notice, that SSH or SCP asks for a password, even from a script.

$ scp -q rabbit:/etc/hosts .
zahn@rabbit's password:

In this article, we show how to manage exactly this situation in a suitable security context using SSH version 1 with the RhostsRSAAuthentication method.

RhostsRSAAuthentication

The RhostsRSAAuthentication method is the rhosts or hosts.equiv method combined with RSA based host authentication. It means that if the login would be permitted by $HOME/.rhosts, $HOME/.shosts, /etc/hosts.equiv, or /etc/shosts.equiv, and if additionally the server can verify the client's host key (see /etc/ssh/ssh_known_hosts), only then login is permitted. This authentication method closes security holes due to IP spoofing, DNS spoofing and routing spoofing. Note to the administrator: /etc/hosts.equiv, $HOME/.rhosts, and the rlogin/rsh protocol in general, are inherently insecure and should be disabled if security is desired.

Example

You want to secure copy (scp) the file /backup/all.gz from the host rabbit to the host opal from a script which is started as a batch job from cron.

1. Setup $HOME/.shosts on the remote machine

If $HOME/.shosts exists in the user's home directory on the remote machine (rabbit) and contains a line containing the name of the client machine (opal) and the name of the user on that machine, the user is permitted to log in. This form of authentication alone is normally not allowed by the server because it is not secure.

On rabbit:

$ cd $HOME
$ ls -l .shosts

-r-------- 1 root root 7 Feb 4 10:48 .shosts

$ cat .shosts

opal root

2. Get the public key of the remote machine

If login would be permitted by $HOME/.shosts, and if additionally the server can verify the client's host key in /etc/ssh/ssh_known_hosts, only then login is permitted. This authentication method closes security holes due to IP spoofing, DNS spoofing and routing spoofing.

Simply log on to the remote machine, the public key will then automatically transferred to the local machine and inserted in $HOME/.ssh/known_hosts. Copy or append the public key the the file /etc/ssh/ssh_known_hosts.

On opal:

$ ssh rabbit

The authenticity of host 'rabbit' can't be established.
RSA key fingerprint is
b2:fc:62:5e:5f:06:ca:63:0a:8c:52:03:db:ad:be:52.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'rabbit,192.168.138.21' (RSA)
to the list of known hosts.

$ cd $HOME/.ssh
$ cat known_hosts >> /etc/ssh/ssh_known_hosts

3. Setup SSHD on the remote machine

The most important step is to configure the secure shell daemon (sshd) on the remote machine. You find the sshd configuration file in /etc/ssh/sshd_config. The needed parameters are the followings:

  • IgnoreRhosts no

  • IgnoreUserKnownHosts yes

  • RhostsAuthentication no

  • RhostsRSAAuthentication yes

Here is the complete file

# This is ssh server systemwide configuration file.

####### Port
#
# Specifies the port number that sshd listens on. The default is 22.
# Multiple options of this type are permitted.
#

Port 22

####### Protocol
#
# Specifies the protocol versions sshd should support. The possible
# values are 1 and 2. Multiple versions must be commaseparated.
# The default is 1.
#

Protocol 1,2

####### ListenAddress
#
# Specifies what local address sshd should listen on. The default
# is to listen to all local addresses. Multiple options of this
# type are permitted. Additionally, the Ports options must precede
# this option.
#

ListenAddress 0.0.0.0

####### HostKey (private host key)
#
# Specifies the file containing the private host keys (default
# /etc/ssh_host_key) used by SSH protocol versions 1 and 2. Note
# that sshd will refuse to use a file if it is group/world-accessible.
# It is possible to have multiple host key files. "rsa1"
# keys are used for version 1 and "dsa" or "rsa" are used for
# version 2 of the SSH protocol.
#

HostKey /etc/ssh/ssh_host_key

####### ServerKeyBits (SSH protocol version 1)
#
# Defines the number of bits in the server key. The minimum value
# is 512, and the default is 768.
#
# Each host has a private host key RSA key (normally 1024 bits) used to iden-
# tify the host. Additionally, when the daemon starts, it generates a
# server RSA key (normally 768 bits). This key is normally regenerated ev-
# ery hour if it has been used, and is never stored on disk.
#
# Whenever a client connects the daemon responds with its public host and
# server keys. The client compares the RSA host key against its own
# database to verify that it has not changed. The client then generates a
# 256 bit random number. It encrypts this random number using both the
# host key and the server key, and sends the encrypted number to the serv-
# er. Both sides then use this random number as a session key which is
# used to encrypt all further communications in the session. The rest of
# the session is encrypted using a conventional cipher, currently Blowfish
# or 3DES, with 3DES being used by default. The client selects the encryp-
# tion algorithm to use from those offered by the server.
#

ServerKeyBits 768
KeyRegenerationInterval 3600

####### LoginGraceTime
#
# The server disconnects after this time if the user has not successfully
# logged in. If the value is 0, there is no time limit.
# The default is 600 (seconds).
#

LoginGraceTime 600

####### PermitRootLogin
#
# Specifies whether the root can log in using ssh(1). The argument
# must be "yes", "without-password" or "no". The default is
# "yes". If this options is set to "without-password" only
# password authentication is disabled for root.
#
# Root login with RSA authentication when the command option has
# been specified will be allowed regardless of the value of this
# setting (which may be useful for taking remote backups even if
# root login is normally not allowed).
#

PermitRootLogin yes

####### IgnoreRhosts
#
# Specifies that ~/.rhosts and ~/.shosts files will not be used in
# authentication. /etc/hosts.equiv and /etc/shosts.equiv are still
# used. The default is "yes".
#
# No: Read ~/.rhosts and ~/.shosts files
# Yes: Don't read ~/.rhosts and ~/.shosts files
#

IgnoreRhosts no

####### IgnoreUserKnownHosts
#
# Specifies whether sshd should ignore the user's
# $HOME/.ssh/known_hosts during RhostsRSAAuthentication.
# The default is "no".
#
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#

IgnoreUserKnownHosts yes

####### StrictModes
#
# Specifies whether sshd should check file modes and ownership of
# the user's files and home directory before accepting login. This
# is normally desirable because novices sometimes accidentally
# leave their directory or files world-writable. The default is "yes".
#

StrictModes yes

####### X11Forwarding
#
# Specifies whether X11 forwarding is permitted. The default is
# "no". Note that disabling X11 forwarding does not improve security
# in any way, as users can always install their own forwarders.
#

X11Forwarding yes

####### X11DisplayOffset
#
# Specifies the first display number available for sshd's X11
# forwarding. This prevents sshd from interfering with real X11
# servers. The default is 10.
#

X11DisplayOffset 10

####### PrintMotd
#
# Specifies whether sshd should print /etc/motd when a user logs in
# interactively. (On some systems it is also printed by the shell,
# /etc/profile, or equivalent.) The default is "yes".
#

PrintMotd no

####### KeepAlive
#
# Specifies whether the system should send keepalive messages to
# the other side. If they are sent, death of the connection or
# crash of one of the machines will be properly noticed. However,
# this means that connections will die if the route is down tem-
# porarily, and some people find it annoying. On the other hand,
# if keepalives are not sent, sessions may hang indefinitely on the
# server, leaving "ghost" users and consuming server resources.
#
# The default is "yes" (to send keepalives), and the server will
# notice if the network goes down or the client host reboots. This
# avoids infinitely hanging sessions.
#
# To disable keepalives, the value should be set to "no" in both
# the server and the client configuration files.
#

KeepAlive yes

####### SyslogFacility
#
# Gives the facility code that is used when logging messages from
# sshd. The possible values are: DAEMON, USER, AUTH, LOCAL0, LOCAL1
# LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7. The default is AUTH.
#

SyslogFacility AUTH

####### LogLevel
#
# Gives the verbosity level that is used when logging messages from
# sshd. The possible values are: QUIET, FATAL, ERROR, INFO, VERBOSE
# and DEBUG. The default is INFO. Logging with level DEBUG violates
# the privacy of users and is not recommended.
#

LogLevel INFO

####### RhostsAuthentication
#
# Specifies whether authentication using rhosts or /etc/hosts.equiv
# files is sufficient. Normally, this method should not be permitted
# because it is insecure. RhostsRSAAuthentication should be
# used instead, because it performs RSA-based host authentication
# in addition to normal rhosts or /etc/hosts.equiv authentication.
# The default is "no".
#

RhostsAuthentication no

####### RhostsRSAAuthentication
#
# Specifies whether rhosts or /etc/hosts.equiv authentication to-
# gether with successful RSA host authentication is allowed. The
# default is "no".
# For this to work you will also need host keys in /etc/ssh_known_hosts
#

RhostsRSAAuthentication yes

####### RSAAuthentication
#
# Specifies whether pure RSA authentication is allowed. The de-
# fault is "yes". Note that this option applies to protocol ver-
# sion 1 only.
#

RSAAuthentication no

####### PasswordAuthentication
#
# Specifies whether password authentication is allowed. The de-
# fault is "yes". Note that this option applies to both protocol
# versions 1 and 2. To disable tunneled clear text passwords,
# change to no here!
#

PasswordAuthentication yes

####### PermitEmptyPasswords
#
# When password authentication is allowed, it specifies whether the
# server allows login to accounts with empty password strings. The
# default is "no".
#

PermitEmptyPasswords no

####### CheckMail
#
# Specifies whether sshd should check for new mail for interactive
# logins. The default is "no".
#

CheckMail no

####### UseLogin
#
# Specifies whether login(1) is used for interactive login ses-
# sions. Note that login(1) is never used for remote command exe-
# cution. The default is "no".
#

UseLogin no

####### AllowUsers
#
# This keyword can be followed by a number of user names, separated
# by spaces. If specified, login is allowed only for users names
# that match one of the patterns. '*' and '?' can be used as wild-
# cards in the patterns. Only user names are valid; a numerical
# user ID isn't recognized. By default login is allowed regardless
# of the user name.
#

AllowUsers root scott smith

4. Setup SSH on the local machine

The final step is to configure the secure shell (ssh) on the local machine. You find the ssh configuration file in /etc/ssh/ssh_config. The needed parameters are the followings:

# This is ssh client systemwide configuration file. This file provides
# defaults for users, and the values can be changed in per-user configuration
# files or on the command line.
#
# Configuration data is parsed as follows:
#
# 1. command line options
# 2. user-specific file
# 3. system-wide file
#
# Any configuration value is only changed the first time it is set.
# Thus, host-specific definitions should be at the beginning of the
# configuration file, and defaults at the end.

# Site-wide defaults for various options

####### Host
#
# Restricts the following declarations (up to the next Host key-
# word) to be only for those hosts that match one of the patterns
# given after the keyword. "*" and "?" can be used as wildcards in
# the patterns. A single "*" as a pattern can be used to provide
# global defaults for all hosts. The host is the hostname argument
# given on the command line (i.e., the name is not converted to a
# canonicalized host name before matching).
#

Host *

####### ForwardAgent
#
# Specifies whether the connection to the authentication agent
# (if any) will be forwarded to the remote machine. The argument
# must be "yes" or "no". The default is "yes".
#

ForwardAgent no

####### ForwardX11
#
# Specifies whether X11 connections will be automatically redirected
# over the secure channel and DISPLAY set. The argument must be
# "yes" or "no". The default is "no".
#

ForwardX11 yes

####### RhostsAuthentication
#
# Specifies whether to try rhosts based authentication. Note that
# this declaration only affects the client side and has no effect
# whatsoever on security. Disabling rhosts authentication may re-
# duce authentication time on slow connections when rhosts authen-
# tication is not used. Most servers do not permit RhostsAuthenti-
# cation because it is not secure (see RhostsRSAAuthentication).
# The argument to this keyword must be "yes" or "no".
#

RhostsAuthentication no

####### RhostsRSAAuthentication
#
# Specifies whether to try rhosts based authentication with RSA
# host authentication. This is the primary authentication method
# for most sites. The argument must be "yes" or "no".
#

RhostsRSAAuthentication yes

####### RSAAuthentication
#
# Specifies whether to try RSA authentication. The argument to
# this keyword must be "yes" or "no". RSA authentication will
# only be attempted if the identity file exists, or an authentica-
# tion agent is running. Note that this option applies to protocol
# version 1 only.
#

RSAAuthentication no

####### PasswordAuthentication
#
# Specifies whether to use password authentication. The argument
# to this keyword must be "yes" or "no". Note that this option
# applies to both protocol version 1 and 2.
#

PasswordAuthentication yes

####### FallBackToRsh
#
# Specifies that if connecting via ssh fails due to a connection
# refused error (there is no sshd listening on the remote host),
# rsh should automatically be used instead (after a suitable
# warning about the session being unencrypted). The argument must
# be "yes" or "no".
#

FallBackToRsh no

####### UseRsh
#
# Specifies that rlogin/rsh should be used for this host. It is
# possible that the host does not at all support the ssh protocol.
# This causes ssh to immediately execute rsh. All other options
# (except HostName) are ignored if this has been specified. The
# argument must be "yes" or "no".
#

UseRsh no

####### BatchMode
#
# If set to "yes", passphrase/password querying will be disabled.
# This option is useful in scripts and other batch jobs where you
# have no user to supply the password. The argument must be
# "yes" or "no".
#

BatchMode no

####### CheckHostIP
#
# If this flag is set to "yes", ssh will additionally check the
# host ip address in the known_hosts file. This allows ssh to de-
# tect if a host key changed due to DNS spoofing. If the option is
# set to "no", the check will not be executed.
#

CheckHostIP yes

####### StrictHostKeyChecking
#
# If this flag is set to "yes", ssh will never automatically add
# host keys to the $HOME/.ssh/known_hosts and
# $HOME/.ssh/known_hosts2 files, and refuses to connect to hosts
# whose host key has changed. This provides maximum protection
# against trojan horse attacks. However, it can be somewhat annoy-
# ing if you don"t have good /etc/ssh_known_hosts and
# /etc/ssh_known_hosts2 files installed and frequently connect to
# new hosts. This option forces the user to manually add all new
# hosts. If this flag is set to "no", ssh will automatically add
# new host keys to the user known hosts files. If this flag is set
# to "ask", new host keys will be added to the user known host
# files only after the user has confirmed that is what they really
# want to do, and ssh will refuse to connect to hosts whose host
# key has changed. The host keys of known hosts will be verified
# automatically in all cases. The argument must be "yes", "no"
# or "ask". The default is "ask".
#

StrictHostKeyChecking yes

####### IdentityFile
#
# Specifies the file from which the user"s RSA authentication iden-
# tity is read (default $HOME/.ssh/identity in the user"s home di-
# rectory). Additionally, any identities represented by the au-
# thentication agent will be used for authentication. The file
# name may use the tilde syntax to refer to a user"s home directo-
# ry. It is possible to have multiple identity files specified in
# configuration files; all these identities will be tried in se-
# quence.
#

IdentityFile ~/.ssh/identity

####### Port
#
# Specifies the port number to connect on the remote host.
# Default is 22.
#

Port 22

####### Protocol
#
# Specifies the protocol versions ssh should support in order of
# preference. The possible values are "1" and "2". Multiple
# versions must be comma separated. The default is "1,2". This
# means that ssh tries version 1 and falls back to version 2 if
# version 1 is not available.
#

Protocol 1,2

####### Cipher
#
# Specifies the cipher to use for encrypting the session in proto-
# col version 1. Currently, "blowfish" and "3des" are support-
# ed. The default is "3des".
#

Cipher 3des

####### EscapeChar
#
# Sets the escape character (default: "~"). The escape character
# can also be set on the command line. The argument should be a
# single character, "^" followed by a letter, or "none" to dis-
# able the escape character entirely (making the connection trans-
# parent for binary data).
#

EscapeChar none

4. Test the connection

Now, you should be able to connect to the remote host without a password. First try the debugging output using the -v option.

opal> ssh -v rabbit "cat /etc/ssh/ssh_config" > ssh_config

SSH Version OpenSSH_2.1.1, protocol versions 1.5/2.0.
Compiled with SSL (0x0090581f).
debug: Reading configuration data /usr/local/etc/ssh_config
debug: Applying options for *
debug: Seeding random number generator
debug: ssh_connect: getuid 0 geteuid 0 anon 0
debug: Connecting to rabbit [193.247.121.196] port 22.
debug: Seeding random number generator
debug: Allocated local port 882.
debug: Connection established.
debug: Remote protocol version 1.99, remote software version OpenSSH_2.1.1
debug: Local version string SSH-1.5-OpenSSH_2.1.1
debug: Waiting for server public key.
debug: Received server public key (768 bits) and host key (1024 bits).
debug: Host 'rabbit' is known and matches the RSA host key.
debug: Seeding random number generator
debug: Encryption type: 3des
debug: Sent encrypted session key.
debug: Installing crc compensation attack detector.
debug: Received encrypted confirmation.
debug: Trying rhosts or /etc/hosts.equiv with RSA host authentication.
debug: Remote: Accepted by .shosts.
debug: Received RSA challenge for host key from server.
debug: Sending response to host key RSA challenge.
debug: Remote: Rhosts with RSA host authentication accepted.
debug: Rhosts or /etc/hosts.equiv with RSA host auth accepted by server.
debug: Requesting X11 forwarding with authentication spoofing.
debug: Sending command: cat /etc/ssh/ssh_config
debug: Entering interactive session.
debug: Transferred: stdin 0, stdout 6425, stderr 0 bytes in 0.3 seconds
debug: Bytes per second: stdin 0.0, stdout 19644.7, stderr 0.0
debug: Exit status 0

opal> scp -v rabbit:/etc/hosts .

Executing: host rabbit, user (unspecified), command scp -v -f /etc/hosts
SSH Version OpenSSH_2.1.1, protocol versions 1.5/2.0.
Compiled with SSL (0x0090581f).
debug: Reading configuration data /usr/local/etc/ssh_config
debug: Applying options for *
debug: Seeding random number generator
debug: ssh_connect: getuid 0 geteuid 0 anon 0
debug: Connecting to rabbit [193.247.121.196] port 22.
debug: Seeding random number generator
debug: Allocated local port 700.
debug: Connection established.
debug: Remote protocol version 1.99, remote software version OpenSSH_2.1.1
debug: Local version string SSH-1.5-OpenSSH_2.1.1
debug: Waiting for server public key.
debug: Received server public key (768 bits) and host key (1024 bits).
debug: Host 'rabbit' is known and matches the RSA host key.
debug: Seeding random number generator
debug: Encryption type: 3des
debug: Sent encrypted session key.
debug: Installing crc compensation attack detector.
debug: Received encrypted confirmation.
debug: Trying rhosts or /etc/hosts.equiv with RSA host authentication.
debug: Remote: Accepted by .shosts.
debug: Received RSA challenge for host key from server.
debug: Sending response to host key RSA challenge.
debug: Remote: Rhosts with RSA host authentication accepted.
debug: Rhosts or /etc/hosts.equiv with RSA host auth accepted by server.
debug: Sending command: scp -v -f /etc/hosts
debug: Entering interactive session.
Sending file modes: C0644 5578 hosts
debug: Transferred: stdin 3, stdout 5633, stderr 0 bytes in 0.1 seconds
debug: Bytes per second: stdin 53.2, stdout 99934.3, stderr 0.0
debug: Exit status 0

原文:

上面的文档介绍了一种不需要输入口令就可以登录sshd服务器的方法。因为对ssh协议不是很熟悉,所以不知道这种方法是否可用。也没有具体做过实验。先转过来吧。

我比较常用的方法是

http://www.mangbar.com/document/view/bd18e8290d351416010d357315ba0053

另外也可以用expect来实现

Pexpect(Pure python expect)的主页:

 原文地址 http://www.mangbar.com/document/5d023b211232d34601124a896af60986

 

 

 

.................................

 

How to transfer files between two linux boxs without pwd   
Let me guess you have two linux boxs ( linux1 and linux2). You want to copy files from linux1 to linux2 without password or do it at crontab.
1. Install SSH
2. Create two users. user1 at liunx1 and user2 at linux2.
3. On linux2, login as user2. do
ssh-keygen -P "" -trsa1 -f ~/.ssh/identity
4. Copy key file to linux1
scp /home/user2/.ssh/identity.pub
[email=user1@linux1:/home/user1/.ssh/authorized_keys]user1@linux1:/home/user1/.ssh/authorized_keys[/email]
5. Change file permission
chmod 600 /home/user2/.ssh/authorized_keys
6. change ssh config file: /etc/ssh/ssh_config
Ad
Host *
ForwardX11 yes
IdentityFile ~/.ssh/identity
Protocol 1
7. Restart sshd
8. login to linux1 as user1.
9.Change file permission
chmod 600 /home/user1/.ssh/identity
10. Restart sshd
Now, you can ssh or secure copy filles by using user1 from linux1 to linux2 without prompt


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/1214/showart_431511.html

 

 

 

 

A为本地主机(即用于控制其他主机的机器) ;

  B为远程主机(即被控制的机器Server), 假如ip为172.24.253.2 ;

  A和B的系统都是Linux

  在A上的命令:

  # ssh-keygen -t rsa (连续三次回车,即在本地生成了公钥和私钥,不设置密码)

  # ssh root@172.24.253.2 "mkdir .ssh;chmod 0700 .ssh" (需要输入密码)

  # scp ~/.ssh/id_rsa.pub root@172.24.253.2:.ssh/id_rsa.pub (需要输入密码)

  在B上的命令:

  # touch /root/.ssh/authorized_keys2 (如果已经存在这个文件, 跳过这条)

  # cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys2 (将id_rsa.pub的内容追加到 authorized_keys2 中)

  回到A机器:

  # ssh root@172.24.253.2 (不需要密码, 登录成功)

  如果能保护好自己的私钥, 这种方法相对在shell上输入密码, 要安全一些

  深入一点点:

  从表面上简单的理解一下登录的过程,

  首先 ssh-keygen -t rsa 命令生成了一个密钥和一个公钥, 而且密钥可以设置自己的密码

  可以把密钥理解成一把钥匙, 公钥理解成这把钥匙对应的锁头,

  把锁头(公钥)放到想要控制的server上, 锁住server, 只有拥有钥匙(密钥)的人, 才能打开锁头, 进入server并控制

  而对于拥有这把钥匙的人, 必需得知道钥匙本身的密码,才能使用这把钥匙 (除非这把钥匙没设置密码), 这样就可以防止钥匙被了配了(私钥被人复制)

  当然, 这种例子只是方便理解罢了,

  拥有root密码的人当然是不会被锁住的, 而且不一定只有一把锁(公钥), 但如果任何一把锁, 被人用其对应的钥匙(私钥)打开了, server就可以被那个人控制了

  所以说, 只要你曾经知道server的root密码, 并将有root身份的公钥放到上面, 就可以用这个公钥对应的私钥"打开" server, 再以root的身分登录, 即使现在root密码已经更改!

  如果想控制n个机器, 那就需要n对钥匙(密钥和公钥), ssh-keygen 命令可以随意更改钥匙对的名字, 比如:

  [root@wwy .ssh]# ssh-keygen -t rsa

  Generating public/private rsa key pair.

  Enter file in which to save the key (/root/.ssh/id_rsa): /root/.ssh/id_rsa_192.168.102.12

  ......

  这样私钥和公钥的名字分别就是:

  id_rsa_192.168.102.12 和 id_rsa_192.168.102.12.pub

  然后将 id_rsa_192.168.102.12.pub 文件的内容, 追加到sever的 ~/.ssh/authorized_keys2 文件中,

  最后, 在本地用ssh命令的 -i 参数指定本地密钥, 并登录:

  # ssh -i /root/.ssh/id_rsa_192.168.102.12 192.168.102.12

  如果密钥设置了密码, 就用密钥的密码登录, 没设密码, 就直接登录进去了

  scp也是一样的

 

--------------------------------

 

假设服务器网址为: server.joycodes.com,客户端就为本地电脑.默认情况下,我们通过客户端ssh到服务器端,是需要输入密码来进行认证的.除了使用用户名和密码,SSH还可以使用公钥/私钥来进行认证,这样就避免在同一客户端SSH多次输入麻烦.

SSH 使用公钥/密钥认证的原理如下:

服务器端持有公钥,客户端持有密钥,当客户端通过SSH到服务器端时将会发送私钥,服务器端根据私钥和自身持有的密钥进行验证.如果匹配,认证通过.具体设置如下:

 1.登录到服务器端,生成SSH公钥和密钥

 1joy:joys-macpro31:~$ssh root@server.joycodes.com #登录用户为root
 2root@server.joycodes.com's password:   #输入root的密码
 3[root@joycodes ~]#ssh-keygen -t rsa
 5Generating public/private rsa key pair.
 6Enter passphrase (empty for no passphrase):  #直接按回车
 7Enter same passphrase again:  #直接按回车
 8Your identification has been saved in /root/.ssh/id_rsa.
 9Your public key has been saved in /root/.ssh/id_rsa.pub.
10The key fingerprint is:
11c5:ec:ce:c5:67:eb:fb:a4:05:a0:fd:05:75:92:ec:1c joy@joys-macpro31.local

 

2.在服务器端将生成的公钥加入authorized_keys中

[root@joycodes ~]# cd ~/.ssh
[root@joycodes ~]# cat id_rsa.pub >> authorized_keys
[root@joycodes ~]# chmod 600 authorized_keys

 

3.退出服务器端,将私钥保存到客户端

1 [root@joycodes ~]# exit
2 joy:joys-macpro31:~$ mkdir -~/.ssh
3 joy:joys-macpro31:~$ cd ~/.ssh
4 joy:joys-macpro31:~/.ssh$ scp neo@server1.techpulp.com:.ssh/id_rsa ./
5 root@server.joycodes.com's password: #再次输入服务器密码 将私钥下载到 ~/.ssh目录中
6 .ssh/id_rsa                                          100% 2587     2.5KB/s   00:00
7 joy:joys-macpro31:~/.ssh$ chmod 600 id_rsa

 

 经过上面步骤后,在次运行 ssh root@server.joycodes.com后就可以直接登录到服务器而无需输入密码.

 附文件

 

this capistrano file is for enable ssh auto login
# run command 
=> cap ssh_auto_login
# by joycodes@gmail.com
set :user, "root" # the user name login for remote server
set :password, "passwd" # login passwd for
role :app, 
"" # remote host
desc 
"this task is for set ssh auto login"
task :ssh_auto_login,:role 
=> :app do
      cmd 
=<<-COMMAND
        cd 
~/.ssh
        ssh
-keygen -t rsa
        cat id_rsa.pub 
>> authorized_keys
        chmod 
600 authorized_keys
      COMMAND
      run cmd.split(
/\n\s*/).join(' && 'do |channel, stream ,data|
        logger.info data
        
if data =~ /Enter file in/
        channel.send_data 
"\n"
      elsif data 
=~ /Overwrite/
        channel.send_data 
"y\n"
      elsif data 
=~ /Enter same passphrase/
        channel.send_data 
"\n"
      elsif data 
=~ /Enter passphrase/
        channel.send_data 
"\n"
      end
      end
      
get "/#{user}/.ssh/id_rsa"'/Users/joy/.ssh/id_rsa' #/User/joy is current local user home path
    run_locally 
"chmod 600 ~/.ssh/id_rsa"
end

 参考原文: 

 

 

When maintaining multiple servers with different rsa-keys it isn't possible to put all the files in ~/.ssh/id_rsa.
With multiple keys in ~/.ssh/id_rsa it only accepts the first key, the rest is ignored.
the way I create the id_rsa file:
cat id_rsa_server >> ~/.ssh/id_rsa

 

I don't understand what you're trying to do. The id_rsa file is only supposed to contain one key; you can put other keys in different files. What are you trying to achieve by putting multiple keys in one file?

on 2009-05-11
Changed in openssh (Ubuntu):
status: New → Incomplete
wrote on 2009-06-02:

wretched_dutchman wrote:

> > When maintaining multiple servers with different rsa-keys it isn't possible to put all the files in ~/.ssh/id_rsa.

Colin answered:

> I don't understand what you're trying to do. The id_rsa file is only supposed to contain one key; you can put other keys in
> different files. What are you trying to achieve by putting multiple keys in one file?

I'm having the same problem I guess:

There are several servers that have different public keys. Now I find out that I want to log into them from the same client machine. I could go and copy all the private keys to different id_rsa files:

- id_rsa1
- id_rsa2
- id_rsa3

Now why would I need/want to differentiate the keys? I don't care what they are named. I just want to log in with whatever key fits (to use a RL analogy: I'd just try to plug in one key after the other into the lock until one opens it).

So I'd say this is more of a feature request?
*t

on 2009-06-02
Changed in openssh (Ubuntu):
status: Incomplete → Confirmed
wrote on 2009-06-02:

> Now why would I need/want to differentiate the keys? I don't care what they are named. I just want to log in with whatever > key fits (to use a RL analogy: I'd just try to plug in one key after the other into the lock until one opens it).

So I'd like to say something like: use whatever key fits. So either I'd need to give start ssh like this:

   ssh -i ~/.ssh/id_rsa1 -i ~/.ssh/id_rsa2 -i ~/.ssh/id_rsa3 -i ~/.ssh/id_rsa4 ...

which is bothersome or, the natural way would seem like saying:

   ssh -i ~/.ssh/id_rsa

respectively by using the default identity file:

   ssh ...

which would use whatever key in id_rsa that works with the public key on the server.
*t

wrote on 2009-06-03:

The correct way of doing this is to specify multiple "IdentityFile" lines in your ~/.ssh/config

The id_rsa[.pub] files represent a keypair and isn't supposed to contain multiple identities, but it's easy and perfectly valid to use several keys, either by using -i or IdentityFile. Closing as this is not a bug and not really a missing feature.

Changed in openssh (Ubuntu):
status: Confirmed → Invalid
wrote on 2009-06-24:

To give more detail, here's what your ~/.ssh/config file needs to look like:

Host *
IdentityFile id_rsa.pub
Host hostname_with_special_keys.com
IdentifyFile id_rsa.hostname_with_special_keys.pub
Host another_host.com
IdentityFile id_rsa.another_host.pub

The actual hostnames and file names are arbitrary, and do not need to match. By doing this, you won't need to specify -i on the commandline each time.

阅读(2685) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~