- DATAENGINER
- Как в jenkins сбросить пароль администратора
- How to reset Jenkins security settings from the command line?
- 23 Answers 23
- Easy way out of this is to use the admin psw to login with your admin user:
- Install xclip if you don’t have it:
- Как сбросить использование / пароль jenkins в Windows?
- 7 ответов
- How to “Unlock Jenkins”?
- 30 Answers 30
DATAENGINER
Добрый день! В прошлой статье мы рассмотрели, как установить Jenkins. Но что делать если мы забыли пароль от учетной записи администратора? На самом деле если у нас есть доступ к машине, то ни чего страшного мы его всегда можем изменить. Итак, давайте рассмотрим, как поменять пароль локальному администратору Jenkins.
Jenkins хранит пароль на сервере в файле config.xml, поэтому нам необходимо найти этот файл и указать новый пароль.
Шаг 1. Перейдем в корневой раздел командой: cd / и запустим поиск при помощи команды find –name “config.xml”.
Необходимый нам конфиг, находится в каталоге /users/administrator – цифры после имени пользователя — это хеш. Хэш уникальней для каждой машины.
Шаг 2. Давайте откроем сам файл конфигурации и посмотрим на его содержимое.
Файл использует разметку xml, поэтому он очень удобен и легко читаем. Вверху указывается имя пользователя, а сам пароль можно найти чуть ниже в блоке
Пароль представлен в виде хэша, чтобы его изменить необходимо заменить хэш после jbcrypt. Заменять нужно только на хэш пароля. Вы можете использовать такой хэш «$2a$10$razd3L1aXndFfBNHO95aj.IVrFydsxkcQCcLmujmFQzll3hcUrY7S». Это уже готовый хэш от слова test.
Шаг 4. Заменим пароль сохраним файл и перезапустим Jenkins чтобы изменения вступили в силу.
Шаг 5. Теперь мы можем авторизоваться с новым паролем.
Если все сделали правильно, то авторизация пройдет без проблем.
Как в jenkins сбросить пароль администратора
Пароль администратора иногда оказывается утерян или забыт.
Если такое произошло — можно задать новый пароль.
Первый способ
Заключается во временном отключении авторизации.
В конфигурационном файле можно поменять значение параметра, который отвечает за то будет ли запрашиваться пароль вообще
False
Если значение установлено в False — пароль не запрашивается.
Далее службу нужно перезапустить
systemctl restart jenkins.service
Когда эти действия проделаны — можно зайти в веб-интерфейс без пароля и установить новый пароль, с которым удобно будет работать.
Затем поменять значение на True и перезапустить Jenkins.
Минус данного подхода в том, что какое-то время Jenkins оказывается полностью открыт и зайти без пароля может кто угодно.
Второй способ
Заключается в генерации хэша и задании его в качестве пароля в конфигурационном файле
Значение генерируется так
Затем оно добавляется в /var/lib/jenkins/admin/config.xml между открывающим и закрывающим тэгами passwordHash
Изменения вступят в силу после перезапуска
systemctl restart jenkins.service
Таким образом пароля менять безопаснее, но прибегая к нему добиться результата удается не всегда.
Статья про установку Jenkins и начало работы.
How to reset Jenkins security settings from the command line?
Is there a way to reset all (or just disable the security settings) from the command line without a user/password as I have managed to completely lock myself out of Jenkins ?
23 Answers 23
The simplest solution is to completely disable security — change true to false in /var/lib/jenkins/config.xml file.
Then just restart Jenkins, by
And then go to admin panel and set everything once again.
If you in case are running your Jenkins inside k8s pod from a docker, which is my case and can not run service command, then you can just restart Jenkins by deleting the pod:
Once the command was issued, the k8s will terminate the old pod and start a new one.
/.jenkins/ folder – Andrii Abramov Jan 3 ’17 at 11:07
One other way would be to manually edit the configuration file for your user (e.g. /var/lib/jenkins/users/username/config.xml) and update the contents of passwordHash:
Once you have done this, just restart Jenkins and log in using this password:
xml tag is a child of . Look at the default admin user for an idea of the total XML structure. – ivandov Jul 27 ’16 at 20:46
I found the file in question located in /var/lib/jenkins called config.xml, modifying that fixed the issue.
element in users/ /config.xml will accept data of the format
So, if your salt is bar and your password is foo then you can produce the SHA256 like this:
You should get 7f128793bc057556756f4195fb72cdc5bd8c5a74dee655a6bfb59b4a4c4f4349 as the result. Take the hash and put it with the salt into
Restart Jenkins, then try logging in with password foo . Then reset your password to something else. (Jenkins uses bcrypt by default, and one round of SHA256 is not a secure way to store passwords. You’ll get a bcrypt hash stored when you reset your password.)
In El-Capitan config.xml can not be found at
Its available in
then after that as other mentioned open the config.xml file and make the following changes
In this replace true with false
Save it and restart the jenkins(sudo service jenkins restart)
The answer on modifying was correct. Yet, I think it should be mentioned that /var/lib/jenkins/config.xml looks something like this if you have activated «Project-based Matrix Authorization Strategy». Deleting /var/lib/jenkins/config.xml and restarting jenkins also does the trick. I also deleted the users in /var/lib/jenkins/users to start from scratch.
To reset it without disabling security if you’re using matrix permissions (probably easily adaptable to other login methods):
- In config.xml , set disableSignup to false .
- Restart Jenkins.
- Go to the Jenkins web page and sign up with a new user.
- In config.xml , duplicate one of the
lines and replace username with the new user.
- Delete the new user.
- Delete the temporary
line in config.xml .
No securities were harmed during this answer.
To disable Jenkins security in simple steps in Linux, run these commands:
It will remove useSecurity and authorizationStrategy lines from your config.xml root config file and restart your Jenkins.
See also: Disable security at Jenkins website
After gaining the access to Jenkins, you can re-enable security in your Configure Global Security page by choosing the Access Control/Security Realm. After than don’t forget to create the admin user.
We can reset the password while leaving security on.
The config.xml file in /var/lib/Jenkins/users/admin/ acts sort of like the /etc/shadow file Linux or UNIX-like systems or the SAM file in Windows, in the sense that it stores the hash of the account’s password.
If you need to reset the password without logging in, you can edit this file and replace the old hash with a new one generated from bcrypt:
This will output your hash, with prefix 2a, the correct prefix for Jenkins hashes.
Now, edit the config.xml file:
Once you insert the new hash, reset Jenkins:
(if you are on a system with systemd):
You can now log in, and you didn’t leave your system open for a second.
On the offchance you accidentally lock yourself out of Jenkins due to a permission mistake, and you dont have server-side access to switch to the jenkins user or root. You can make a job in Jenkins and add this to the Shell Script:
Then click Build Now and restart Jenkins (or the server if you need to!)
Copy the password from the initialAdminPassword file and paste it into the Jenkins.
In order to remove the by default security for jenkins in Windows OS,
You can traverse through the file Config.xml created inside /users/
Inside this file you can change the code from
1 first check location if you install war or Linux or windows based on that
for example if war under Linux and for admin user
go to this tag after #jbcrypt:
change this password using use any website for bcrypt hash generator
make sure it start with $2a cause this one jenkens uses
step-1 : go to the directory cd .jenkins/secrets then you will get a ‘initialAdminPassword’.
step-2 : nano initialAdminPassword
you will get a password
remember this, set to false only may cause a problem for you, since these instructions are mentioned in thier official documentation here.
Easy way out of this is to use the admin psw to login with your admin user:
- Change to root user: sudo su —
- Copy the password: xclip -sel clip
- Login with admin and press ctrl + v on password input box.
Install xclip if you don’t have it:
Jenkins over KUBENETES and Docker
In case of Jenkins over a container managed by a Kubernetes POD is a bit more complex since: kubectl exec PODID —namespace=jenkins -it — /bin/bash will you allow to access directly to the container running Jenkins, but you will not have root access, sudo , vi and many commands are not available and therefore a workaround is needed.
Use kubectl describe pod [. ] to find the node running your Pod and the container ID (docker://. )
- SSH into the node
- run docker exec -ti -u root — /bin/bash to access the container with Root privileges
- apt-get update
- sudo apt-get install vim
The second difference is that the Jenkins configuration file are placed in a different path that corresponds to the mounting point of the persistent volume, i.e. /var/jenkins_home , this location might change in the future, check it running df .
Then disable security — change true to false in /var/jenkins_home/jenkins/config.xml file.
Now it is enough to restart the Jenkins, action that will cause the container and the Pod to die, it will created again in some seconds with the configuration updated (and all the chance like vi, update erased) thanks to the persistent volume.
The whole solution has been tested on Google Kubernetes Engine. UPDATE Notice that you can as well run ps -aux the password in plain text is shown even without root access.
Как сбросить использование / пароль jenkins в Windows?
Может быть, дурацкий вопрос, я установил jenkins на окнах по умолчанию, не установил пользователя / пароля, сначала он работал, не нужно входить в систему. Но при запуске веб-страницы 8080 сейчас она зависает, страница входа в систему зависает, я пробовал несколько обычных комбинаций пользователя и пароля, ни одна из них не прошла. Также искал разрешение на веб-сайте, нашел только немного о Linux, но не о Windows, поэтому нужна помощь. страница входа jenkins
7 ответов
Вы можете попытаться восстановить безопасность Jenkins:
- Остановите службу Jenkins
- Откройте config.xml в текстовом редакторе (например, в блокноте ++), возможно, в C:\jenkins\config.xml (можно также сделать резервную копию).
- Найдите этот true и измените его на false
- Запустить службу Jenkins
Вы можете создать пользователя с правами администратора и снова включить безопасность.
Это для среды Windows:
Я получил начальный пароль администратора в папке C: \ Users \ Deepak («MyUser»). Jenkins \ secrets \ initialAdminPassword
Я смог войти с пользователем «admin» и выше паролем. Затем в Jenkins> people я отредактировал пароль пользователя и нажал «Применить», чтобы отразить изменения.
Прочтите начальный пароль:
Имя пользователя по умолчанию — ‘admin’ , а пароль — пароль от initialAdminPassword, когда вы следуете указанному выше пути.
Затем выйдите из системы и войдите, чтобы убедиться, что новый пароль работает.
Я создал нового пользователя с «admin» и новым паролем на этапах установки. Но через какое-то время я хотел снова войти в систему, и этот пароль показывал неправильный, поэтому я снова использовал исходный пароль для входа.
Первоначальный пароль можно найти в следующем месте: —
Попробуйте этот метод
1) Скопируйте initialAdminPassword в указанный путь.
2) Войдите в систему со следующими учетными данными
3) После входа в приложение jenkins вы можете щелкнуть профиль администратора и сбросить пароль.
Я получил начальный пароль в пути C: \ Program Files (x86) \ Jenkins \ secrets \ initialAdminPassword
Затем я успешно вхожу в систему с именем пользователя «администратор».
У меня была такая же проблема, без подключения при втором входе в систему.
После решения проблемы (useSecurity и т. Д., См. Выше) я понял, что admin / admin работает (с Synology, это актуально).
How to “Unlock Jenkins”?
I am installing Jenkins 2 on windows,after installing,a page is opened,URL is:
http://localhost:8080/login?from=%2F
content of the page is like this:
Question:
How to «Unlock Jenkins»?
PS:I have looked for the answer in documentation and google.
30 Answers 30
Starting from version 2.0 of Jenkins you may use
to prevent this screen.
Accroding to documentation
jenkins.install.runSetupWizard — Set to false to skip install wizard. Note that this leaves Jenkins unsecured by default. Development-mode only: Set to true to not skip showing the setup wizard during Jenkins development.
More details about Jenkins properties can be found on this Jenkins Wiki page.
e.g. for Linux, use the command: less /var/log/jenkins/jenkins.log
And scroll down to the part: «Jenkins initial setup is required. An admin user has been created . to proceed to installation:
[randompasswordhere] /var/log/jenkins/jenkins.log , unless customized in /etc/default/jenkins (for *.deb) or via /etc/sysconfig/jenkins (for */rpm)
Windows
By default logs should be at %JENKINS_HOME%/jenkins.out and %JENKINS_HOME%/jenkins.err , unless customized in %JENKINS_HOME%/jenkins.xml
Mac OS X
Log files should be at /var/log/jenkins/jenkins.log , unless customized in org.jenkins-ci.plist
- open file: e:\Program Files (x86)\Jenkins\secrets\initialAdminPassword
- copy content file: 47c5d4f760014e54a6bffc27bd95c077
- paste in input: http://localhost:8080/login?from=%2F
Some of the above instructions seem to have gone out of date. As of the released version 2.0, creating the following file will cause Jenkins to skip the unlock screen:
This file must contain the string 2.0 without any line terminators. I’m not sure if this is required but Jenkins also sets the owner/group to be the same as the Jenkins server, so that’s probably a good thing to mimic as well.
I did not need to create the upgraded or .last_exec_version files.
I assume you were running jenkins.war manually with java -jar jenkins.war , then all logging information by default is output to standard out, just type the token to unlock jenkins2.0.
If you were not running jenkins with java -jar jenkins.war , then you can always follow this Official Document to find the correct log location.
I have seen a lot of response to the question, most of them were actually solution to it but they solve the problem when jenkins is actually run as a standalone CI without Application container using the command:
But when running on Tomcat as it is the case in this scenario, Jenkins logs are displayed on the catalina logs since the software is running on a container. So you need to go to the logs folder:
in my own case. Just scroll almost to the middle to look for a generated password which is essentially a token and copy and paste it to unlock jenkins.
I hope this fix your problem.
Step 1: Open the terminal on your mac
Step 2: Concatenate or Paste
Step 3: It will ask for password, type your mac password and enter
Step 4: A key would be generated.
Step 5: Copy and paste the security token in Jenkins
Step 6: Click continue
Open your terminal and type code below to find all the containers.
docker container list -a
You will find jenkinsci/blueocean and/or docker:dind if not than
docker container run —name jenkins-docker —rm —detach ^ —privileged —network jenkins —network-alias docker ^ —env DOCKER_TLS_CERTDIR=/certs ^ —volume jenkins-docker-certs:/certs/client ^ —volume jenkins-data:/var/jenkins_home ^ —volume «%HOMEDRIVE%%HOMEPATH%»:/home ^ docker:dind
docker container run —name jenkins-blueocean —rm —detach ^ —network jenkins —env DOCKER_HOST=tcp://docker:2376 ^ —env DOCKER_CERT_PATH=/certs/client —env DOCKER_TLS_VERIFY=1 ^ —volume jenkins-data:/var/jenkins_home ^ —volume jenkins-docker-certs:/certs/client:ro ^ —volume «%HOMEDRIVE%%HOMEPATH%»:/home ^ —publish 8080:8080 —publish 50000:50000 jenkinsci/blueocean
docker run jenkinsci/blueocean or docker run docker:dind