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服务器。再次尝试登陆服务器会发现已经不需要密码了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值