Linux скрипты ввод пароля

How to provide password to a command that prompts for one in bash?

I’m writing a UNIX shell function that is going to execute a command that will prompt the user for a password. I want to hard-code the password into the script and provide it to the command. I’ve tried piping the password into the command like this:

This may not work for some commands as the command may flush the input buffer before prompting for the password. I’ve also tried redirecting standard input to a file containing the password like this, but that doesn’t work either:

I know that some commands allow for the password to be provided as an argument, but I’d rather go through standard input. I’m looking for a quick and dirty way of piping a password into a command in bash.

Have you looked at autoexpect ? It doesn’t get much easier than that. You just just pass it the command and it will record everything you do and create the expect file for you.

8 Answers 8

How to use autoexpect to pipe a password into a command:

These steps are illustrated with an Ubuntu 12.10 desktop. The exact commands for your distribution may be slightly different.

This is dangerous because you risk exposing whatever password you use to anyone who can read the autoexpect script file.

DO NOT expose your root password or power user passwords by piping them through expect like this. Root kits WILL find this in an instant and your box is owned.

EXPECT spawns a process, reads text that comes in then sends text predefined in the script file.

    Make sure you have expect and autoexpect installed:

sudo apt-get install expect sudo apt-get install expect-dev 
man expect man autoexpect 
touch testfile.txt sudo chown root:root testfile.txt [enter password to authorize the changing of the owner] 
touch myfile.txt autoexpect -f my_test_expect.exp sudo chown root:root myfile.txt [enter password which authorizes the chown to root] autoexpect done, file is my_test_expect.exp 
sudo chown el my_test_expect.exp //make el the owner. sudo chmod 700 my_test_expect.exp //make file only readable by el. 
set timeout -1 spawn sudo chown root:root myfile.txt match_max 100000 expect -exact "\[sudo\] password for el: " send -- "YourPasswordStoredInPlaintext\r" expect eof 
expect my_test_expect.exp spawn sudo chown root:root myfile.txt [sudo] password for el: 
ls -l -rw-r--r-- 1 root root 0 Dec 2 14:48 myfile.txt 

It worked because it is root, and el never entered a password. If you expose your root, sudo, or power user password with this script, then acquiring root on your box will be easy. Such is the penalty for a security system that lets everybody in no questions asked.

Источник

Automatically input a password when a bash script is run [duplicate]

How do I put the root password into the script so that it accepts it as the password when it reads and executes the sudo line (so I don’t have to type it manually)?

Читайте также:  Linux set ethernet speed

1 Answer 1

Spawning an expect session within your bash script is typically how you automate interactive prompts.

expect -c " spawn sudo setpci -s 00:02.0 F4.B=00 expect -nocase \"password:\" " 

Note that this isn’t the recommended approach in this case as it is a huge security hole to store your root password in a bash script.

The correct solution would be to edit your /etc/sudoers/ to not prompt you for a password for that binary.

#in /etc/sudoers neohexane ALL=(ALL) NOPASSWD : /usr/bin/setpci 

«isn’t recommended» seems like an understatement. I’d remove the expect solution altogether. Unless this is his own personal box, he should absolutely not be leaving the root password lying around in a plain text file.

I think it’s worth keeping as an example of how to use expect. I’ll emphasise how not recommended it is.

Leaving the password «Lying around» is the real problem with security. You can not automate a system unless the automatic has the password, and giving that password securely is a major pain. Even using the best method given. (using «—login-path»), is technically not real secure as the password is still there, just encrypted. Without more information what is to say a hacker that gets on the system can extract the password from the «.mylogin.cnf» file? Still it that is the most secure method so far.

Источник

передать пароль в терминал linux из скрипта

как можно сделать так, чтобы пароль вводился автоматом из скрипта. P.S.: Данный код написан мной и для меня проблема безопасности не стоит.

Используйте expect , но можно разрешить безпарольный вызов из конфигурации sudo (почти как в ответе, но я бы ограничил только определённый набор команд, а не всё подряд).

2 ответа 2

Если вопрос стоит в том, чтобы не вводить пароль sudo , тогда нужно просто его настроить, для этого добавляется в файл /etc/sudoers строка:

Пароль больше не будет запрашиваться.

#!/bin/bash echo mYsuperPassWorD|sudo -S iptables -t mangle -A POSTROUTING -j TTL --ttl-set 65 

Читайте хелпы и маны, они рулез!

$ sudo --help . Параметры: -A, --askpass использовать вспомогательную программу для ввода пароля -b, --background выполнить команду в фоновом режиме -B, --bell ring bell when prompting -C, --close-from=num закрыть все дескрипторы файлов >= num -E, --preserve-env сохранить пользовательское окружение при выполнении команды --preserve-env=list preserve specific environment variables -e, --edit редактировать файлы вместо выполнения команды -g, --group=group выполнить команду от имени или ID указанной группы -H, --set-home установить для переменной HOME домашний каталог указанного пользователя -h, --help показать справку и выйти -h, --host=host выполнить команду на узле (если поддерживается модулем) -i, --login запустить оболочку входа в систему от имени указанного пользователя; также можно задать команду -K, --remove-timestamp полностью удалить файл timestamp -k, --reset-timestamp объявить недействительным файл timestamp -l, --list показать список прав пользователя или проверить заданную команду; в длинном формате используется дважды -n, --non-interactive автономный режим без не вывода запросов пользователю -P, --preserve-groups сохранить вектор группы вместо установки целевой группы -p, --prompt=prompt использовать указанный запрос пароля -S, --stdin читать пароль из стандартного ввода . 

