Certainly! Below, you'll find a bash script that takes three arguments: the first is the file you want to copy, the second is a list of remote hosts (in a file, where each line is a host), and the third is the remote path where the file should be copied to. This script will copy the specified file to the given location on each remote host and then execute a pkill command on each host.
Before running the script, make sure you have password-less SSH access set up to each remote host using SSH keys, or you'll be prompted for the password for each host multiple times.
The script also assumes the user you're SSHing as has the necessary permissions to copy files to the desired location and run the pkill command.
#!/bin/bash
# Usage: ./script.sh file_to_copy host_list remote_path
FILE_TO_COPY=$1
HOST_LIST=$2
REMOTE_PATH=$3
# Command to be executed on the remote machine(s).
# Tailor this command to your specific needs (e.g., replace 'process_name' with the actual name).
PKILL_COMMAND="pkill -f process_name"
if [ "$#" -ne 3 ]; then
echo "Usage: $0 [File to Copy] [Host List] [Remote Path]"
exit 1
fi
# Check if the file to copy exists
if [ ! -f "$FILE_TO_COPY" ]; then
echo "Error: File $FILE_TO_COPY not found."
exit 1
fi
# Check if the host list file exists
if [ ! -f "$HOST_LIST" ]; then
echo "Error: Host list file $HOST_LIST not found."
exit 1
fi
# Main loop to iterate over hosts
while IFS= read -r host
do
echo "Copying $FILE_TO_COPY to $host:$REMOTE_PATH"
scp "$FILE_TO_COPY" "${host}:$REMOTE_PATH"
# Check if SCP was successful
if [ $? -eq 0 ]; then
echo "Successfully copied $FILE_TO_COPY to $host:$REMOTE_PATH"
echo "Executing pkill command on $host"
ssh "$host" "$PKILL_COMMAND"
if [ $? -eq 0 ]; then
echo "Successfully executed pkill command on $host"
else
echo "Failed to execute pkill command on $host"
fi
else
echo "Failed to copy $FILE_TO_COPY to $host:$REMOTE_PATH"
fi
done < "$HOST_LIST"
echo "Done."
Save this script into a file, make it executable with chmod +x script.sh, and then you can run it as described. Remember to replace 'process_name' in the PKILL_COMMAND variable with the name of the process you actually want to kill.
Keep in mind, depending on what you're trying to kill, you might need to adjust permissions or use sudo for the pkill command, which would complicate the script slightly due to password prompting for sudo. In such cases, you'd typically configure NOPASSWD for specific commands in /etc/sudoers on the remote hosts or handle the password input in another secure way.