windows git - 服务器主机密钥未缓存

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4931384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:03:27  来源:igfitidea点击:

git - Server host key not cached

windowsgitsshputtyplink

提问by Rene Terstegen

I try to push changes from my local repo to a remote repo. When I type:

我尝试将更改从本地存储库推送到远程存储库。当我输入:

git push origin

I get the following error:

我收到以下错误:

The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx
Connection abandoned.
fatal: The remote end hung up unexpectedly

How can I solve this? I'm using git from the command line in Windows 7.

我该如何解决这个问题?我在 Windows 7 的命令行中使用 git。

Edit

编辑

When I try to do a simple ssh

当我尝试做一个简单的 ssh 时

ssh user@hostname

I get the following error:

我收到以下错误:

Could not create directory '/c//%HOMEDRIVE%%HOMEPATH%/.ssh'.
percent_expand: unknown key %H

Somehow it will not create the directory, because the path is invalid. How to fix this?

它不会以某种方式创建目录,因为路径无效。如何解决这个问题?

@eckes: Edit2

@eckes:Edit2

My Home is set to %HOMEDRIVE%%HOMEPATH%is this correct?

我的主页设置为%HOMEDRIVE%%HOMEPATH%正确吗?

采纳答案by eckes

The message means that the host key of originis not present in your trusted hosts file.

该消息意味着origin您的受信任主机文件中不存在的主机密钥。

To get around this, open a plain SSH connection to originand SSH will ask you if you want to trust the remote host (from the Git console):

为了解决这个问题,打开一个普通的 SSH 连接origin,SSH 会询问你是否要信任远程主机(来自 Git 控制台):

$ ssh 127.0.0.1
The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
RSA key fingerprint is <FINGERPRINT>.
Are you sure you want to continue connecting (yes/no)?

If you trust the remote host (i.e. type yes), SSH will add its key to the list of known hosts.

如果您信任远程主机(即 type yes),SSH 会将其密钥添加到已知主机列表中。

After that, you should be able to do your git push origin.

之后,您应该可以执行您的git push origin.

As an alternative, you could also manually add the key of originto .ssh/known_hostsbut this requires that you adhere to the format of the known_hostsfile as described in the man page of sshd(Section AUTHORIZED_KEYS FILE FORMAT).

作为替代方案,您也可以手动添加originto的键,.ssh/known_hosts但这要求您遵守known_hosts手册页中描述的文件格式sshd(部分AUTHORIZED_KEYS FILE FORMAT)。

回答by Roman Starkov

For those of you who are setting up MSYS Git on Windows using PuTTY via the standard command prompt, the way to add a host to PuTTY's cache is to run

对于那些通过标准命令提示符使用 PuTTY 在 Windows 上设置 MSYS Git 的人,将主机添加到 PuTTY 缓存的方法是运行

> plink.exe <host>

For example:

例如:

> plink.exe codebasehq.com

The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 2e:db:b6:22:f7:bd:48:f6:da:72:bf:59:d7:75:d7:4e
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n)

Just answer y, and then Ctrl+C the rest.

只需回答y,然后 Ctrl+C 其余部分。

Do check the fingerprint though. This warning is there for a good reason. Fingerprints for some git services (please edit to add more):

不过还是要查指纹。这个警告是有充分理由的。一些 git 服务的指纹(请编辑以添加更多):

回答by Thijs

Try doing a "set | grep -i ssh" from the Git Bash prompt

尝试从 Git Bash 提示符执行“set | grep -i ssh”

If your setup is like mine you probably have these set:

如果你的设置和我的一样,你可能有这些设置:

GIT_SSH='C:\Program Files (x86)\PuTTY\plink.exe'
PLINK_PROTOCOL=ssh
SVN_SSH='"C:\Program Files (x86)\PuTTY\plink.exe"'

I did a

我做了一个

unset GIT_SSH
unset PLINK_PROTOCOL
unset GIT_SVN

and it worked after that,.. I guess putty saves its keys somewhere else as $HOME/.ssh or something... (I've also had a problem on a box where $HOME was set to "C:\Users\usrnam" instead of "/C/Users/usrnam/"

然后它就工作了,..我猜腻子将它的密钥保存在其他地方作为 $HOME/.ssh 或其他东西......(我在 $HOME 设置为“C:\Users\ usrnam" 而不是 "/C/Users/usrnam/"

anyway, your mileage may vary, but that fixed it for me. :-)

无论如何,您的里程可能会有所不同,但这对我来说是固定的。:-)

(probably just doing the unset GIT_SSH is enough, but I was on a roll)

(可能只是做未设置的 GIT_SSH 就足够了,但我很顺利)