Но лучше сразу запускать скрипт от рутового пользователя. Например из cron или юнита/таймера systemd.

Читайте также:  Linux примонтировать внешний диск

Источник

Is it possible to pass passwords on a shell script?

Long time i am searching for this, i would like to know is it possible to pass passwords in a shell script? Many of the answers returned with no. Recently i read an article stating that how to pass passwords in a shell script. I have tried that, but it doesn’t seem to work. This is the link. Can anyone checkitout and revert back? Also pls say me is there a way to pass passwords in a shell script? If no pls say me how linux gets the input for the password?

6 Answers 6

By «entering passwords», you likely mean entering data without being visible for the user.

(suggested by geirha) When using bash, you can use the -s option to prevent typed characters from being displayed:

read -p "Password please: " -s pass 

Alternatively, change the behavior of the terminal to hide typed characters with stty -echo (disable echo ). After reading the password with the shell built-in read into a variable (in the below example, $pass ), turn it back on with stty echo . Because the new line from Enter is hidden to, you’ve to print a newline to get future output on a new line.

stty -echo read -p "Password please: " pass stty echo printf '\n' 

read and printf are shell built-ins. stty is provided by the coreutils package which is installed by default. That means that this snippet is very portable.

Note: the -p option is not standard, but from bash . If you need to display a prompt in other shells, use:

printf "Password please: " stty -echo read pass stty echo printf '\n' 

I just want to give the root password of the remote system in the script. Is it possible in your case?

@karthick87: no, this script just captures the data the user types in interactively. If you want to put root passwords in scripts, why don’t you consider keybased logins?

In zsh it is achievable through read -s ‘pw?Prompt text’ , where pw is a variable where password will be placed and -s is a flag to hide input.

To which program do you want to pass a password?

The script on the link works for me. Note that is not a shell script but an expect script (needs the package expect to be installed`). Using expect is a common way to automate text based interactive programs.

Non-interactive ssh logins are often done using key-based authentication with an empty passphrase.

Some other programs (like sudo ) have options to read a password from stdin.

Читайте также:  Usb to serial converter in linux

Providing a password as a command line option is often a security problem as on most systems any user can see any other users processes including there command line arguments using simple tools like ps .

So maybe key authentication works for you: Use ssh-keygen to create a authentication key (just press Enter when asked for a pass phrase) and copy it to the remote user using ssh-copy-id .If key authentication is enabled for sshd (it is by default) ssh will then not ask you for a password.

A script should never really handle passwords. Have whichever application needs the password ask for it itself, or if that’s not possible, find a better means of authenticating with the application. Please read http://mywiki.wooledge.org/BashFAQ/069

I ran into this issue as well and created an opensource (MIT License) tool to do this called encpass.sh. (https://github.com/plyint/encpass.sh) It creates a key for the script and stores the key and encrypted secrets in a hidden directory on disk. (Typically in your user’s home directory, but you can define another location if you prefer)

you can simply do something like this.

# echo -e "password_here\npassword_here" | su user 

There’s a way to store passwords in a bash script but you have to encrypt the script so no one can actually read it, or run any type of debugger on it to see exactly what it is doing. To encrypt a bash/shell script and have it actually be executable, try copying and pasting it here

On the above page, all you have to do is submit your script (you can submit a sample script first for your peace of mind). A zip file will be generated for you. Right click on the download link and copy the URL you’re provided. Then, go to your UNIX box and perform the following steps.

Installation:

 wget link-to-the-zip-file unzip the-newly-downloaded-zip-file cd /tmp/KingLazySHIELD ./install.sh /var/tmp/KINGLAZY/SHIELDX-(your-script-name) /home/(your-username) -force 

What the above install command will do for you is:

  1. It’ll install the encrypted script in the directory /var/tmp/KINGLAZY/SHIELDX-(your-script-name) .
  2. It’ll place a link to this encrypted script in whichever directory you specify in replacement of /home/(your-username) — that way, it allows you to easily access the script without having to type the absolute path.
  3. Ensures NO ONE can modify the script — Any attempts to modify the encrypted script will render it inoperable. until those attempts are stopped or removed.
  4. Ensures absolutely NO ONE can make copies of it. No one can copy your script to a secluded location and try to screw around with it to see how it works. All copies of the script must be links to the original location which you specified during install.

I don’t believe this works for interactive scripts that prompts the user for a response. The values should be hardcoded into the script. The encryption ensures no one can actually see those values so you need not worry about that.

Источник

Оцените статью
Adblock
detector