Git clone fatal protocol error bad line length character

I set up a git server and want now to push initially my repo from the client. I used git push origin master and get this error message: fatal: protocol error: bad line length character: Unab I do...

I set up a git server and want now to push initially my repo from the client.
I used git push origin master and get this error message:

fatal: protocol error: bad line length character: Unab

I don’t know what’s wrong. I don’t know what «Unab» is. I tried to resize the shell but it is still «Unab».
I cannot find a solution for this error message.

I setup the server with «authorized_keys» and SSH. (I can connect to it, using SSH.)

It seems to be a git problem?

BTW: The server is set up in a Windows 7 VM

Tito's user avatar

Tito

8,78411 gold badges51 silver badges86 bronze badges

asked Nov 17, 2011 at 16:11

user437899's user avatar

2

This error message is a bit obtuse, but what it’s actually trying to tell you is that the remote server didn’t reply with a proper git response. Ultimately, there was a problem on the server running the git-receive-pack process.

In the Git protocol, the first four bytes should be the line length. Instead, they were the characters Unab… which is probably the beginning an error message of some kind. (ie, it’s probably «Unable to...» do something).

What happens when you run ssh <host> git-receive-pack <path-to-git-repository>? You should see the error message that your git client is barfing on and you may be able to correct it.

answered Nov 17, 2011 at 22:29

Edward Thomson's user avatar

Edward ThomsonEdward Thomson

72.5k14 gold badges156 silver badges183 bronze badges

19

I had similar issue, but the exact error message was:

fatal: protocol error: bad line length character: Usin

This is in Windows, with GIT_SSH set to the path of plink.exe of PuTTY.

Possible problems and solutions:

  • Make sure the path to plink.exe is correct. Unix style path works fine too, for example /c/work/tools/PuTTY/plink.exe
  • Make sure the key agent of PuTTY (pageant.exe) is running
  • Make sure the key agent contains a valid key to access the server

answered Mar 10, 2016 at 10:12

janos's user avatar

janosjanos

119k29 gold badges222 silver badges232 bronze badges

8

For GitExtension users:

I faced the same issue after upgrading git to 2.19.0

Solution:

Tools > Settings > Git Extensions > SSH

Select [OpenSSH] instead of [PuTTY]

enter image description here

answered Oct 1, 2018 at 6:58

Amit Shah's user avatar

Amit ShahAmit Shah

7,4935 gold badges39 silver badges52 bronze badges

1

I had the same kind of problem after installing GIT on Windows. At first it worked; then, a day later (after a PC reboot), it didn’t anymore, and I got this:

$ git pull
fatal: protocol error: bad line length character: git@

The problem was that after the reboot, the automatically started Putty «pageant.exe» didn’t have the private key active anymore. When you add a key in pageant, it’s not a persistent setting by default. I just had to add the key again, and it worked fine. So, for that case, it’s necessary to make pagenant load the key automatically, as discussed here:

https://www.digitalocean.com/community/tutorials/how-to-use-pageant-to-streamline-ssh-key-authentication-with-putty

answered Apr 11, 2017 at 11:40

MaeseDude's user avatar

MaeseDudeMaeseDude

4114 silver badges4 bronze badges

1

Maybe you have a statement in the server’s .bashrc that produces output. I, for example had this:

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"
rvm use ruby-1.9.3-p194@rails32

In this case the output from the rvm use will be (wrongly) interpreted as coming from git. So replace it by:

rvm use ruby-1.9.3-p194@rails32 > /dev/null

answered Jan 27, 2013 at 14:38

Christer Fernstrom's user avatar

2

After loading the SSH private key in Git Extensions, this issue gets resolved.

answered Dec 16, 2015 at 15:32

Stanley Emmanuel's user avatar

3

You can redirect any output from .bashrc to stderr:

# inside .bashrc
echo 'some error/warning/remind message' 1>&2

git will ignore this symbols

answered May 17, 2013 at 9:12

1

I had a similar problem on Windows using Git Bash. I kept getting this error when trying to do a git clone. The repository was on a Linux box with GitLab installed.

git clone git@servername:path/to/repo
fatal: protocol error: bad line length character: git@

I made sure the ssh key was generated. The public key was added on GitLab. The ssh-agent was running and the generated key was added (github link).

I ran out of options and then finally tried closing Git Bash and opening it again by right clicking ‘Run as Administrator’. Worked after that.

answered Nov 4, 2015 at 2:07

syclee's user avatar

sycleesyclee

6977 silver badges18 bronze badges

3

For me it was becuase I recently added

RequestTTY force

into .ssh/config

commenting this out allowed it to work

answered Jan 10, 2017 at 16:24

Thu 01 Jan 1970 000000 GMT's user avatar

1

This might help someone. When I was trying to clone a project from an EC2 instance, I was getting the below error:

Cloning into 'repo1'...
fatal: protocol error: bad line length character: logi

The resolution for me includes the below steps:

  1. Ensure SSH key (public) is added/updated in the EC2 instance.
  2. Ensure authentication agent (in my case its Pageant=Putty Authentication Agent) is running and the corresponding private key is loaded.
  3. Use the EC2 SSH key ID for the public key for git clone. Example:

    git clone ssh://{SSH Key ID}@someaccount.amazonaws.com/v1/repos/repo1

answered Jan 18, 2017 at 17:10

acveer's user avatar

acveeracveer

3701 gold badge4 silver badges10 bronze badges

3

In my case after fetch it was written: fatal: protocol error: bad line length character: Pass. Also after push I got: fatal: protocol error: bad line length character: git@
Done
.

After reboot of Windows I had to start «PuTTY agent» (pageant.exe) again and add a private key that disappeared from a list of keys.

answered Feb 5, 2018 at 8:16

CoolMind's user avatar

CoolMindCoolMind

25.3k14 gold badges179 silver badges214 bronze badges

If you use Putty. Then make sure to have Pageant running and your private key is loaded in Pageant (mouse right-click on Pageant icon on the Taskbar and click «View keys» on the menu that pops up).

Otherwise when you do in cmd.exe :

git clone ssh://name@host:/path/to/git/repo.git

you get this message «fatal: protocol error: bad line length character:»

answered Feb 21, 2019 at 11:00

Developer Marius Žilėnas's user avatar

1

Check your startup files on the account used to connect to the remote machine for «echo» statements. For the Bash shell these would be your .bashrc and .bash_profile etc. Edward Thomson is correct in his answer but a specific issue that I have experienced is when there is some boiler-plate printout upon login to a server via ssh. Git will get the first four bytes of that boiler-plate and raise this error. Now in this specific case I’m going to guess that «Unab» is actually the work «Unable…» which probably indicates that there is something else wrong on the Git host.

answered Jul 30, 2013 at 12:54

snarkyname77's user avatar

snarkyname77snarkyname77

1,1441 gold badge9 silver badges23 bronze badges

TL;DR: Do not omit username@ in your remote URLs when on Windows.

On Linux and on Windows with the default ssh, you can omit the username from remote URLs, like so:

git clone server-name:/srv/git/repo-name

Because ssh’s default behavior is to just use whatever username you’re currently logged in with. If you’re on Windows and have set up git to use plink.exe so that you can use the key loaded in your pageant, then this will not work, because plink does not have this same automatic username behavior, resulting in those cryptic error messages, because it will prompt for the username:

$ plink server-name
login as: _

Versus:

$ plink username@server-name
...logs you in...

If you already cloned a repository somehow you can fix the remotes in your .git/config by adding the username@ to the remote URL.

answered Jun 28, 2019 at 8:25

jlh's user avatar

jlhjlh

4,12039 silver badges44 bronze badges

1

i also encounter that error once in a while, but when it does, it means that my branch is not up-to-date so i have to do git pull origin <current_branch>

