Quantcast
Channel: Active questions tagged ssh - Ask Ubuntu
Viewing all articles
Browse latest Browse all 803

Bash script for executing linux commands on remote machines using ssh key [duplicate]

$
0
0

I want to run a script to get details of hardwares and user details from multiple remote machines by login using ssh private key. this is my script

#!/bin/bash# Check if the user provided a fileif [ $# -eq 0 ]; then    echo "provide input file"    echo "Usage: $0 <input_file>"    exit 1fi# Read input fileinput_file=$1# Check if the file existsif [ ! -f "$input_file" ]; then    echo "Error: File $input_file not found."    exit 1fi# Read each line from the input filewhile IFS=, read -r ip_address username; do    echo "Machine IP: $ip_address"    # Connect to the server via SSH and execute the command    echo "System Users:"    ssh -i /home/subash/Desktop/privatekey "$username"@"$ip_address" "ls -l /home/ | awk 'NR >1 {print \$3}'" 2>/dev/null    echo "---------------"    echo "Disk details:"    ssh -i privatekey "$username"@"$ip_address" 'lsblk -o name,model,size,ro,mountpoint,type | grep -e part -e disk' 2>/dev/null    echo "---------------"    echo "OPERATING SYSTEM:"    ssh -i privatekey "$username"@"$ip_address" "cat /etc/os-release | grep '^NAME' | cut -d'=' -f2-" 2>/dev/null    echo "---------------"  done < "$input_file"`

The input file I'm providing have the ip address and the username. I have added my public key to all the machines authorized keys. when executing the script the while loop executes with the first IP and provides the expected output and exists it doesn't consider the next line of input. how can I modify the script to read all the input. Thanks in Advance.

The sample input file:

192.168.1.1,user1

192.168.1.2,user2

192.168.1.3,user3

If I remove the ssh command and print all the IP and user names it prints all the values from the input file.


Viewing all articles
Browse latest Browse all 803

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>