write a shell script to ssh to a remote machine and execute commands

后端 未结 9 1395
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 19:11

I have two questions:

  1. There are multiple remote linux machines, and I need to write a shell script which will execute the same set of commands in each machine.
9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 19:41

    Install sshpass using, apt-get install sshpass then edit the script and put your linux machines IPs, usernames and password in respective order. After that run that script. Thats it ! This script will install VLC in all systems.

    #!/bin/bash
    SCRIPT="cd Desktop; pwd;  echo -e 'PASSWORD' | sudo -S apt-get install vlc"
    HOSTS=("192.168.1.121" "192.168.1.122" "192.168.1.123")
    USERNAMES=("username1" "username2" "username3")
    PASSWORDS=("password1" "password2" "password3")
    for i in ${!HOSTS[*]} ; do
         echo ${HOSTS[i]}
         SCR=${SCRIPT/PASSWORD/${PASSWORDS[i]}}
         sshpass -p ${PASSWORDS[i]} ssh -l ${USERNAMES[i]} ${HOSTS[i]} "${SCR}"
    done
    

提交回复
热议问题