answered Jun 8, 2015 at 19:11

bonbon.langes's user avatar

bonbon.langesbonbon.langes

1,6812 gold badges22 silver badges36 bronze badges

FYI I got this same error message after I upgraded a CentOS6 container to CentOS7 — some git operations started failing when building the container, e.g.

# git remote show origin
fatal: protocol error: bad line length character: Inva

Running ssh gave me an error I could search on:

# ssh git@bitbucket.org
Invalid clock_id for clock_gettime: 7

That led me to https://github.com/wolfcw/libfaketime/issues/63 where I realized I had forgotten I had a LD_PRELOAD=/usr/local/lib/faketime/libfaketime.so.1 in a parent Dockerfile. Commenting that out fixed the error.

answered Aug 28, 2015 at 2:30

jamshid's user avatar

jamshidjamshid

1,75617 silver badges13 bronze badges

In my case the problem was 32-bit Putty and pageant.exe — it can’t communicate with 64-bit TortoisePlink.exe. Replacing 32-bit Putty with a 64-bit version solved the problem.

answered May 16, 2017 at 19:47

Nikolai Koudelia's user avatar

Nikolai KoudeliaNikolai Koudelia

2,4461 gold badge26 silver badges28 bronze badges

I had the same error "fatal: protocol error: bad line length character: shmi"
Where the shmi is user name in my case.
I switched SSH from PuTTY to OpenSSH in "Git Extensions->Settings->SSH".
It helped.

FMFF's user avatar

FMFF

1,6534 gold badges32 silver badges60 bronze badges

answered Oct 13, 2017 at 20:56

Val's user avatar

I had the same problem as Christer Fernstrom. In my case it was a message I had put in my .bashrc that reminds me do do a backup when I haven’t done one in a couple of days.

answered Apr 6, 2013 at 4:52

Christopher Vickery's user avatar

The following may help someone:
When trying to clone a project I have on my AWS EC2 instance I was getting the following error:

Cloning into 'AWSbareRepo'...
fatal: protocol error: bad line length character: Plea

This was caused by trying to ssh as root instead of EC2-USER.
if you actually ssh without doing a git clone… you will see the error msg in something along the lines of «Please login with ec2-user»
Once I did a git clone as a ec2-user it was good.

answered Apr 16, 2015 at 2:04

ConfusedDeer's user avatar

ConfusedDeerConfusedDeer

3,2757 gold badges42 silver badges69 bronze badges

For me adding the same host details into Putty with the private key (convert with puttygen) worked. Any git bash commands after that had no problems.

answered Sep 20, 2017 at 14:17

David Aleu's user avatar

David AleuDavid Aleu

3,8823 gold badges26 silver badges48 bronze badges

Had some similar issue but git fatal: protocol error: bad line length character: Cann and I was not able getting rid of it until I got rid of all the plink.exe dependency (have installed the Putty via choco installer) but also removed the next line from the .gitconfig file sshCommand = plink -batch.

answered Nov 2, 2021 at 14:28

Silviu's user avatar

SilviuSilviu

1031 silver badge7 bronze badges

1

Check if Shell access is allowed on the server.

answered Jan 27, 2012 at 18:54

perpetual_dream's user avatar

perpetual_dreamperpetual_dream

1,0365 gold badges18 silver badges51 bronze badges

1

The error transformed in:
fatal: protocol error: bad line length character: fata

after adding the location of git-upload-pack to the system path.

The problem seem to be an apostrophe added around the repository name: Looking with a tool like Process Monitor (from sys internals), that were added by the git client. It seems to be a git specific windows problem.

I tried the same command line in the prompt of the server: the full error was «fatal: not a given repository (or any of the parent directories): .git»

In conclusion, to me it seems like a software bug. Be advised that I am not a git expert, it is first time I use git, i come from subversion and perforce.

answered Dec 29, 2012 at 18:02

Razvan's user avatar

RazvanRazvan

1571 silver badge2 bronze badges

We ran into this as well.

Counting objects: 85, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (38/38), done.
Writing objects: 100% (38/38), 3.38 KiB | 0 bytes/s, done.
Total 38 (delta 33), reused 0 (delta 0)
Auto packing the repository for optimum performance.
fatal: protocol error: bad line length character: Remo
error: error in sideband demultiplexer

I don’t know the gitty details about what went wrong, but in our case what triggered it was that the disk on the server was full.

answered Dec 16, 2014 at 9:21

anr78's user avatar

anr78anr78

1,3082 gold badges16 silver badges31 bronze badges

It could be a security access on your machine, are you running Pageant (which is a putty agent)?

answered Apr 29, 2016 at 16:07

Kevin Davis's user avatar

Kevin DavisKevin Davis

3671 gold badge7 silver badges25 bronze badges

you can always have http link to your git project. You can use that instead of ssh link. This is just an option you have

answered Nov 25, 2016 at 6:39

Mohanakrrishna's user avatar

Well, I had this same issue (Windows 7). Try to get repo by password.
I use Git Bash + Plink (environment variable GIT_SSH) + Pageant.
Deleting GIT_SSH (temporary) helps me. I don’t know why I can’t use login by pass and login with RSA at the same time…

answered Dec 26, 2016 at 8:48

Philipp Klemeshov's user avatar

Late answer here, but hope it will help someone. If its a protocol error, it has to do something with your local git not able to communicate to the remote git. This can happen if you cloned the repo via ssh and sometime later, you lost the keys to the repo or your ssh agent cannot find those keys anymore.

