简体   繁体   中英

Bash Script read hostnames from .txt file and place in variable for ssh

I created a Bash Script that is the following:

File=/library/logs/file.txt
ssh -n username@<ip> "$(< testscript.sh)" > $File 

It will remote into a machine and run a script and place the output in file.txt What I need to do now is instead of manually entering an ip address, I need to have it read from a list of hostnames coming from a .txt file and have it place it in a variable that will substitute the ip address. An example would be: ssh username@Variable in which "Variable" will be changing each time a word is read from a file containing hostnames. Any ideas how to go about this?

Use xargs with -I

cat hosts.txt | xargs -I %REPL ssh user@%REPL

-I defines a "replacement-string", in this case "%REPL" (but you can set it to what you like). Then that specific string will be will be replaced in the command, with each line from input.

Another way i like, is using printf

echo -e "host1.com\nhost2.com" | xargs -n1 printf "ssh user@%s -p 999\n"

This is especially great, if you wanted to use more lines in the same command.. Imagine that you have a file with username on line 1 and hostname on line 2. You could simply do:

xargs -n2 printf "ssh %s@%s -p 999\n" < user_and_host.txt

Passwords

All this, assumes you are using SSH keys because, by design , the openssh client will not let you "script" passwords.

If you want to script using password authentication, there are tons of hints and methods (someone will yell "expect" any second now). But i did them all at some point or another, and they bring eternal pain and indigestion .

Its not worth it , scripting this yourself. Have a look at my favorite tool for this:

This will let you pretty much do what you need. Give it username, password, one or more commands to run + a bunch of hosts/ip's. When its done, you'll have a nice CSV-file with the result of every command, ordered by its host.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM