cmder ssh免密登錄

Linux服務器每次登陸或者scp複製文件時都需要繁瑣的輸入密碼過程,而使用SSH Key來實現SSH無密碼登錄不僅免去了繁瑣的密碼輸入步驟,也爲Linux服務器增加了又一道安全防線(可以禁用掉ssh-root密碼登錄).

很多文章介紹ssh無密碼登錄方式都有多個步驟,其實遠不必這麼麻煩,接下來我們以windows系統cmder爲例完成ssh無密碼登錄設置,要求下載的cmder爲完整版。

  1. SSH密鑰和公鑰是否存在?
    首先看C:\Users{用戶名}目錄下有沒有.ssh目錄,並且目錄中是否已經存在id_rsa.pub文件,如果已經有該文件,請跳到步驟3,請不要輕易刪除該文件,除非你知道該文件被覆蓋/刪除意味着什麼。

  2. 生成SSH公鑰和密鑰文件
    打開cmder,執行:ssh-keygen -t rsa,按Enter鍵,輸入一個密碼,然後再次輸入同樣的密碼,密碼至少要20位長度,隨後就會在.ssh文件夾生成相對應的公私鑰文件。

  3. 將SSH公鑰上傳到Linux服務器

"""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)
local_key = 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執行python ssh-copy-id.py [email protected],其中root爲登陸用戶名,xx.xx.xx.xx爲IP
隨後會提示輸入遠程服務器密碼,密碼正確則自動登陸服務器並把公鑰文件複製到Linux服務器。再次嘗試登陸服務器會發現已經不需要密碼了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章