Kill a Program on Connecting to a specific WiFi – OSX

Hi folks. If you have the tendency, like me, to forget that you are on the corporate VPN, or leave a certain software open when you bring your laptop to work, this might be helpful to you too. It’s a small script which kills a program when you change your Wifi network. Script: #!/bin/bash function log { directory="/Users/<username>/wifi_detect" log_dir_exists=true if [ ! -d $directory ]; then echo "Attempting to create => $directory" mkdir -p $directory if [ ! -d $directory ]; then echo "Could not create directory. Continue to log to echo." log_dir_exists=false fi fi if $log_dir_exists ; then echo "$(date):$1" >> "$directory/log.txt" else echo "$(date):$1" fi } function check_program { to_kill="[${1::1}]${1:1}" log "Checking if $to_kill really quit." ps=$(ps aux |grep "$to_kill") log "ps => $ps" if [ -z "$ps" ]; then # 0 - True return else # 1 - False return 1 fi } function kill_program { log "Killing program" `pkill -f "$1"` sleep 1 if ! check_program $1 ; then log "$1 Did not quit!" else log "$1 quit successfully" fi } wifi_name=$(networksetup -getairportnetwork en0 |awk -F": " '{print $2}') log "Wifi name: $wifi_name" if [ "$wifi_name" = "<wifi_name>" ]; then log "On corporate network... Killing Program" kill_program "<programname>" elif [ "$wifi_name" = "<home_wifi_name>" ]; then # Kill <program> if enabled and if on <home_wifi> and if Tunnelblick is running. log "Not on corporate network... Killing <program> if Tunnelblick is active." if ! check_program "Tunnelblick" ; then log "Tunnelblick is active. Killing <program>" kill_program "<program>" else log "All good... Happy coding." fi else log "No known Network..." fi Now, the trick is, on OSX to only trigger this when your network changes. For this, you can have a ’launchd’ daemon, which is configured to watch three files which relate to a network being changed. ...

October 26, 2015 · 2 min · hannibal

Circular buffer in Go

I’m proud of this one too. No peaking. I like how go let’s you do this kind of stuff in a very nice way. package circular import "fmt" //TestVersion testVersion const TestVersion = 1 //Buffer buffer type type Buffer struct { buffer []byte full int size int s, e int } //NewBuffer creates a new Buffer func NewBuffer(size int) *Buffer { return &Buffer{buffer: make([]byte, size), s: 0, e: 0, size: size, full: 0} } //ReadByte reads a byte from b Buffer func (b *Buffer) ReadByte() (byte, error) { if b.full == 0 { return 0, fmt.Errorf("Danger Will Robinson: %s", b) } readByte := b.buffer[b.s] b.s = (b.s + 1) % b.size b.full-- return readByte, nil } //WriteByte writes c byte to the buffer func (b *Buffer) WriteByte(c byte) error { if b.full+1 > b.size { return fmt.Errorf("Danger Will Robinson: %s", b) } b.buffer[b.e] = c b.e = (b.e + 1) % b.size b.full++ return nil } //Overwrite overwrites the oldest byte in Buffer func (b *Buffer) Overwrite(c byte) { b.buffer[b.s] = c b.s = (b.s + 1) % b.size } //Reset resets the buffer func (b *Buffer) Reset() { *b = *NewBuffer(b.size) } func (b *Buffer) String() string { return fmt.Sprintf("Buffer: %d, %d, %d, %d", b.buffer, b.s, b.e, b.size) }

October 15, 2015 · 1 min · hannibal

DataMunger Kata with Go

Quickly wrote up the Data Munger code kata in Go. Next time, I want better abstractions. And a way to select columns based on their header data. For now, this is not bad. package main import ( "bufio" "fmt" "log" "math" "os" "regexp" "strconv" "strings" ) //Data which is Data type Data struct { columnName string compareOne float64 compareTwo float64 } func main() { // datas := []Data{WeatherData{}, FootballData{}} fmt.Println("Minimum weather data:", GetDataMinimumDiff("weather.dat", , 1, 2)) fmt.Println("Minimum football data:", GetDataMinimumDiff("football.dat", 1, 6, 7)) } //GetDataMinimumDiff gathers data from file to fill up Columns. func GetDataMinimumDiff(filename string, nameColumn int, compareColOne int, compareColTwo int) Data { data := Data{} minimum := math.MaxFloat64 readLines := ReadFile(filename) for _, value := range readLines { valueArrays := strings.Split(value, ",") name := valueArrays[nameColumn] trimmedFirst, _ := strconv.ParseFloat(valueArrays[compareColOne], 64) trimmedSecond, _ := strconv.ParseFloat(valueArrays[compareColTwo], 64) diff := trimmedFirst - trimmedSecond diff = math.Abs(diff) if diff <= minimum { minimum = diff data.columnName = name data.compareOne = trimmedFirst data.compareTwo = trimmedSecond } } return data } //ReadFile reads lines from a file and gives back a string array which contains the lines. func ReadFile(fileName string) (fileLines []string) { file, err := os.Open(fileName) if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) //Skipping the first line which is the header. scanner.Scan() for scanner.Scan() { line := scanner.Text() re := regexp.MustCompile("\\w+") lines := re.FindAllString(line, -1) if len(lines) > { fileLines = append(fileLines, strings.Join(lines, ",")) } } if err := scanner.Err(); err != nil { log.Fatal(err) } return }

October 4, 2015 · 2 min · hannibal

How to Aggregate Tests with Jenkins with Aggregate Plugin on non-relating jobs

