notes create windows git ssh putty plink

windows - notes - git create release



git-Clave de host del servidor no almacenada en caché (15)

Solución con Plink

Guarde este script de python en 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

Probado en Win7x64 y Python 2.7 .

Entonces corre:

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

Y elija importar en el registro. El keyscan recuperará la clave pública para el dominio (tuve mis problemas con bitbucket), y luego el script de python lo convertirá a formato Plink.

Intento impulsar los cambios de mi repositorio local a un repositorio remoto. Cuando escribo:

git push origin

Obtuve el siguiente 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

¿Como puedo resolver esto? Estoy usando git desde la línea de comandos en Windows 7.

Editar

Cuando trato de hacer un simple ssh

ssh user@hostname

Obtuve el siguiente error:

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

De alguna manera, no creará el directorio porque la ruta no es válida. ¿Cómo arreglar esto?

@eckes: Edit2

Mi casa está configurada en %HOMEDRIVE%%HOMEPATH% es correcto?


Agregar el host directamente con Bash no resolvió el problema, el error aún ocurría al usar ''Obtener todo'' en las extensiones de Git. Al usar ''Pull'' en una rama, las extensiones de Git agregaron automáticamente el host requerido con una pantalla emergente Bash. Después de hacer esto, pude usar ''Buscar todo'' nuevamente. No estoy seguro de qué es lo que hacen las extensiones de Git de manera diferente.


Cambiar de PuTTY a OpenSSH solucionó este problema para mí, sin tener que deshacer GIT_SSH, etc.


El mensaje significa que la clave de origin del host no está presente en su archivo de hosts de confianza.

Para evitar esto, abra una conexión SSH simple al origin y SSH le preguntará si desea confiar en el host remoto (desde la consola 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)?

Si confía en el host remoto (es decir, escriba yes ), SSH agregará su clave a la lista de hosts conocidos.

Después de eso, deberías poder hacer tu git push origin .

Como alternativa, también puede agregar manualmente la clave de origin a .ssh/known_hosts pero esto requiere que se adhiera al formato del archivo known_hosts como se describe en la página man de sshd (Sección AUTHORIZED_KEYS FILE FORMAT ).


He intentado todos los métodos anteriores, pero ninguno de ellos pudo solucionar el mismo problema en mi computadora portátil. Finalmente, en lugar de empujar la rama hacia el origen en git bash, trunco ​​para utilizar la opción de inserción de TortoiseGit para hacer el empuje, luego aparece una ventana emergente para pedirme que agregue la nueva clave de host a la memoria caché, luego de hacer clic en el botón bien ahora.

Espero que ayude a todos ustedes.


Intenta hacer un "set | grep -i ssh" desde el prompt de Git Bash

Si su configuración es como la mía, probablemente tenga estos conjuntos:

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

hice un

unset GIT_SSH unset PLINK_PROTOCOL unset GIT_SVN

y funcionó después de eso, supongo que Putty guarda sus claves en otro lugar como $ HOME / .ssh o algo así ... (También he tenido un problema en un cuadro donde $ HOME estaba configurado en "C: / Users /" usrnam "en lugar de" / C / Users / usrnam / "

de todos modos, su millaje puede variar, pero eso lo solucionó para mí. :-)

(Probablemente basta con deshacer GIT_SSH, pero estaba en una buena racha)

Nota: si unset no funciona para usted, intente esto:

set GIT_SSH=


Para aquellos de ustedes que están configurando MSYS Git en Windows usando PuTTY a través del símbolo del sistema estándar, la forma de agregar un host a la memoria caché de PuTTY es ejecutar

> plink.exe <host>

Por ejemplo:

> 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)

Simplemente responda y , y luego Ctrl + C el resto.

Sin embargo, verifique la huella digital. Esta advertencia está ahí por una buena razón. Huellas dactilares para algunos servicios de git (edite para agregar más):


René, tu variable HOME no está configurada correctamente. Cambie a c:/Users/(your-username) o simplemente a %USERNAME% .


Resolví un problema similar usando esta workaround .

Simplemente tiene que cambiar a Embedded Git, presione, presione el botón Sí y luego vuelva a System Git.

Puedes encontrar esta opción en

Tools -> Options -> Git


Simplemente abra Putty e intente establecer una conexión con el servidor remoto al que desea aplicar su código. cuando aparece el diálogo, presione Sí (confía en el control remoto), entonces todo estará bien.


Simplemente no es suficiente con el host, al menos en Windows. Eso agrega la clave de host a ssh/known_hosts pero el error aún persiste.

Debes cerrar la ventana de git bash y abrir una nueva. Luego se borra la caché de registro y luego funciona el push / pull.


Sospecho que su variable de entorno GIT_SSH se establece en %ProgramFiles(x86)%/putty/plink.exe . Por algún motivo, PLink no utiliza el archivo .ssh/known_hosts en su directorio de usuario para almacenar las claves de los hosts remotos.

Si este es realmente su caso, y puede ser a propósito si desea usar el concurso, primero necesita usar PLink para conectarse al servidor.

"$GIT_SSH" user@hostname

Deberías recibir un mensaje similar

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)

Una vez que haya respondido y a la pregunta y conectado exitosamente al host remoto, debe estar todo listo. Adelante, prueba tu empuje de nuevo.


Tuve el mismo problema, y ​​me olvidé de conectarme a SSH en el puerto donde está el repositorio actual , no solo en el puerto SSH general, ¡entonces la clave del host es diferente!


Yo también tuve el mismo problema cuando intentaba clonar un repositorio en mi máquina con Windows 7. Intenté la mayoría de las respuestas mencionadas aquí. Ninguno de ellos funcionó para mí.

Lo que funcionó para mí fue ejecutar el programa Pageant (agente de autenticación Putty). Una vez que el concurso se estaba ejecutando en segundo plano, pude clonar, empujar y tirar desde / hacia el repositorio. Esto funcionó para mí, puede ser porque he configurado mi clave pública de modo que cuando se utiliza por primera vez se requiere una contraseña y el concurso se inicia.


Ambiente de trabajo:

  • Windows 10
  • git
  • masilla

Primero: Eliminar masty known_hosts en registy según el Regedit.
Entonces: Ejecutar el comando %GIT_SSH% user@hostname en el cmd de Windows resuelve el problema.

Espero que les ayude a todos.