Note: if unset doesn't work for you, try this:

注意:如果 unset 对你不起作用,试试这个:

set GIT_SSH=

回答by Gunee

I suspect that your GIT_SSHenvironment variable is set to %ProgramFiles(x86)%\putty\plink.exe. For some reason, PLink does not use the .ssh/known_hostsfile in your user directory to store the remote hosts keys.

我怀疑您的GIT_SSH环境变量设置为%ProgramFiles(x86)%\putty\plink.exe. 出于某种原因,PLink 不使用.ssh/known_hosts用户目录中的文件来存储远程主机密钥。

If this is actually your case, and it might be so on purpose if you want to use pageant, you need to use PLink to connect to the host first.

如果这确实是您的情况,并且如果您想使用选美比赛可能是故意的,您需要先使用 PLink 连接到主机。

"$GIT_SSH" user@hostname

You should get a similar message

你应该收到类似的消息

The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 86:7b:1b:12:85:35:8a:b7:98:b6:d2:97:5e:96:58:1d
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n)

Once you have answered yto the question and successfully connected to the remote host, you should be all set. Go ahead and try your push again.

一旦您回答y了问题并成功连接到远程主机,您就应该准备就绪。继续并再次尝试推动。

回答by andynormancx

Just ssh'ing to the host is not enough, on Windows at least. That adds the host key to ssh/known_hostsbut the error still persists.

至少在 Windows 上,仅仅通过 ssh 连接到主机是不够的。这将主机密钥添加到,ssh/known_hosts但错误仍然存​​在。

You need to close the git bash window and open a new one. Then the registry cache is cleared and the push/pull then works.

您需要关闭 git bash 窗口并打开一个新窗口。然后清除注册表缓存,然后推/拉工作。

回答by rezsa f

Rene, your HOMEvariable isn't set correctly. Either change it to c:\Users\(your-username)or just to %USERNAME%.

Rene,你的HOME变量设置不正确。将其更改为c:\Users\(your-username)或仅更改为%USERNAME%.

回答by Henrik

Solution with Plink

使用 Plink 解决方案

Save this python scriptto known_hosts.py:

将此python脚本保存到known_hosts.py

#! /usr/bin/env python

# $Id$
# Convert OpenSSH known_hosts and known_hosts2 files to "new format" PuTTY
# host keys.
#   usage:
#     kh2reg.py [ --win ] known_hosts1 2 3 4 ... > hosts.reg
#       Creates a Windows .REG file (double-click to install).
#     kh2reg.py --unix    known_hosts1 2 3 4 ... > sshhostkeys
#       Creates data suitable for storing in ~/.putty/sshhostkeys (Unix).
# Line endings are someone else's problem as is traditional.
# Developed for Python 1.5.2.

import fileinput
import base64
import struct
import string
import re
import sys
import getopt

def winmungestr(s):
    "Duplicate of PuTTY's mungestr() in winstore.c:1.10 for Registry keys"
    candot = 0
    r = ""
    for c in s:
        if c in ' \*?%~' or ord(c)<ord(' ') or (c == '.' and not candot):
            r = r + ("%%%02X" % ord(c))
        else:
            r = r + c
        candot = 1
    return r

def strtolong(s):
    "Convert arbitrary-length big-endian binary data to a Python long"
    bytes = struct.unpack(">%luB" % len(s), s)
    return reduce ((lambda a, b: (long(a) << 8) + long(b)), bytes)

def longtohex(n):
    """Convert long int to lower-case hex.

    Ick, Python (at least in 1.5.2) doesn't appear to have a way to
    turn a long int into an unadorned hex string -- % gets upset if the
    number is too big, and raw hex() uses uppercase (sometimes), and
    adds unwanted "0x...L" around it."""

    plain=string.lower(re.match(r"0x([0-9A-Fa-f]*)l?$", hex(n), re.I).group(1))
    return "0x" + plain

output_type = 'windows'

try:
    optlist, args = getopt.getopt(sys.argv[1:], '', [ 'win', 'unix' ])
    if filter(lambda x: x[0] == '--unix', optlist):
        output_type = 'unix'
except getopt.error, e:
    sys.stderr.write(str(e) + "\n")
    sys.exit(1)

if output_type == 'windows':
    # Output REG file header.
    sys.stdout.write("""REGEDIT4

[HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\SshHostKeys]
""")

