• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 333
  • Last Modified:

Linux For Loop

How can I write a script to shutdown some remote Linux servers.  I believe I need to create a list of IP addresses for the servers to have the script loop to it, then ssh into as root and shut it down with the shutdown command.  Thanks
0
yogio
Asked:
yogio
2 Solutions
 
woolmilkporcCommented:
Yes, you should create a list of IP addresses or hostnames, one per line.

You can then run either a "while" or a "for" loop against that file, where I prefer the "while" loop:

while read server
  do
    ssh -n root@$server "shutdown now"
  done < /path/to/hostname_list

Here is the "for" loop:

for server in $(</path/to/hostname_list)
  do
    ssh root@$server "shutdown now"
  done

Add options like "-H" or "-P" to the shutdown command, if desired.

wmp
0
 
arnoldCommented:
With ssh, after issuing the shutdown, you have to also issue an exit, or the shutdown, might lock your session.
Usually root login might not be allowed, the use of a Setuid script or sudo shutdown now ;exit might be a way to go.
0
 
simon3270Commented:
There shouldn't be a hang - the ssh call will run the command and exit as soon as it finishes.

It can be a problem if you log onto the remote server and issue the "shutdown now" command manually.  In that case, you could issue the command
    exec shutdown now
so that the session ends as soon as the command completes (and before the machine shuts down).
0
 
omarfaridCommented:
If you are looking for automating the script, then you need to set trust relationship between your system and remote systems by exchanging keys (so you don't have to provide passwords).

please see link below:

http://www.linuxproblem.org/art_9.html

You can avoid hanging shutdown commands by running woolmilkporc's modified script below:

for server in $(</path/to/hostname_list)
  do
    ssh root@$server "nohup shutdown now &"
  done
0
 
yogioAuthor Commented:
Thanks for all the help.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now