Windows系统使用cmder-ssh免密码登录linux服务器

Linux服务器每次登陆或者scp复制文件时都需要繁琐的输入密码过程,而使用SSH Key来实现SSH无密码登录不仅免去了繁琐的密码输入步骤,也为Linux服务器增加了又一道安全防线(可以禁用掉ssh-root密码登录).

很多文章介绍ssh无密码登录方式都有多个步骤,其实远不必这么麻烦,接下来我们以windows系统cmder为例完成ssh无密码登录设置,要求下载的cmder为完整版。

  1. SSH密钥和公钥是否存在?

首先看C:Users{用户名}目录下有没有.ssh目录,并且目录中是否已经存在id_rsa.pub文件,如果已经有该文件,请跳到步骤3,请不要轻易删除该文件,除非你知道该文件被覆盖/删除意味着什么。

  1. 生成SSH公钥和密钥文件

打开cmder,执行:ssh-keygen -t rsa,按Enter键,输入一个密码,然后再次输入同样的密码,密码至少要20位长度,随后就会在.ssh文件夹生成相对应的公私钥文件。

  1. 将SSH公钥上传到Linux服务器
  2. 使用脚本完成操作
"""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执行python ssh-copy-id root@xx.xx.xx.xx,其中root为登陆用户名,xx.xx.xx.xx为IP
随后会提示输入远程服务器密码,密码正确则自动登陆服务器并把公钥文件复制到Linux服务器。再次尝试登陆服务器会发现已经不需要密码了。

相关推荐