ssh-copy-id的 使用

ssh-copy-id是sshclient套件内一个预设的指令,简单的来说他只是一个script,当你在本机电脑已经有产生了RSAorDSAauthentication,可以透过ssh-copy-id的指令将认证传送到远端主机。

如何建立RSAorDSAauthentication?

$ssh-keygen-tdsa(ssh-keygen-trsa)

Generatingpublic/privatedsakeypair.

Enterfileinwhichtosavethekey(/root/.ssh/id_dsa)

RSA与DSA的差异

ssh-keygencancreateRSAkeysforusebySSHprotocolversion1and

RSAorDSAkeysforusebySSHprotocolversion2

简单来说,若您只使用SSHprotocolversion2,建议使用DSA来建立authentication。

ssh-copy-id的运用

$ssh-copy-id.orig-i~/.ssh/id_dsa.pubwawa@remotehost

wawa@remotehost'spassword:(需要输入一次密码)

Nowtryloggingintothemachine,with"ssh'wawa@remotehost'",andcheck

in:

.ssh/authorized_keys

tomakesurewehaven'taddedextrakeysthatyouweren'texpecting.

简单的执行ssh-copy-id.orig-i认证档案帐号@主机

就可以完成认证,之后就可以直接不敲密码就ssh连线到远端主机

基本上对外服务的主机,sshlistenport都会改掉预设的22port,如此一来可以减少主机被入侵的机会,更改sshlistenport是最基本的第一道防线,请将设定档内的Port22进行更改,并且重新启动ssh的服务。

但是当您改掉sshlistenport之后,ssh-copy-id这个好用的指令将无法运用,这样一来不是很可惜吗?于是我们就可以对ssh-copy-id这个script进行一些修改,让他可以支援指定不同的serviceport。

更改ssh-copy-id

$cp/usr/bin/ssh-copy-id/usr/bin/ssh-copy-id.orig

$vi/usr/bin/ssh-copy-id

#!/bin/sh

#Shellscripttoinstallyouridentity.pubonaremotemachine

#Takestheremotemachinenameasanargument.

#Obviously,theremotemachinemustacceptpasswordauthentication,

#oroneoftheotherkeysinyourssh-agent,forthistowork.

ID_FILE="${HOME}/.ssh/identity.pub"

whilegetopts':i:p:P:h'OPTION

do

case$OPTIONin

i)

if[-n"$OPTARG"];then

ifexpr"$OPTARG":".*.pub">/dev/null;then

ID_FILE="$OPTARG"

else

ID_FILE="$OPTARG.pub"

fi

fi

;;

P|p)

PORT=$OPTARG;

;;

h)

echo"Usage:$0[-i[identity_file]][user@]machine">&2

exit1

;;

esac;

done;

shift$(($OPTIND-1))

if[$#-lt1]&&[x$SSH_AUTH_SOCK!=x];then

GET_id="$GET_IDssh-add-L"

fi

if[-z"`eval$GET_ID`"]&&[-r"${ID_FILE}"];then

GET_id="cat${ID_FILE}"

fi

if[-z"`eval$GET_ID`"];then

echo"$0:ERROR:Noidentitiesfound">&2

exit1

fi

if[-z$PORT];then

PORTOPTION=""

else

PORTOPTION="-p$PORT"

fi;

{eval"$GET_ID";}|ssh$PORTOPTION$1"umask077;test-d.ssh||

mkdir.ssh;cat>>.ssh/authorized_keys"||exit1

cat<<EOF

Nowtryloggingintothemachine,with"ssh$PORTOPTION'$1'",andcheck

in:

.ssh/authorized_keys

tomakesurewehaven'taddedextrakeysthatyouweren'texpecting.

EOF

主要是增加了port的设定进去,建议可以直接复制贴上取代即可。

以上script参考来源:http://blog.vieth.biz/2009/03/23/ssh-copy-id-with-port/

ssh-copy-idwithport的运用

$ssh-copy-id-i~/.ssh/id_dsa.pub-p1234wawa@remotehost

wawa@remotehost'spassword:(需要输入一次密码)

Nowtryloggingintothemachine,with"ssh-p1234'wawa@remotehost'",

andcheckin:

.ssh/authorized_keys

tomakesurewehaven'taddedextrakeysthatyouweren'texpecting.

ssh-copy-idwithport的认证就完成啰!

转自:http://blog.csdn.net/Johnvikey/archive/2010/05/28/5630548.aspx

以上操作和脚本均在CentOS 5.x和6.x下均测试通过,转载以备日后查用。

常见问题:权限方面,须要保证在服务器端,authorized_keys能被other用户读取到,否则会提示输入密码,仍不能自动登录,如:

[usr@target ~]$ ll .ssh/

总计4

-rw----r--1usrusr61012-0510:11authorized_keys