# Now process all known_hosts input.
for line in fileinput.input(args):

    try:
        # Remove leading/trailing whitespace (should zap CR and LF)
        line = string.strip (line)

        # Skip blanks and comments
        if line == '' or line[0] == '#':
            raise "Skipping input line"

        # Split line on spaces.
        fields = string.split (line, ' ')

        # Common fields
        hostpat = fields[0]
        magicnumbers = []   # placeholder
        keytype = ""        # placeholder

        # Grotty heuristic to distinguish known_hosts from known_hosts2:
        # is second field entirely decimal digits?
        if re.match (r"\d*$", fields[1]):

            # Treat as SSH-1-type host key.
            # Format: hostpat bits10 exp10 mod10 comment...
            # (PuTTY doesn't store the number of bits.)
            magicnumbers = map (long, fields[2:4])
            keytype = "rsa"

        else:

            # Treat as SSH-2-type host key.
            # Format: hostpat keytype keyblob64 comment...
            sshkeytype, blob = fields[1], base64.decodestring (fields[2])

            # 'blob' consists of a number of
            #   uint32    N (big-endian)
            #   uint8[N]  field_data
            subfields = []
            while blob:
                sizefmt = ">L"
                (size,) = struct.unpack (sizefmt, blob[0:4])
                size = int(size)   # req'd for slicage
                (data,) = struct.unpack (">%lus" % size, blob[4:size+4])
                subfields.append(data)
                blob = blob [struct.calcsize(sizefmt) + size : ]

            # The first field is keytype again, and the rest we can treat as
            # an opaque list of bignums (same numbers and order as stored
            # by PuTTY). (currently embedded keytype is ignored entirely)
            magicnumbers = map (strtolong, subfields[1:])

            # Translate key type into something PuTTY can use.
            if   sshkeytype == "ssh-rsa":   keytype = "rsa2"
            elif sshkeytype == "ssh-dss":   keytype = "dss"
            else:
                raise "Unknown SSH key type", sshkeytype

        # Now print out one line per host pattern, discarding wildcards.
        for host in string.split (hostpat, ','):
            if re.search (r"[*?!]", host):
                sys.stderr.write("Skipping wildcard host pattern '%s'\n"
                                 % host)
                continue
            elif re.match (r"\|", host):
                sys.stderr.write("Skipping hashed hostname '%s'\n" % host)
                continue
            else:
                m = re.match (r"\[([^]]*)\]:(\d*)$", host)
                if m:
                    (host, port) = m.group(1,2)
                    port = int(port)
                else:
                    port = 22
                # Slightly bizarre output key format: 'type@port:hostname'
                # XXX: does PuTTY do anything useful with literal IP[v4]s?
                key = keytype + ("@%d:%s" % (port, host))
                value = string.join (map (longtohex, magicnumbers), ',')
                if output_type == 'unix':
                    # Unix format.
                    sys.stdout.write('%s %s\n' % (key, value))
                else:
                    # Windows format.
                    # XXX: worry about double quotes?
                    sys.stdout.write("\"%s\"=\"%s\"\n"
                                     % (winmungestr(key), value))

    except "Unknown SSH key type", k:
        sys.stderr.write("Unknown SSH key type '%s', skipping\n" % k)
    except "Skipping input line":
        pass

Tested on Win7x64 and Python 2.7.

在 Win7x64 和Python 2.7上测试。

Then run:

然后运行:

ssh-keyscan -t rsa bitbucket.org >>~/.ssh/known_hosts
python --win known_hosts.py >known_hosts.reg
start known_hosts.reg

And choose to import into the registry. The keyscan will retrieve the public key for the domain (I had my problems with bitbucket), and then the python script will convert it to Plink format.

并选择导入到注册表中。密钥扫描将检索域的公钥(我在使用 bitbucket 时遇到了问题),然后 Python 脚本会将其转换为 Plink 格式。

回答by Mateusz

Had the same issue, and forget to connect to SSH on port where is actuall repository, not just general SSH port, then the host key is different!

遇到了同样的问题,忘记在实际存储库所在的端口上连接到 SSH,而不仅仅是一般的 SSH 端口,那么主机密钥就不同了!

回答by sadegh saati

Just open Putty and try to establish connection to remote server you want to push your code. when the dialog appears press Yes(you trust remote) then everything would be OK.

只需打开 Putty 并尝试与要推送代码的远程服务器建立连接。当对话框出现时按是(你信任远程)然后一切都会好起来的。

回答by u5584387

Working environment:

工作环境:

  • Windows 10
  • git
  • putty
  • 视窗 10
  • 混帐
  • 油灰

First:Delete putty known_hosts in registy according to the Regedit.
Then:Executing the command %GIT_SSH% user@hostnamein Window's cmd solves the problem.

第一:根据Regedit删除registy中的putty known_hosts。
然后:%GIT_SSH% user@hostname在Window的cmd中执行命令即可解决问题。

Hope it helps you all.

希望对大家有帮助。