Hello folks. Today, I would like to talk about something I came in contact with, and was hard to find a proper answer / solution for it. So I’m writing this down to document my findings. Like the title says, this is about aggregating test result with Jenkins, using the plug-in provided. If you, like me, have a pipeline structure which do not work on the same artifact, but do have a upstream-downstream relationship, you will have a hard time configuring and making Aggregation work. So here is how, I fixed the issue. ...

October 2, 2015 · 4 min · hannibal

Sieve of Eratosthenes in Go

I’m pretty proud of this one as well. package sieve //Sieve Uses the Sieve of Eratosthenes to calculate primes to a certain limit func Sieve(limit int) []int { var listOfPrimes []int markers := make([]bool, limit) for i := 2; i < limit; i++ { if !markers[i] { for j := i + i; j < limit; j += i { markers[j] = true } listOfPrimes = append(listOfPrimes, i) } } return listOfPrimes }

July 30, 2015 · 1 min · hannibal

Quick Tip for Debugging Headless Locally

If you are installing something with Packer and you have Headless enabled(and you are lazy and don’t want to switch it off), it gets difficult, to see output. Especially on a windows install the Answer File / Unattended install can be like => Waiting for SSH. for about an hour or two! If you are doing this locally fret not. Just start VirtualBox, and watch the Preview section which will display the current state even if it’s a headless install! ...

July 22, 2015 · 1 min · hannibal

Converting numbers into string representations

I quiet like this one. My first go program snippet without any peaking or googling. I’m proud, though it could be improved with a bit of struct magic and such and such. And it only counts ’till 1000. package main import "fmt" var words = map[int]string{1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten", 11: "eleven", 12: "twelve", 13: "thirteen", 14: "fourteen", 15: "fifteen", 16: "sixteen", 17: "seventeen", 18: "eighteen", 19: "nineteen", 20: "twenty", 30: "thirty", 40: "forty", 50: "fifty", 60: "sixty", 70: "seventy", 80: "eighty", 90: "ninety"} // CountLetters count the letters in a long string number representation func CountLetters(limit int) { myLongNumberString := "" for i := 1; i <= limit; i++ { addLettersToMyString(&myLongNumberString, i) } // fmt.Println("1-9 written with letters is: ", len(myLongNumberString)) fmt.Println("The string is:", myLongNumberString) fmt.Println("Lenght of string is:", len(myLongNumberString)) } func addLettersToMyString(myString *string, num int) { if num < 20 { *myString += words[num] } if num >= 20 && num < 100 { *myString += countMiddle(num) } if num >= 100 && num < 1000 { hundred, tenth := countHundred(num) if tenth == { *myString += hundred } else if tenth >= 11 && tenth < 20 { *myString += hundred + "and" + words[tenth] } else { *myString += hundred + "and" + countMiddle(tenth) } } if num == 1000 { *myString += "onethousand" } } func countMiddle(num int) string { minues := num % 10 num -= minues return words[num] + words[minues] } func countHundred(num int) (string, int) { minues := num % 100 num -= minues return (words[(num/100)] + "hundred"), minues }

July 19, 2015 · 2 min · hannibal

Selenium Testing with Packer and Vagrant

So, recently, the tester team talked to me, that their build takes too long, and why is that? A quick look at their configuration and build scripts showed me, that they are actually using a vagrant box, which never gets destroyed or re-started at least. To remedy this problem, I came up with the following solution. ...

July 16, 2015 · 7 min · hannibal

Packer 0.8.1.

Previously I wrote that the scripts I’m writing, are failing because Packer hangs. Apparently, this was a known issue. And apparently, I was using an older version, 0.7.5. After I updated everything is working wonderfully!!! And for my thanks, here is an updated PowerShell script for provisioning my dotnet stuff. $source = "http://download.microsoft.com/download/1/6/7/167F0D79-9317-48AE-AEDB-17120579F8E2/NDP451-KB2858728-x86-x64-AllOS-ENU.exe" $destination = "C:\Windows\Temp\dotnet.exe" Write-Host 'Starting to download dotnet file.' try { (New-Object System.Net.WebClient).DownloadFile($source, $destination) } catch [Exception] { Write-Host "Exception during download. Probable cause could be that the directory or the file didn't exist." Write-Host '$_.Exception is' $_.Exception } Write-Host 'Download done. Checking if file exists.' if (!(Test-Path $destination)) { Write-Host 'Downloading dotnet Failed!' } else { Write-Host 'Download successful.' } Write-Host 'Starting install process.' try { Start-Process -FilePath $source -ArgumentList "/q /norestart" -Wait -PassThru } catch [Exception] { Write-Host 'Exception during install process.' Write-Host '$_.Exception is' $_.Exception } Write-Host 'All done. Goodbye.' Thanks for reading! ...

July 1, 2015 · 1 min · hannibal

Powershell can also be nice -Or Installing Java silently and waiting

Hello folks. Today, I would like to show you a small script. It installs Java JDK, both version, x86 and 64 bit, silently, and wait for that process to finish. The wait is necessary because /s on a java install has the nasty habit of running in the background. If you are using a .bat file, you shouldn’t, than you would use something like: start /w jdk-setup.exe /s. This gets it done, but is ugly. Also, if you are using Packer and PowerShell provisioning, you might want to set up some environment variables as well for the next script. And you want that property to be available and you don’t want to mess it up with setting a path into a file and then re-setting your path on the begin of your other script. Or pass it around with Packer. No. Use a proper PowerShell script. Learn it. It’s not that hard. Be a professional. Don’t hack something together for the next person to suffer at. ...

June 30, 2015 · 3 min · hannibal