Search code examples
bashscriptingdirectorylshostname

Bash Script to gather directory and server info on a single line


I am currently using the below command in a ,sh to gather a list of contents of a specific folder, on a list of servers, depicted by list.txt (contains IPs)

for f in `cat serverlist.txt`; do
    echo "### $f ###";
    sshpass -p PASSWORD ssh USER@$f ls /usr/local/folder  >>list.txt;
done

Whilst this works, its only half of my problem, I am a total novice with BASH

What I am trying to obtain is a list formatted as such

file1.HOSTNAMEOFSERVER1
file2.HOSTNAMEOFSERVER1
file3.HOSTNAMEOFSERVER1
file1.HOSTNAMEOFNEXTSERVER2
file2.HOSTNAMEOFNEXTSERVER2
file3.HOSTNAMEOFNEXTSERVER2
file1.HOSTNAMEOFNEXTSERVER3

Is any one able to help?


Solution

  • Untested:

    while read host; do
        sshpass -p PASSWORD ssh USER@"$host" ls /usr/local/folder | 
            sed 's/$/.'"$host"/;
    done < serverlist.txt
    

    DO NOT ACTUALLY PUT YOUR PASSWORD in a script like this. Set up your ssh keys instead.