How to write a bash script to give a different program response

I have a bash script that performs several tasks, including python manage.py syncdb in a new database. This command prompts for input, for example, login information for the administrator. Currently, I just type this on the command line every time. Is there a way that I can automatically provide these answers as part of a bash script?

Thanks, I don't know anything about bash.

I am using Ubuntu 10.10.

+4
source share
4 answers

I answered a similar question on SF, but this one is more general and good to have on SO.

"You want to use expect for this. Maybe it’s already on your computer [try which expect ]. A tool for any interactive command line automation. This is the Tcl library, so you can get some Tcl skills along the way for free. Beware, it's addictive "

In this case, I should mention that there is also pexpect , which is what Python expected.

 #!/path/to/expect spawn python manage.py syncdb expect "login:*" send -- "myuser\r" expect "*ssword:*" send -- "mypass\r" interact 
+3
source

If the program in question cannot read input from stdin , for example:

 echo "some input" | your_progam 

then you need to look at something like expect and / or autoexepect

+3
source

You can specify default values ​​for variables. On lines 4 and 5, if the RSRC and LOCAL variables are not set, they are set to these default values. This way you can specify script parameters or use default

 #!/bin/bash RSRC=$1 LOCAL=$2 : ${RSRC:="/var/www"} : ${LOCAL:="/disk2/backup/remote/hot"} rsync -avz -e 'ssh ' user@myserver :$RSRC $LOCAL 
0
source

You can do it like this, for example with the login.py script example:

 if __name__ == '__main__': import sys user = sys.stdin.readline().strip() passwd = sys.stdin.readline().strip() if user == 'root' and passwd == 'password': print 'Login successful' sys.exit(0) sys.stderr.write('error: invalid username or password\n') sys.exit(1) 

good-credentials.txt

 root password 

bad credentials.txt

 user foo 

Then you can do an automatic login using:

 $cat good-credentials.txt | python login.py Login successful $cat bad-credentials.txt | python login.py error: invalid username or password 

The downside of this approach is that you save your password in plain text, which is not a big practice.

0
source

Source: https://habr.com/ru/post/1336084/


All Articles