Linux服務(wù)器每次登陸或者scp復(fù)制文件時(shí)都需要繁瑣的輸入密碼過(guò)程沈善,而使用SSH Key來(lái)實(shí)現(xiàn)SSH無(wú)密碼登錄不僅免去了繁瑣的密碼輸入步驟乓搬,也為L(zhǎng)inux服務(wù)器增加了又一道安全防線(可以禁用掉ssh-root密碼登錄).
很多文章介紹ssh無(wú)密碼登錄方式都有多個(gè)步驟,其實(shí)遠(yuǎn)不必這么麻煩千埃,接下來(lái)我們以windows系統(tǒng)cmder為例完成ssh無(wú)密碼登錄設(shè)置,要求下載的cmder為完整版。
1. SSH密鑰和公鑰是否存在残家?
首先看C:\Users\{用戶名}
目錄下有沒(méi)有.ssh
目錄,并且目錄中是否已經(jīng)存在id_rsa.pub
文件售躁,如果已經(jīng)有該文件跪削,請(qǐng)?zhí)讲襟E3,請(qǐng)不要輕易刪除該文件迂求,除非你知道該文件被覆蓋/刪除意味著什么碾盐。
2. 生成SSH公鑰和密鑰文件
打開(kāi)cmder,執(zhí)行:ssh-keygen -t rsa
揩局,按Enter鍵毫玖,輸入一個(gè)密碼,然后再次輸入同樣的密碼凌盯,密碼至少要20位長(zhǎng)度付枫,隨后就會(huì)在.ssh
文件夾生成相對(duì)應(yīng)的公私鑰文件。
3. 將SSH公鑰上傳到Linux服務(wù)器
"""ssh-copy-id for Windows.
Example usage: python ssh-copy-id.py ceilfors@my-remote-machine
This script is dependent on msysgit by default as it requires scp and ssh.
For convenience you can also try that comes http://bliker.github.io/cmder/.
"""
import argparse, os
from subprocess import call
def winToPosix(win):
"""Converts the specified windows path as a POSIX path in msysgit.
Example:
win: C:\\home\\user
posix: /c/home/user
"""
posix = win.replace('\\', '/')
return "/" + posix.replace(':', '', 1)
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--identity_file", help="identity file, default to ~\\.ssh\\idrsa.pub", default=os.environ['HOME']+"\\.ssh\\id_rsa.pub")
parser.add_argument("-d", "--dry", help="run in the dry run mode and display the running commands.", action="store_true")
parser.add_argument("remote", metavar="user@machine")
args = parser.parse_args()
local_key = winToPosix(args.identity_file)
remote_key = "~/temp_id_rsa.pub"
# Copy the public key over to the remote temporarily
scp_command = "scp {} {}:{}".format(local_key, args.remote, remote_key)
print(scp_command)
if not args.dry:
call(scp_command)
# Append the temporary copied public key to authorized_key file and then remove the temporary public key
ssh_command = ("ssh {} "
"mkdir ~/.ssh;"
"touch ~/.ssh/authorized_keys;"
"cat {} >> ~/.ssh/authorized_keys;"
"rm {};").format(args.remote, remote_key, remote_key)
print(ssh_command)
if not args.dry:
call(ssh_command)
將以上python代碼保存到本地驰怎,命名為ssh-copy-id.py
阐滩,然后cmder執(zhí)行python ssh-copy-id root@xx.xx.xx.xx
,其中root
為登陸用戶名县忌,xx.xx.xx.xx為IP
隨后會(huì)提示輸入遠(yuǎn)程服務(wù)器密碼掂榔,密碼正確則自動(dòng)登陸服務(wù)器并把公鑰文件復(fù)制到Linux服務(wù)器。再次嘗試登陸服務(wù)器會(huì)發(fā)現(xiàn)已經(jīng)不需要密碼了症杏。