git-ключ хоста сервера не кэшируется
Я пытаюсь протолкнуть изменения из моего локального РЕПО в удаленное РЕПО. Когда я печатаю:
git push origin
Я получаю следующую ошибку:
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
Как я могу это решить? Я использую git из командной строки в Windows 7.
Edit
Когда я пытаюсь сделать простой ssh
ssh user@hostname
Я получаю следующую ошибку:
Could not create directory '/c//%HOMEDRIVE%%HOMEPATH%/.ssh'.
percent_expand: unknown key %H
Каким-то образом он не создаст каталог, потому что путь недопустим. Как это исправить?
@eckes: Edit2
Мой дом установлен to %HOMEDRIVE%%HOMEPATH% Правильно ли это?
15 ответов:
Сообщение означает, что ключ узла
originотсутствует в вашем файле trusted hosts.Чтобы обойти это, откройте простое 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)?Если Вы доверяете удаленному хосту (т. е. типу
yes), SSH добавит свой ключ в список известных хостов.После этого вы должны быть в состоянии сделать свой
git push origin.В качестве альтернативы можно также вручную добавить ключ
originно это требует, чтобы вы придерживались формата файлаknown_hosts, как описано в man-страницеsshd(раздел формат файла AUTHORIZED_KEYS ).
Для тех из вас, кто настраивает MSYS Git на Windows с помощью PuTTY через стандартную командную строку, способ добавить хост в кэш PuTTY-это запустить
> plink.exe <host>Например:
> 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)Просто ответьте
y, а затем Ctrl+C остальное.Все же проверьте отпечаток пальца. Это предупреждение существует по уважительной причине. Отпечатки пальцев для некоторых сервисов git (пожалуйста, отредактируйте, чтобы добавить больше):
Попробуйте выполнить "set | grep-i ssh" из командной строки Git Bash
Если ваша настройка похожа на мою, у вас, вероятно, есть следующие настройки:
GIT_SSH='C:\Program Files (x86)\PuTTY\plink.exe' PLINK_PROTOCOL=ssh SVN_SSH='"C:\\Program Files (x86)\\PuTTY\\plink.exe"'Я сделал
unset GIT_SSH unset PLINK_PROTOCOL unset GIT_SVNИ это сработало после этого,.. Я думаю, что putty сохраняет свои ключи где-то еще, как $HOME/.шшш или что-то вроде того... (У меня также была проблема с коробкой, где $HOME был установлен на "C:\Users\usrnam" вместо "/C / Users / usrnam/ "
В любом случае, ваш пробег может отличаться, но это исправило его для меня. :- )
(вероятно, просто делает unset GIT_SSH достаточно, но я был на рулоне)
Примечание: если unset не работает для вас, попробуйте следующее:
set GIT_SSH=
Я подозреваю, что ваша переменная окружения
GIT_SSHимеет значение%ProgramFiles(x86)%\putty\plink.exe. По какой-то причине PLink не использует файл.ssh/known_hostsв вашем пользовательском каталоге для хранения ключей удаленных хостов.Если это действительно ваш случай, и это может быть так нарочно, если вы хотите использовать pageant, вам нужно использовать PLink для подключения к хосту в первую очередь.
"$GIT_SSH" user@hostnameВы должны получить аналогичное сообщение
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)После того, как вы ответили на вопрос
yи успешно подключились к удаленному хосту, вы должно быть все готово. Продолжай и попробуй толкнуть еще раз.
Просто ssh-соединения с хостом недостаточно, по крайней мере в Windows. Это добавляет ключ хоста к
ssh/known_hosts, но ошибка все еще сохраняется.Вам нужно закрыть окно git bash и открыть новое. Затем кэш реестра очищается, и push/pull затем работает.
Рене, ваша переменная
HOMEустановлена неправильно. Либо измените его наc:\Users\(your-username), либо просто на%USERNAME%.
У
Была та же проблема, и забудьте подключиться к SSH на порту, где находится собственно репозиторий , а не только общий SSH-порт, тогда ключ хоста другой!
Рабочая среда:
- Windows 10
- git
- шпатлевка
Первый: Удалить putty known_hosts в Registry согласно Regedit.
затем: выполнение команды%GIT_SSH% user@hostnameв окне cmd решает проблему.Надеюсь, что это поможет вам всем.
Решение с Плинком
Сохраните этот скрипт 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Протестировано на Win7x64 иPython 2.7 .
Затем выполните:
ssh-keyscan -t rsa bitbucket.org >>~/.ssh/known_hosts python --win known_hosts.py >known_hosts.reg start known_hosts.regИ выберите Импорт в реестр. Keyscan извлекает открытый ключ для домена (у меня были проблемы с bitbucket), а затем скрипт python преобразует его в формат Plink.
У меня тоже была та же проблема, когда я пытался клонировать репозиторий на моей машине с Windows 7. Я попробовал большинство ответов, упомянутых здесь. Ни один из них не работал на меня.
Что меня устраивало, так это запуск программы Pageant (Putty authentication agent). Как только конкурс был запущен в фоновом режиме, я смог клонировать, нажимать и тянуть из/в хранилище. Это сработало для меня, может быть, потому, что я настроил свой открытый ключ таким образом, что всякий раз, когда он используется в первый раз пароль требуется & конкурс запускается.
Просто откройте Putty и попробуйте установить соединение с удаленным сервером, на который вы хотите отправить свой код. когда появится диалоговое окно, нажмите Yes (Вы доверяете remote), тогда все будет в порядке.
Я решил аналогичную задачу, используя этот обходной путь.
Вам просто нужно переключиться на встроенный Git, нажать, нажать кнопку Yes, а затем снова переключиться на System Git.Вы можете найти эту опцию в
Tools -> Options -> Git
Переход от PuTTY к OpenSSH исправил эту проблему для меня, без необходимости снимать git_ssh и т. д.
Добавление хоста непосредственно с Bash не решило проблему, ошибка все еще происходила при использовании 'Fetch all' в расширениях Git. При использовании "Pull" на одной ветке, необходимый хост был добавлен автоматически Git Extensions с всплывающим экраном Bash. После этого я смог снова использовать "Fetch All". Не уверен, что расширения Git делают по-другому.
Я перепробовал все методы выше, но ни один из них не мог исправить ту же проблему на моем ноутбуке. Наконец, вместо того, чтобы нажимать ветку в origin в git bash, я решил использовать опцию push TortoiseGit, чтобы сделать это, затем появляется окно с просьбой добавить новый ключ хоста в кэш, после нажатия кнопки yes, теперь все идет нормально.
Надеюсь, что это поможет вам всем.
Comments