0

I am very new to shell scripting, can anyone help to solve a simple problem: I have written a simple shell script that does: 1. Stops few servers. 2. Kills all the process by user1 3. Starts few servers .

This script runs on the remote host. so I need to ssh to the machine copy my script and then run it. Also Command I have used for killing all the process is:

ps -efww | grep "user1"| grep -v "sshd"| awk '{print $2}' | xargs kill

Problem1: since user1 is used for ssh and running the script.It kills the process that is running the script and never goes to start the server.can anyone help me to modify the above command.

Problem2: how can I automate the process of sshing into the machine and running the script. I have tried expect script but do I need to have a separate script for sshing and performing these tasksor can I do it in one script itself. any help is welcomed.

user1731553
  • 1,887
  • 5
  • 22
  • 33

3 Answers3

2

Basically the answer is already in your script.

Just exclude your script from found processes like this

grep -v <your script name>

Regarding running the script automatically after you ssh, have a look here, it can be done by a special ssh configuration

Community
  • 1
  • 1
deimus
  • 9,565
  • 12
  • 63
  • 107
1

Just create a simple script like:

#!/bin/bash

ssh user1@remotehost '
  someservers stop
  # kill processes here
  someservers start
'

In order to avoid killing itself while stopping all user's processes try to add | grep -v bash after grep -v "sshd"

amenzhinsky
  • 962
  • 6
  • 12
0

This is a problem with some nuance, and not straightforward to solve in shell.

The best approach

My suggestion, for easier system administration, would be to redesign. Run the killing logic as root, for example, so you may safely TERMinate any luser process without worrying about sawing off the branch you are sitting on. If your concern is runaway processes, run them under a timeout. Etc.

A good enough approach

Your ssh login shell session will have its own pseudo-tty, and all of its descendants will likely share that. So, figure out that tty name and skip anything with that tty:

TTY=$(tty | sed 's!^/dev/!!')  # TTY := pts/3 e.g.
ps -eo tty=,user=,pid=,cmd= | grep luser | grep -v -e ^$TTY -e sshd | awk ...

Almost good enough approaches

The problem with "almost good enough" solutions like simply excluding the current script and sshd via ps -eo user=,pid=,cmd= | grep -v -e sshd -e fancy_script | awk ...) is that they rely heavily on the accident of invocation. ps auxf probably reveals that you have a login shell in between your script and your sshd (probably -bash) — you could put in special logic to skip that, too, but that's hardly robust if your script's invocation changes in the future.

What about question no. 2? (How can I automate sshing...?)

Good question. Off-topic. Try superuser.com.

Community
  • 1
  • 1
pilcrow
  • 56,591
  • 13
  • 94
  • 135