Solution

  1. Generate a new key and add it your git repo or configure your ssh agent to load the keys if you still have the keys with you & not with someone else ;)

  2. Another quick fix is to go to your .git directory and edit the config file’s [remote "origin"] url from git to http so that ssh keys are not needed to push and it will revert to asking your username and password.

    [remote "origin"]
    url = git@gitlab.*****.com:****/****.git
    fetch = +refs/heads/*:refs/remotes/origin/*
    

Change to

    [remote "origin"]
    url = http://gitlab.*****.com/****/****.git
    fetch = +refs/heads/*:refs/remotes/origin/*

answered Jul 6, 2017 at 21:00

Tito's user avatar

TitoTito

8,78411 gold badges51 silver badges86 bronze badges

Содержание

  1. Bad line length character after updating to Sourcetree 3.4.8
  2. Git Remote: ошибка: фатальная: ошибка протокола: неверный символ длины строки: Unab
  3. 30 ответы

Bad line length character after updating to Sourcetree 3.4.8

i am experiencing an issue already discussed both here and on stackoverflow, concerning this error:

but most solutions suggest the problem lies in the server.

Thing is, this happens only on my desktop where i’ve updated to SourceTree 3.4.8; if i try to fetch/push from my laptop to the very same server it works just fine.
On my laptop i delayed the update, and still running SourceTree ver. 3.4.7.

As for the server address, which includes the 4 bytes of the error message reported above, it is in fact:

Pageant is running on the client, although there is no ssh key, since i am hosting the server in my house and there’s just a password auth for the user git_user .

I also tried removing the passwd file, to see if it was failing authentication, but pushing/fetching won’t even get to the authentication phase: i reckon the error happens before auth, since i’m not being asked to input the password again.

Aside from testing with both machines, with the same configuration, where one works and the other doesn’t, i’m quite stuck with troubleshooting. the only thing i could concieve was the version mismatch.
I should probably try to downgrade and see if it solves the issue.

Can anyone provide additional feedback?
Thanks

Источник

Git Remote: ошибка: фатальная: ошибка протокола: неверный символ длины строки: Unab

Я настроил сервер git и теперь хочу сначала отправить свое репо с клиента. я использовал git push origin master и получите это сообщение об ошибке:

Я не знаю, что случилось. Я не знаю, что такое «Унаб». Я попытался изменить размер оболочки, но она все еще «Unab». Я не могу найти решение для этого сообщения об ошибке.

Я настраиваю сервер с «authorized_keys» и SSH. (Я могу подключиться к нему, используя SSH.)

Вроде проблема с git?

Кстати: сервер настроен на виртуальной машине Windows 7

Была аналогичная проблема с «фатальной: ошибка протокола: неправильный символ длины строки: это», мое сообщение об ошибке было «Эта учетная запись в настоящее время недоступна». — hj’

30 ответы

Это сообщение об ошибке немного туповатое, но на самом деле оно пытается вам сказать, что удаленный сервер не ответил правильным ответом git. В конечном итоге возникла проблема на сервере, на котором запущен git-receive-pack процесс.

В протоколе Git первые четыре байта должны быть длиной строки. Вместо этого они были персонажами Unab . что, вероятно, является началом сообщения об ошибке. (т.е., вероятно, » Unable to. » сделай что-нибудь).

Что происходит, когда ты бежишь ssh git-receive-pack

? Вы должны увидеть сообщение об ошибке, с которым работает ваш git-клиент, и вы, возможно, сможете его исправить.

ответ дан 19 апр.

Это и ssh /bin/true не должен ничего выводить. — Стефан Нэве

У меня была такая же проблема, и причиной было «echo» .bashrc «» в моем .bashrc, поэтому вместо «фатальной: ошибка протокола: неправильная длина строки» символ: Unab «я видел» фатальная: ошибка протокола: неправильная длина строки персонаж: .bas «. — snarkyname77

Да, это тоже была моя проблема: моя .bashrc на машине, на которой размещался репозиторий Git, с которого я пытался извлечь, была строка, которая выдавала эхо на стандартный вывод. (То есть я был владельцем репозитория на удаленной машине, поэтому это был мой .bashrc это вызвало проблему.) Я использовал трюк, данный пользователем ruslo в другом ответе, а именно перенаправил вывод этой команды из stdout в stderr ( some_command 1>&2 ). После этого, git pull снова работал. — Теему Лейсти

С помощью приведенной выше команды вывод просто зависает. В нем перечислены все мои ветки, по одной в строке, а затем в последней напечатанной строке я получаю вывод 0000 и курсор сразу после этого, как если бы другая строка была записана, но никогда не завершается. — демонголем

Ненавижу сталкиваться с проблемой семилетней давности, но у меня та же проблема 0000 с git-receive-pack. Он зависает до тех пор, пока я не нажму четыре раза клавишу возврата, после чего он сообщает о той же ошибке протокола и завершает работу. — Марк Э. Гамильтон

У меня была аналогичная проблема, но точное сообщение об ошибке было:

фатальный: ошибка протокола: неправильная длина строки символ: Usin

Это в Windows, с GIT_SSH установить на путь plink.exe PuTTY.

Возможные проблемы и решения:

  • Убедитесь, что путь к plink.exe верно. Путь в стиле Unix тоже работает нормально, например /c/work/tools/PuTTY/plink.exe
  • Убедитесь, что ключевой агент PuTTY ( pageant.exe ) это работает
  • Убедитесь, что ключевой агент содержит действительный ключ для доступа к серверу.

ответ дан 10 мар ’16, в 10:03

У меня была такая же проблема в Windows, и она оказалась той же основной причиной по противоположной причине. Я пытался использовать Cygwin (и встроенный Git SSH), но GIT_SSH был установлен на C: . plink.exe, что вызывало конфликт. Как только я удалил это, все заработало. — Мэтт Хольцман

Удаление записи GIT_SSH из переменных среды помогло мне — Chamalabey

Похожая ошибка после обновления GitExt пришлось перезапустить pageant и повторно импортировать ключевой файл .ppk. — Билл Долан

Я просто забыл загрузить закрытый ключ на конкурсе, который закончился fatal: protocol error: bad line length character: git@ . Что за вводящее в заблуждение сообщение об ошибке. — Людвиг

В моем случае (Windows 10) конкурс не запускался. Как только я запустил его и добавил к нему закрытый ключ, это просто сработало. — april26

Я столкнулся с той же проблемой после обновления git до 2.19.0

Инструменты> Настройки> Расширения Git> SSH

Выбрать [OpenSSH] вместо того [PuTTY]

ответ дан 01 окт ’18, 07:10

Это именно то, что я сделал, когда вы получили сообщение об ошибке fatal: protocol error: bad line length character: git@ . Убедитесь, что ключ SSH сгенерирован и добавлен в GitLab. Возможно перезапуск Расширения Git было необходимо. — Тестирование

У меня была такая же проблема после установки GIT в Windows. Сначала это сработало; затем, через день (после перезагрузки ПК) этого больше не было, и я получил следующее:

Проблема заключалась в том, что после перезагрузки у автоматически запускаемого Putty «pageant.exe» больше не было активного закрытого ключа. Когда вы добавляете ключ в конкурс, это не постоянный параметр по умолчанию. Мне просто пришлось снова добавить ключ, и все заработало. Итак, в этом случае необходимо, чтобы pagenant загружал ключ автоматически, как описано здесь:

ответ дан 11 апр.

Для меня ситуация заключалась в том, что в Visual Studio я получал ошибку: «Git завершился с фатальной ошибкой. Ошибка протокола: неправильная длина строки, символ: gitu» каждый раз при перезапуске Windows. Процесс конкурса вообще не начался. Мне нужно было использовать, например, TortoiseGit, который решил эту проблему в фоновом режиме, а затем GIT работал в Visual Studio как шарм. — Хонза П.

Возможно, у вас есть оператор в серверном .bashrc, который производит вывод. У меня, например, было такое:

В этом случае результат использования rvm будет (ошибочно) интерпретирован как исходящий от git. Поэтому замените его на:

В моем случае (Windows 10) проблема заключалась в выводе некоторых команд, связанных с докером, в моем сценарии запуска cmd init.cmd (который я создал с помощью этих инструкций: stackoverflow.com/questions/17404165/…). но это тот же принцип. благодарю вас! — ЭТ-КС

Так было со мной. В моем .bashrc была команда «баннер». Комментирование устранило проблему. Спасибо :). — Джейми

После загрузки закрытого ключа SSH в Git Extensions эта проблема решена.

ответ дан 16 дек ’15, 15:12

для меня — добавление закрытого ключа ssh в конкурс — Ник Грили

Вы можете перенаправить любой вывод из .bashrc в stderr :

git проигнорирует эти символы

ответ дан 17 мая ’13, 10:05

Это сделало это для меня. У меня было заявление rvm use 2.0.0-p353 В моем .bashrc , который, должно быть, запутал git pull . После добавления 1>&2 и пытаюсь снова, git pull работал нормально. — Теему Лейсти

У меня была аналогичная проблема в Windows с использованием Git Bash. Я продолжал получать эту ошибку при попытке сделать клон git. Репозиторий находился в ящике Linux с установленным GitLab.

Я убедился, что ключ ssh был сгенерирован. Публичный ключ был добавлен на GitLab. Ssh-agent был запущен и сгенерированный ключ был добавлен (ссылка на github).

У меня закончились параметры, и я наконец попытался закрыть Git Bash и снова открыть его, щелкнув правой кнопкой мыши «Запуск от имени администратора». После этого работал.

Я вижу то же самое (10-разрядная версия Windows 64), но запуск от имени администратора не исправляет. — Эд Авис

У меня есть догадка о том, что вызывает это. Если у вас не настроена пара ключей ssh ​​(или она по какой-то причине не читается), тогда ssh запрашивает пароль. В Windows нет четкого различия между стандартным выводом и выводом на консоль, поэтому запрос пароля переходит к stdout: «git @ любой пароль:». Это рассматривается git как поврежденный вывод протокола. — Эд Авис

@EdAvis Спасибо! У меня была та же проблема, и после прочтения вашего комментария я дважды проверил свой ключевой агент (который обычно запускается при запуске на моей машине). Оказалось, что он почему-то не запускается . — Гриддо

Для меня это было потому, что я недавно добавил

комментирование этого позволило ему работать

И в моем случае я добавил LocalCommand config, чтобы что-то повторить — Фу Нго

Это может кому-то помочь. Когда я пытался клонировать проект из экземпляра EC2, я получал следующую ошибку:

Решение для меня включает следующие шаги:

  1. Убедитесь, что ключ SSH (открытый) добавлен / обновлен в экземпляре EC2.
  2. Убедитесь, что агент аутентификации (в моем случае его Pageant = Putty Authentication Agent) запущен и соответствующий закрытый ключ загружен.

Используйте идентификатор ключа SSH EC2 в качестве открытого ключа для git clone. Пример:

git clone ssh: // @someaccount.amazonaws.com/v1/repos/repo1

Примечание: это потому, что вы используете plink, и если вы это сделаете plink ls тогда первое, что выводит plink на стандартный вывод, это login as , который git пытается интерпретировать как нечто важное. Быстрое решение — просто unset GIT_SSH и unset SVN_SSH . Больше информации здесь — Стручок

@Pod, вы правы, в Windows эти команды должны помочь: set GIT_SSH= и set SVN_SSH= — Максим Костромин

У меня была такая же проблема с TFS. После добавления идентификатора ключа все работает нормально, спасибо! — Андре Хофмайстер

Проверьте файлы запуска в учетной записи, используемой для подключения к удаленному компьютеру, на наличие «эхо» операторов. Для оболочки Bash это будут ваши .bashrc и .bash_profile и т. Д. Эдвард Томсон прав в своем ответе, но конкретная проблема, с которой я столкнулся, — это когда при входе на сервер через ssh появляется распечатка шаблона. Git получит первые четыре байта этого шаблона и вызовет эту ошибку. Теперь в этом конкретном случае я собираюсь предположить, что «Unab» на самом деле является работой «Unable . », которая, вероятно, указывает на то, что на хосте Git что-то не так.

Создан 30 июля ’13, 13:07

В моем случае после загрузки было написано: fatal: protocol error: bad line length character: Pass . Также после толчка я получил: fatal: protocol error: bad line length character: git@ Done .

После перезагрузки Windows мне пришлось снова запустить «агент PuTTY» (pageant.exe) и добавить закрытый ключ, который исчез из списка ключей.

ответ дан 23 авг.

Если вы используете Putty. Затем убедитесь, что Pageant запущен и ваш закрытый ключ загружен в Pageant (щелкните правой кнопкой мыши значок Pageant на панели задач и выберите «Просмотреть ключи» в всплывающем меню).

В противном случае, когда вы делаете в cmd.exe:

git clone ssh://name@host:/path/to/git/repo.git

вы получите сообщение «фатальная: ошибка протокола: неверный символ длины строки:»

Я пришел к такому же выводу на ПК с Windows 10 с Visual Studio Code — PaulH

я также сталкиваюсь с этой ошибкой время от времени, но когда это происходит, это означает, что моя ветка не обновлена, поэтому мне нужно сделать git pull origin

К вашему сведению, я получил то же сообщение об ошибке после того, как обновил контейнер CentOS6 до CentOS7 — некоторые операции git начали давать сбой при создании контейнера, например

Запуск ssh дал мне ошибку, по которой я мог искать:

Это привело меня к https://github.com/wolfcw/libfaketime/issues/63 где я понял, что забыл, что у меня есть LD_PRELOAD=/usr/local/lib/faketime/libfaketime.so.1 в родительском Dockerfile. Комментируя это, вы исправили ошибку.

ответ дан 28 авг.

В моем случае проблема заключалась в 32-битных Putty и pageant.exe — он не может взаимодействовать с 64-битным TortoisePlink.exe. Замена 32-битной Putty на 64-битную версию решила проблему.

ответ дан 16 мая ’17, 20:05

У меня была такая же ошибка «fatal: protocol error: bad line length character: shmi» Где shmi это имя пользователя в моем случае. Я переключил SSH с PuTTY на OpenSSH в «Git Extensions->Settings->SSH» . Это помогло.

ответ дан 18 мая ’18, 00:05

TL; DR: Do не пропускать username@ в ваших удаленных URL-адресах в Windows.

В Linux и Windows с ssh по умолчанию вы можете опустить имя пользователя в удаленных URL-адресах, например:

Потому что по умолчанию ssh просто использует любое имя пользователя, с которым вы сейчас вошли в систему. Если вы работаете в Windows и настроили git для использования plink.exe так что вы можете использовать ключ, загруженный в ваш pageant , то это не сработает, потому что plink не имеет такого же автоматического поведения имени пользователя, что приводит к этим загадочным сообщениям об ошибках, потому что он запрашивает имя пользователя:

Если вы уже клонировали репозиторий каким-то образом, вы можете исправить пульты в своем .git/config добавив username@ на удаленный URL.

Источник

fatal: protocol error: bad line length character is an error I started seeing when trying to perform git clone, git fetch or git pull from public Git repositories hosted at git.wincent.com. I am not entirely sure when the problem started but I first noticed it after updating my local Git install to version 1.6.4 (see «Updating to Git 1.6.4»), with the server still running 1.6.3.3 (see «Updating to Git 1.6.3.3»).

Troubleshooting

First step, try using another version of Git to perform the clone. On the server itself:

$ git --version
git version 1.6.3.3
$ cd /tmp
$ git clone git://git.wincent.com/WOPublic.git
Initialized empty Git repository in /tmp/WOPublic/.git/
fatal: protocol error: bad line length character

So we know it’s not a conflict between 1.6.3.3 and 1.6.4. Could be a problem with the 1.6.3.3 server, so let’s update the server; see «Updating to Git 1.6.4» for the full details.

Now we repeat our server-side clone test:

$ git --version
git version 1.6.4
$ git clone git://git.wincent.com/WOPublic.git
Initialized empty Git repository in /tmp/WOPublic/.git/
fatal: protocol error: bad line length character

So back to the old drawing board… Try cloning from a different server:

$ git clone git://github.com/wincent/WOPublic.git
Initialized empty Git repository in /tmp/WOPublic/.git/
remote: Counting objects: 403, done.
remote: Compressing objects: 100% (218/218), done.
remote: Total 403 (delta 242), reused 297 (delta 172)
Receiving objects: 100% (403/403), 153.31 KiB, done.
Resolving deltas: 100% (242/242), done.

So we can see here that the problem is almost certainly not on the client side, regardless of whether the client is running 1.6.3.3 and 1.6.4. And we’ve also established that the problem on the server side was present in 1.6.3.3 just as it is in 1.6.4.

I wanted to see if this affected all repositories or just the one I was working with at that moment (WOPublic), but it turns out that the message is always the same, even for non-existent repos such as this fictional «xyz» one:

$ git clone git://git.wincent.com/xyz
Initialized empty Git repository in /private/tmp/xyz/.git/
fatal: protocol error: bad line length character

Looks like this is going to be hideously painful, but I am going to try and bisect it. I am not even sure what the last known «good» version was, so I guess I am going to go back through the «major» revisions (1.6.3, 1.6.2, 1.6.1) until I find one that works, then will run git bisect from there:

$ git co v1.6.3
$ make clean
$ NO_CURL=1 NO_EXPAT=1 NO_SVN_TESTS=1 NO_TCLTK=1 make test prefix=/usr/local
$ sudo -s
# NO_CURL=1 NO_EXPAT=1 NO_SVN_TESTS=1 NO_TCLTK=1 make prefix=/usr/local install

Ditto for:

  • v1.6.2 (broken)
  • v1.6.1 (works)

That’s a relief. We can start the real bisection:

$ git bisect start v1.6.2 v1.6.1
$ make clean
$ NO_CURL=1 NO_EXPAT=1 NO_SVN_TESTS=1 NO_TCLTK=1 make test prefix=/usr/local
$ sudo -s
# NO_CURL=1 NO_EXPAT=1 NO_SVN_TESTS=1 NO_TCLTK=1 make prefix=/usr/local install
# exit

And then git bisect good or git bisect bad, depending on the result and repeat…

Ultimately, we bisect down to this:

8e3462837b0ace04357503a3f58802cc2231df29 is first bad commit
commit 8e3462837b0ace04357503a3f58802cc2231df29
Author: Steffen Prohaska <prohaska@zib.de>
Date:   Sun Jan 18 13:00:13 2009 +0100

    Modify setup_path() to only add git_exec_path() to PATH

    Searching git programs only in the highest priority location is
    sufficient.  It does not make sense that some of the required
    programs are located at the highest priority location but other
    programs are picked up from a lower priority exec-path.  If
    exec-path is overridden a complete set of commands should be
    provided, otherwise several different versions could get mixed,
    which is likely to cause confusion.

    If a user explicitly overrides the default location (by --exec-path
    or GIT_EXEC_PATH), we now expect that all the required programs are
    found there.  Instead of adding the directories "argv_exec_path",
    "getenv(EXEC_PATH_ENVIRONMENT)", and "system_path(GIT_EXEC_PATH)"
    to PATH, we now rely on git_exec_path(), which implements the same
    order, but only returns the highest priority location to search for
    executables.

    Accessing only the location with highest priority is also required
    for testing executables built with RUNTIME_PREFIX.  The call to
    system_path() should be avoided if RUNTIME_PREFIX is set and the
    executable is not installed at its final destination.  Because we
    test before installing, we want to avoid calling system_path()
    during tests.  The modifications in this commit avoid calling
    system_path(GIT_EXEC_PATH) if a higher-priority location is
    provided, which is the case when running the tests.

    Signed-off-by: Steffen Prohaska <prohaska@zib.de>
    Acked-by: Johannes Sixt <j6t@kdbg.org>
    Signed-off-by: Junio C Hamano <gitster@pobox.com>

This is on a server with Git installed using prefix=/usr/local, but /usr/local/bin is not in the default PATH so the daemon is launched via xinetd with the following settings in /etc/xinetd.d/git:

  • server is explicitly set to the absolute path, /usr/local/bin/git
  • in server_args, we pass --exec-path=/usr/local/bin daemon --inetd etc

The key paragraph in the commit message for 8e34628 sheds light on what’s happening here:

   If a user explicitly overrides the default location (by --exec-path
   or GIT_EXEC_PATH), we now expect that all the required programs are
   found there.  Instead of adding the directories "argv_exec_path",
   "getenv(EXEC_PATH_ENVIRONMENT)", and "system_path(GIT_EXEC_PATH)"
   to PATH, we now rely on git_exec_path(), which implements the same
   order, but only returns the highest priority location to search for
   executables.

So, dropped the explicit --exec-path from the server_args and the bad line length character errors go away. The git executable is obviously smart enough to know where the needed binaries are (currently /usr/local/libexec/git-core) and so doesn’t need the explicit parameter; and in fact, it was something that I only ever added in the first place to fix breakage caused by changes to where the binaries were stored and how they were searched for (see «Upgrading to Git 1.5.4»).

See also

  • Entry on the official Git FAQ for the protocol error: bad line length character message (not really helpful/applicable to this specific case as it applies to SSH-based access and I am talking about anonymous public access using the Git protocol): http://git.or.cz/gitwiki/GitFaq#protocolerror.3Abadlinelengthcharacter
  • Mailing list thread: http://kerneltrap.org/mailarchive/git/2007/1/20/236259
  • Google search for ‘»protocol error: bad line length character» git’ (currently 209 results at time of writing)

Я настроил сервер git и теперь хочу сначала отправить свое репо с клиента. я использовал git push origin master и получите это сообщение об ошибке:

fatal: protocol error: bad line length character: Unab

Я не знаю, что случилось. Я не знаю, что такое «Унаб». Я попытался изменить размер оболочки, но она все еще «Unab». Я не могу найти решение для этого сообщения об ошибке.

Я настраиваю сервер с «authorized_keys» и SSH. (Я могу подключиться к нему, используя SSH.)

Вроде проблема с git?

Кстати: сервер настроен на виртуальной машине Windows 7

30 ответы

Это сообщение об ошибке немного туповатое, но на самом деле оно пытается вам сказать, что удаленный сервер не ответил правильным ответом git. В конечном итоге возникла проблема на сервере, на котором запущен git-receive-pack процесс.

В протоколе Git первые четыре байта должны быть длиной строки. Вместо этого они были персонажами Unab… что, вероятно, является началом сообщения об ошибке. (т.е., вероятно, «Unable to...» сделай что-нибудь).

Что происходит, когда ты бежишь ssh <host> git-receive-pack <path-to-git-repository>? Вы должны увидеть сообщение об ошибке, с которым работает ваш git-клиент, и вы, возможно, сможете его исправить.

ответ дан 19 апр.

У меня была аналогичная проблема, но точное сообщение об ошибке было:

фатальный: ошибка протокола: неправильная длина строки символ: Usin

Это в Windows, с GIT_SSH установить на путь plink.exe PuTTY.

Возможные проблемы и решения:

  • Убедитесь, что путь к plink.exe верно. Путь в стиле Unix тоже работает нормально, например /c/work/tools/PuTTY/plink.exe
  • Убедитесь, что ключевой агент PuTTY (pageant.exe) это работает
  • Убедитесь, что ключевой агент содержит действительный ключ для доступа к серверу.

ответ дан 10 мар ’16, в 10:03

Для пользователей GitExtension:

Я столкнулся с той же проблемой после обновления git до 2.19.0

Решение:

Инструменты> Настройки> Расширения Git> SSH

Выбрать [OpenSSH] вместо того [PuTTY]

Введите описание изображения здесь

ответ дан 01 окт ’18, 07:10

У меня была такая же проблема после установки GIT в Windows. Сначала это сработало; затем, через день (после перезагрузки ПК) этого больше не было, и я получил следующее:

$ git pull
fatal: protocol error: bad line length character: git@

Проблема заключалась в том, что после перезагрузки у автоматически запускаемого Putty «pageant.exe» больше не было активного закрытого ключа. Когда вы добавляете ключ в конкурс, это не постоянный параметр по умолчанию. Мне просто пришлось снова добавить ключ, и все заработало. Итак, в этом случае необходимо, чтобы pagenant загружал ключ автоматически, как описано здесь:

https://www.digitalocean.com/community/tutorials/how-to-use-pageant-to-streamline-ssh-key-authentication-with-putty

ответ дан 11 апр.

Возможно, у вас есть оператор в серверном .bashrc, который производит вывод. У меня, например, было такое:

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"
rvm use ruby-1.9.3-p194@rails32

В этом случае результат использования rvm будет (ошибочно) интерпретирован как исходящий от git. Поэтому замените его на:

rvm use ruby-1.9.3-p194@rails32 > /dev/null

Создан 27 янв.

После загрузки закрытого ключа SSH в Git Extensions эта проблема решена.

ответ дан 16 дек ’15, 15:12

Вы можете перенаправить любой вывод из .bashrc в stderr:

# inside .bashrc
echo 'some error/warning/remind message' 1>&2

git проигнорирует эти символы

ответ дан 17 мая ’13, 10:05

У меня была аналогичная проблема в Windows с использованием Git Bash. Я продолжал получать эту ошибку при попытке сделать клон git. Репозиторий находился в ящике Linux с установленным GitLab.

git clone git@servername:path/to/repo
fatal: protocol error: bad line length character: git@

Я убедился, что ключ ssh был сгенерирован. Публичный ключ был добавлен на GitLab. Ssh-agent был запущен и сгенерированный ключ был добавлен (ссылка на github).

У меня закончились параметры, и я наконец попытался закрыть Git Bash и снова открыть его, щелкнув правой кнопкой мыши «Запуск от имени администратора». После этого работал.

Создан 04 ноя.

Для меня это было потому, что я недавно добавил

RequestTTY force

в .ssh / config

комментирование этого позволило ему работать

Создан 10 янв.

Это может кому-то помочь. Когда я пытался клонировать проект из экземпляра EC2, я получал следующую ошибку:

Cloning into 'repo1'...
fatal: protocol error: bad line length character: logi

Решение для меня включает следующие шаги:

  1. Убедитесь, что ключ SSH (открытый) добавлен / обновлен в экземпляре EC2.
  2. Убедитесь, что агент аутентификации (в моем случае его Pageant = Putty Authentication Agent) запущен и соответствующий закрытый ключ загружен.
  3. Используйте идентификатор ключа SSH EC2 в качестве открытого ключа для git clone. Пример:

    git clone ssh: // {ID ключа SSH}@someaccount.amazonaws.com/v1/repos/repo1

Создан 18 янв.

Проверьте файлы запуска в учетной записи, используемой для подключения к удаленному компьютеру, на наличие «эхо» операторов. Для оболочки Bash это будут ваши .bashrc и .bash_profile и т. Д. Эдвард Томсон прав в своем ответе, но конкретная проблема, с которой я столкнулся, — это когда при входе на сервер через ssh появляется распечатка шаблона. Git получит первые четыре байта этого шаблона и вызовет эту ошибку. Теперь в этом конкретном случае я собираюсь предположить, что «Unab» на самом деле является работой «Unable …», которая, вероятно, указывает на то, что на хосте Git что-то не так.

Создан 30 июля ’13, 13:07

В моем случае после загрузки было написано: fatal: protocol error: bad line length character: Pass. Также после толчка я получил: fatal: protocol error: bad line length character: git@
Done
.

После перезагрузки Windows мне пришлось снова запустить «агент PuTTY» (pageant.exe) и добавить закрытый ключ, который исчез из списка ключей.

ответ дан 23 авг.

Если вы используете Putty. Затем убедитесь, что Pageant запущен и ваш закрытый ключ загружен в Pageant (щелкните правой кнопкой мыши значок Pageant на панели задач и выберите «Просмотреть ключи» в всплывающем меню).

В противном случае, когда вы делаете в cmd.exe:

git clone ssh://name@host:/path/to/git/repo.git

вы получите сообщение «фатальная: ошибка протокола: неверный символ длины строки:»

Создан 21 фев.

я также сталкиваюсь с этой ошибкой время от времени, но когда это происходит, это означает, что моя ветка не обновлена, поэтому мне нужно сделать git pull origin <current_branch>

Создан 08 июн.

К вашему сведению, я получил то же сообщение об ошибке после того, как обновил контейнер CentOS6 до CentOS7 — некоторые операции git начали давать сбой при создании контейнера, например

# git remote show origin
fatal: protocol error: bad line length character: Inva

Запуск ssh дал мне ошибку, по которой я мог искать:

# ssh git@bitbucket.org
Invalid clock_id for clock_gettime: 7

Это привело меня к https://github.com/wolfcw/libfaketime/issues/63 где я понял, что забыл, что у меня есть LD_PRELOAD=/usr/local/lib/faketime/libfaketime.so.1 в родительском Dockerfile. Комментируя это, вы исправили ошибку.

ответ дан 28 авг.

В моем случае проблема заключалась в 32-битных Putty и pageant.exe — он не может взаимодействовать с 64-битным TortoisePlink.exe. Замена 32-битной Putty на 64-битную версию решила проблему.

ответ дан 16 мая ’17, 20:05

У меня была такая же ошибка "fatal: protocol error: bad line length character: shmi"
Где shmi это имя пользователя в моем случае. Я переключил SSH с PuTTY на OpenSSH в "Git Extensions->Settings->SSH". Это помогло.

ответ дан 18 мая ’18, 00:05

TL; DR: Do не пропускать username@ в ваших удаленных URL-адресах в Windows.

В Linux и Windows с ssh по умолчанию вы можете опустить имя пользователя в удаленных URL-адресах, например:

git clone server-name:/srv/git/repo-name

Потому что по умолчанию ssh просто использует любое имя пользователя, с которым вы сейчас вошли в систему. Если вы работаете в Windows и настроили git для использования plink.exe так что вы можете использовать ключ, загруженный в ваш pageant, то это не сработает, потому что plink не имеет такого же автоматического поведения имени пользователя, что приводит к этим загадочным сообщениям об ошибках, потому что он запрашивает имя пользователя:

$ plink server-name
login as: _

Против:

$ plink username@server-name
...logs you in...

Если вы уже клонировали репозиторий каким-то образом, вы можете исправить пульты в своем .git/config добавив username@ на удаленный URL.

Создан 28 июн.

У меня была та же проблема, что и у Кристера Фернстрома. В моем случае это было сообщение, которое я поместил в свой .bashrc, которое напоминает мне, что нужно делать резервную копию, если я не делал ее в течение нескольких дней.

ответ дан 06 апр.

Кому-то может помочь следующее: при попытке клонировать проект, который у меня есть на моем экземпляре AWS EC2, я получал следующую ошибку:

Cloning into 'AWSbareRepo'...
fatal: protocol error: bad line length character: Plea

Это было вызвано попыткой использовать ssh как root вместо EC2-USER. если вы на самом деле ssh, не выполняя клон git … вы увидите сообщение об ошибке примерно в строках «Пожалуйста, войдите с пользователем ec2». Как только я сделал клон git как пользователь ec2, это было хорошо.

ответ дан 16 апр.

Создан 15 июн.

Для меня сработало добавление тех же деталей хоста в Putty с закрытым ключом (преобразование с помощью puttygen). Любые команды git bash после этого не имели проблем.

Создан 20 сен.

Проверьте, разрешен ли доступ к Shell на сервере.

Создан 27 янв.

Ошибка трансформировалась в: фатальная: ошибка протокола: неверный символ длины строки: fata

после добавления местоположения git-upload-pack в системный путь.

Проблема, похоже, заключается в добавлении апострофа вокруг имени репозитория: поиск с помощью такого инструмента, как Process Monitor (из внутренних компонентов sys), который был добавлен клиентом git. Кажется, это проблема с окнами git.

Я попробовал ту же командную строку в приглашении сервера: полная ошибка была «фатальной: не данный репозиторий (или любой из родительских каталогов): .git»

В заключение, мне кажется, что это программная ошибка. Имейте в виду, что я не эксперт по git, это первый раз, когда я использую git, я пришел из подрывной деятельности и по волеизъявлению.

ответ дан 29 дек ’12, 18:12

Мы тоже столкнулись с этим.

Counting objects: 85, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (38/38), done.
Writing objects: 100% (38/38), 3.38 KiB | 0 bytes/s, done.
Total 38 (delta 33), reused 0 (delta 0)
Auto packing the repository for optimum performance.
fatal: protocol error: bad line length character: Remo
error: error in sideband demultiplexer

Я не знаю подробностей о том, что пошло не так, но в нашем случае это вызвало то, что диск на сервере был заполнен.

ответ дан 16 дек ’14, 09:12

Это может быть безопасный доступ на вашем компьютере, вы используете Pageant (который является агентом замазки)?

ответ дан 29 апр.

у вас всегда может быть http-ссылка на ваш проект git. Вы можете использовать это вместо ссылки ssh. Это просто вариант, который у вас есть

Создан 25 ноя.

Ну, у меня была такая же проблема (Windows 7). Попробуйте получить репо по паролю. Я использую Git Bash + Plink (переменная окружения GIT_SSH) + Pageant. Мне помогает удаление GIT_SSH (временного). Я не знаю, почему я не могу использовать вход по проходу и вход через RSA одновременно …

ответ дан 26 дек ’16, 08:12

Поздний ответ здесь, но надеюсь, что это кому-то поможет. Если это ошибка протокола, он должен что-то делать с вашим локальным git, который не может связаться с удаленным git. Это может произойти, если вы клонировали репо через ssh, а когда-то позже вы потеряли ключи репо или ваш агент ssh больше не может найти эти ключи.

Решения

  1. Сгенерируйте новый ключ и добавьте его в репозиторий git или настройте свой ssh-агент для загрузки ключей, если у вас все еще есть ключи с вами, а не с кем-то еще;)

  2. Еще одно быстрое решение — перейти к вашему .git каталог и отредактируйте config файл [remote "origin"] url от git в http так что ключи ssh не нужны, и он вернется к запросу вашего имени пользователя и пароля.

    [remote "origin"]
    url = git@gitlab.*****.com:****/****.git
    fetch = +refs/heads/*:refs/remotes/origin/*
    

Изменения в

    [remote "origin"]
    url = http://gitlab.*****.com/****/****.git
    fetch = +refs/heads/*:refs/remotes/origin/*

Создан 06 июля ’17, 22:07

Изменение исполняемого файла ssh со встроенного на nativ в settings / version control / git помогло мне.

Создан 18 июля ’18, 13:07

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

git
ssh
authorized-keys

or задайте свой вопрос.

I set up a git server and want now to push initially my repo from the client.
I used git push origin master and get this error message:

fatal: protocol error: bad line length character: Unab

I don’t know what’s wrong. I don’t know what «Unab» is. I tried to resize the shell but it is still «Unab».
I cannot find a solution for this error message.

I setup the server with «authorized_keys» and SSH. (I can connect to it, using SSH.)

It seems to be a git problem?

BTW: The server is set up in a Windows 7 VM

30 Answers

This error message is a bit obtuse, but what it’s actually trying to tell you is that the remote server didn’t reply with a proper git response. Ultimately, there was a problem on the server running the git-receive-pack process.

In the Git protocol, the first four bytes should be the line length. Instead, they were the characters Unab… which is probably the beginning an error message of some kind. (ie, it’s probably «Unable to...» do something).

What happens when you run ssh <host> git-receive-pack <path-to-git-repository>? You should see the error message that your git client is barfing on and you may be able to correct it.

I had similar issue, but the exact error message was:

fatal: protocol error: bad line length character: Usin

This is in Windows, with GIT_SSH set to the path of plink.exe of PuTTY.

Possible problems and solutions:

  • Make sure the path to plink.exe is correct. Unix style path works fine too, for example /c/work/tools/PuTTY/plink.exe
  • Make sure the key agent of PuTTY (pageant.exe) is running
  • Make sure the key agent contains a valid key to access the server

For GitExtension users:

I faced the same issue after upgrading git to 2.19.0

Solution:

Tools > Settings > Git Extensions > SSH

Select [OpenSSH] instead of [PuTTY]

enter image description here

I had the same kind of problem after installing GIT on Windows. At first it worked; then, a day later (after a PC reboot), it didn’t anymore, and I got this:

$ git pull
fatal: protocol error: bad line length character: [email protected]

The problem was that after the reboot, the automatically started Putty «pageant.exe» didn’t have the private key active anymore. When you add a key in pageant, it’s not a persistent setting by default. I just had to add the key again, and it worked fine. So, for that case, it’s necessary to make pagenant load the key automatically, as discussed here:

https://www.digitalocean.com/community/tutorials/how-to-use-pageant-to-streamline-ssh-key-authentication-with-putty

Maybe you have a statement in the server’s .bashrc that produces output. I, for example had this:

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"
rvm use [email protected]

In this case the output from the rvm use will be (wrongly) interpreted as coming from git. So replace it by:

rvm use [email protected] > /dev/null

After loading the SSH private key in Git Extensions, this issue gets resolved.

You can redirect any output from .bashrc to stderr:

# inside .bashrc
echo 'some error/warning/remind message' 1>&2

git will ignore this symbols

I had a similar problem on Windows using Git Bash. I kept getting this error when trying to do a git clone. The repository was on a Linux box with GitLab installed.

git clone [email protected]:path/to/repo
fatal: protocol error: bad line length character: [email protected]

I made sure the ssh key was generated. The public key was added on GitLab. The ssh-agent was running and the generated key was added (github link).

I ran out of options and then finally tried closing Git Bash and opening it again by right clicking ‘Run as Administrator’. Worked after that.

For me it was becuase I recently added

RequestTTY force

into .ssh/config

commenting this out allowed it to work

This might help someone. When I was trying to clone a project from an EC2 instance, I was getting the below error:

Cloning into 'repo1'...
fatal: protocol error: bad line length character: logi

The resolution for me includes the below steps:

  1. Ensure SSH key (public) is added/updated in the EC2 instance.
  2. Ensure authentication agent (in my case its Pageant=Putty Authentication Agent) is running and the corresponding private key is loaded.
  3. Use the EC2 SSH key ID for the public key for git clone. Example:

    git clone ssh://{SSH Key ID}@someaccount.amazonaws.com/v1/repos/repo1

Check your startup files on the account used to connect to the remote machine for «echo» statements. For the Bash shell these would be your .bashrc and .bash_profile etc. Edward Thomson is correct in his answer but a specific issue that I have experienced is when there is some boiler-plate printout upon login to a server via ssh. Git will get the first four bytes of that boiler-plate and raise this error. Now in this specific case I’m going to guess that «Unab» is actually the work «Unable…» which probably indicates that there is something else wrong on the Git host.

In my case after fetch it was written: fatal: protocol error: bad line length character: Pass. Also after push I got: fatal: protocol error: bad line length character: [email protected]
Done
.

After reboot of Windows I had to start «PuTTY agent» (pageant.exe) again and add a private key that disappeared from a list of keys.

If you use Putty. Then make sure to have Pageant running and your private key is loaded in Pageant (mouse right-click on Pageant icon on the Taskbar and click «View keys» on the menu that pops up).

Otherwise when you do in cmd.exe :

git clone ssh://[email protected]:/path/to/git/repo.git

you get this message «fatal: protocol error: bad line length character:»

i also encounter that error once in a while, but when it does, it means that my branch is not up-to-date so i have to do git pull origin <current_branch>

FYI I got this same error message after I upgraded a CentOS6 container to CentOS7 — some git operations started failing when building the container, e.g.

# git remote show origin
fatal: protocol error: bad line length character: Inva

Running ssh gave me an error I could search on:

# ssh [email protected]
Invalid clock_id for clock_gettime: 7

That led me to https://github.com/wolfcw/libfaketime/issues/63 where I realized I had forgotten I had a LD_PRELOAD=/usr/local/lib/faketime/libfaketime.so.1 in a parent Dockerfile. Commenting that out fixed the error.

In my case the problem was 32-bit Putty and pageant.exe — it can’t communicate with 64-bit TortoisePlink.exe. Replacing 32-bit Putty with a 64-bit version solved the problem.

I had the same error "fatal: protocol error: bad line length character: shmi"
Where the shmi is user name in my case.
I switched SSH from PuTTY to OpenSSH in "Git Extensions->Settings->SSH".
It helped.

I had the same problem as Christer Fernstrom. In my case it was a message I had put in my .bashrc that reminds me do do a backup when I haven’t done one in a couple of days.

The following may help someone:
When trying to clone a project I have on my AWS EC2 instance I was getting the following error:

Cloning into 'AWSbareRepo'...
fatal: protocol error: bad line length character: Plea

This was caused by trying to ssh as root instead of EC2-USER.
if you actually ssh without doing a git clone… you will see the error msg in something along the lines of «Please login with ec2-user»
Once I did a git clone as a ec2-user it was good.

For me adding the same host details into Putty with the private key (convert with puttygen) worked. Any git bash commands after that had no problems.

TL;DR: Do not omit [email protected] in your remote URLs when on Windows.

On Linux and on Windows with the default ssh, you can omit the username from remote URLs, like so:

git clone server-name:/srv/git/repo-name

Because ssh’s default behavior is to just use whatever username you’re currently logged in with. If you’re on Windows and have set up git to use plink.exe so that you can use the key loaded in your pageant, then this will not work, because plink does not have this same automatic username behavior, resulting in those cryptic error messages, because it will prompt for the username:

$ plink server-name
login as: _

Versus:

$ plink [email protected]
...logs you in...

If you already cloned a repository somehow you can fix the remotes in your .git/config by adding the [email protected] to the remote URL.

Check if Shell access is allowed on the server.

The error transformed in:
fatal: protocol error: bad line length character: fata

after adding the location of git-upload-pack to the system path.

The problem seem to be an apostrophe added around the repository name: Looking with a tool like Process Monitor (from sys internals), that were added by the git client. It seems to be a git specific windows problem.

I tried the same command line in the prompt of the server: the full error was «fatal: not a given repository (or any of the parent directories): .git»

In conclusion, to me it seems like a software bug. Be advised that I am not a git expert, it is first time I use git, i come from subversion and perforce.

We ran into this as well.

Counting objects: 85, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (38/38), done.
Writing objects: 100% (38/38), 3.38 KiB | 0 bytes/s, done.
Total 38 (delta 33), reused 0 (delta 0)
Auto packing the repository for optimum performance.
fatal: protocol error: bad line length character: Remo
error: error in sideband demultiplexer

I don’t know the gitty details about what went wrong, but in our case what triggered it was that the disk on the server was full.

It could be a security access on your machine, are you running Pageant (which is a putty agent)?

you can always have http link to your git project. You can use that instead of ssh link. This is just an option you have

Well, I had this same issue (Windows 7). Try to get repo by password.
I use Git Bash + Plink (environment variable GIT_SSH) + Pageant.
Deleting GIT_SSH (temporary) helps me. I don’t know why I can’t use login by pass and login with RSA at the same time…

Late answer here, but hope it will help someone. If its a protocol error, it has to do something with your local git not able to communicate to the remote git. This can happen if you cloned the repo via ssh and sometime later, you lost the keys to the repo or your ssh agent cannot find those keys anymore.

Solution

  1. Generate a new key and add it your git repo or configure your ssh agent to load the keys if you still have the keys with you & not with someone else ;)

  2. Another quick fix is to go to your .git directory and edit the config file’s [remote "origin"] url from git to http so that ssh keys are not needed to push and it will revert to asking your username and password.

    [remote "origin"]
    url = [email protected]*****.com:****/****.git
    fetch = +refs/heads/*:refs/remotes/origin/*
    

Change to

    [remote "origin"]
    url = http://gitlab.*****.com/****/****.git
    fetch = +refs/heads/*:refs/remotes/origin/*

Changing the ssh exectuable from builtin to nativ under settings/version control/git did the trick for me.

#git #ssh #gitlab

# #git #ssh #gitlab

Вопрос:

При попытке клонирования с использованием SSH URL мы получаем следующую ошибку:

 $ git clone git@host:repository.git
Cloning into 'test'...
fatal: protocol error: bad line length character: This
 

Мы используем GitLab локально и используем SSH URL для клонирования репозиториев. Вчера все пользователи и Дженкинс сообщили о проблемах с клонированием, извлечением и отправкой кода в репозитории. Вскоре мы выяснили, что протокол HTTPS работает должным образом, и эта проблема была ограничена для всех, использующих SSH URL.

Вот некоторые вещи, которые мы пытались получить более подробно, но безрезультатно, за исключением того, что мы видим, что после авторизации происходит сбой со статусом выхода 254 или 1 случайным образом:

 GIT_SSH_COMMAND='ssh -v' git clone git@host:repository.git

GIT_SSH_COMMAND='ssh -v' git clone git@host:repository.git
 

Фрагмент вывода из приведенных выше команд

 debug1: Authentication succeeded (publickey).
Authenticated to host ([a.y.x.b]:22).
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: pledge: network
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug1: Remote: Forced command.
debug1: Remote: Port forwarding disabled.
debug1: Remote: X11 forwarding disabled.
debug1: Remote: Agent forwarding disabled.
debug1: Remote: PTY allocation disabled.
debug1: Remote: Forced command.
debug1: Remote: Port forwarding disabled.
debug1: Remote: X11 forwarding disabled.
debug1: Remote: Agent forwarding disabled.
debug1: Remote: PTY allocation disabled.
debug1: Sending environment.
debug1: Sending env GIT_PROTOCOL = version=2
debug1: Sending command: git-upload-pack 'repository.git'
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: client_input_channel_req: channel 0 rtype eow@openssh.com reply 0
debug1: channel 0: free: client-session, nchannels 1
fatal: protocol error: bad line length character: This
Transferred: sent 2352, received 2984 bytes, in 0.1 seconds
Bytes per second: sent 22560.7, received 28622.9
debug1: Exit status 1
 

Комментарии:

1. Попробуйте запустить ssh git@host 'echo hello' и посмотреть, печатает ли он что-нибудь, кроме «привет».

2. В качестве шага отладки: запуск простого ssh git@host файла также может помочь выявить некоторые проблемы.

Ответ №1:

Проверьте, какие поддерживаемые оболочки

 cat /etc/shells
 

В нашем случае у пользователя git была отключена оболочка, и на изображении ниже отображался /sbin/ nologin

остановлен экземпляр gitlab

 gitlab-ctl stop
 

Обновить оболочку для пользователя git (вы можете использовать любую из приведенных ниже команд)

 usermod -s which git-shell git
usermod -s /bin/sh git
 

Перенастроить GitLab

 gitlab-ctl reconfigured
 

Перезапустите службу GitLab

 gitlab-ctl restart
 

Наконец, проверьте, что /sbin/ nologin изменился на /bin/sh для пользователя git, как показано на рисунке ниже

 vi /etc/passwd | grep git
 

введите описание изображения здесь

Комментарии:

1. /bin/sh возможно, это не та оболочка, которую вы хотели бы использовать здесь. Смотрите git-scm.com/docs/git-shell

2. Мы выполнили следующую команду, и мне сказали, «какой git-shell» сопоставляется с /bin/sh: usermod -s, который git-shell git

3. С вашей настройкой любой, у кого есть git@host доступ, теперь может запускать любую команду от имени пользователя git . Например, ssh git@host echo test будет печатать test . Это может быть нормально, в зависимости от того, насколько вы доверяете своим пользователям. Вот почему я сказал, что этого не может быть . Это просто примечание.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Git clone error filename too long
  • Git clone certificate error
  • Git checkout unmerged error
  • Git checkout master error pathspec master did not match any file s known to git
  • Git checkout main error pathspec main did not match any file s known to git

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии