0

Im running ubuntu 14.04 LTS (no GUI)

and im looking to write a bash script that does the following:

  1. Check to see if the ssh service is enabled or disabled

  2. If enabled, then disable, if disabled then enable.

Every time I run this script it should turn on/off the SSH service.

2 Answers 2

2

Here is a small shell script,

#!/bin/bash
if `service ssh status | grep -q running`
then
    service ssh stop
    echo "ssh stopped by user"
else
    service ssh start
    echo "ssh started by user" 
fi

After saving it as script.sh, run it as, (give it execution permission)

sudo ./script.sh

or without execution permission

sudo bash ./script.sh
1
  • Thanks Dude, one small issue though, I need it to be automated, so i cant be pressing "y" or "n" it needs to work like a switch, running "sh script.sh" should just enable or disable the SSH service automaticly. Jul 18, 2014 at 5:26
0

Save the following in a file named "toggleSsh.sh"

#!/bin/bash

stat=`status ssh`
echo $stat
#stat is returned like: ssh start/running, process 1602
goal=`echo $stat|cut -f2 -d" "|cut -f1 -d/`
#cut the 2nd field afetr 1st space; then cut the 1st field before "/" to get the "goal" of the ssh job.

#ignoring the status
echo $goal
if [ "$goal" == "start" ];
then
  service ssh stop
else
  service ssh start
fi

Run this script as sudo toggleSsh.sh since service command needs root privilege.

You can finetune the above script by taking into account the status(waiting, starting, pre-start, spawned, post-start, running, pre-stop, stopping, killed or post-stop) of the ssh job, and not just the goal (start/stop.) Read man status to understand more about how you can utilise the status command.

10
  • Thanks Dude, your a Ledgend, i'll have a play soon, and try get it working :) Jul 18, 2014 at 5:48
  • Ok, its not quite working, seems to be an error on line 11, "if [ "$goal" == "start" ];" see verbose output below.. Jul 18, 2014 at 6:14
  • opps, to long to paste here... Jul 18, 2014 at 6:15
  • #!/bin/bash stat=status ssh echo $stat ssh start/running, process 1663 #stat is returned like: ssh start/running, process 1602 goal=echo $stat|cut -f2 -d" "|cut +f1 -d/ cut: you must specify a list of bytes, characters, or fields Try 'cut --help' for more information. #cut the 2nd field afetr 1st space; then cut the 1st field before "/" to get the "goal" of the ssh job. #ignoring the status echo $goal if [ "$goal" == "start" ]; then service ssh stop else service ssh start fi ssh.sh: 11: [: unexpected operator start: Job is already running: ssh Jul 18, 2014 at 6:18
  • ffs! this website suX! Jul 18, 2014 at 6:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .