Skip to content

Instantly share code, notes, and snippets.

@soruly
Last active May 29, 2020 14:29
Show Gist options
  • Save soruly/5bcdc14ddfccf8fefe9fbefaaeb05853 to your computer and use it in GitHub Desktop.
Save soruly/5bcdc14ddfccf8fefe9fbefaaeb05853 to your computer and use it in GitHub Desktop.
Various scripts for demo
#!/bin/bash
CHECK_DELAY=${CHECK_DELAY:-7}
CHECK_IP1=${CHECK_IP1:-8.8.8.8}
CHECK_IP2=${CHECK_IP2:-8.8.4.4}
PRIMARY_IF=${PRIMARY_IF:-enp4s0}
PRIMARY_GW=${PRIMARY_GW:-192.168.2.1}
BACKUP_IF=${BACKUP_IF:-eno1}
BACKUP_GW=${BACKUP_GW:-192.168.1.1}
HOSTNAME=${HOSTNAME:-socky}
is_gateway() {
[[ "$1" = "$(ip route show default 0.0.0.0/0 | cut -d' ' -f5)" ]]
}
curl --silent --header 'Access-Token: ' \
--header 'Content-Type: application/json' \
--data-binary '{"body":"Socky has just started or rebooted.","title":"Socky has started","type":"note"}' \
--request POST https://api.pushbullet.com/v2/pushes > /dev/null
ip rule del table t1
ip rule del table t2
ip rule add from 192.168.1.10 table t1
ip rule add from 192.168.2.10 table t2
while sleep "$CHECK_DELAY"
do
ip route add 192.168.1.0 dev $BACKUP_IF src 192.168.1.10 table t1 &>/dev/null
ip route add 192.168.2.0 dev $PRIMARY_IF src 192.168.2.10 table t2 &>/dev/null
ip route add $CHECK_IP1 via $BACKUP_GW dev $BACKUP_IF src 192.168.1.10 table t1 &>/dev/null
ip route add $CHECK_IP1 via $PRIMARY_GW dev $PRIMARY_IF src 192.168.2.10 table t2 &>/dev/null
ip route add $CHECK_IP2 via $BACKUP_GW dev $BACKUP_IF src 192.168.1.10 table t1 &>/dev/null
ip route add $CHECK_IP2 via $PRIMARY_GW dev $PRIMARY_IF src 192.168.2.10 table t2 &>/dev/null
ip route add default via $BACKUP_GW table t1 &>/dev/null
ip route add default via $PRIMARY_GW table t2 &>/dev/null
# ip route add 192.168.1.0/24 dev eno1 src 192.168.1.10 metric 100 &>/dev/null
# ip route add 192.168.2.0/24 dev enp4s0 src 192.168.2.10 metric 100 &>/dev/null
# ip rule add from 192.168.1.10 table t1
# ip rule add from 192.168.2.10 table t2
ip route add $CHECK_IP1 via $BACKUP_GW metric 1 &>/dev/null
ip route add $CHECK_IP1 via $PRIMARY_GW metric 2 &>/dev/null
ip route add $CHECK_IP2 via $BACKUP_GW metric 1 &>/dev/null
ip route add $CHECK_IP2 via $PRIMARY_GW metric 2 &>/dev/null
PRIMARY_DOWN=1
BACKUP_DOWN=1
if ping -I "$PRIMARY_IF" -c1 -W1 "$CHECK_IP1" &>/dev/null
then
if ping -I "$PRIMARY_IF" -c1 -W1 "$CHECK_IP2" &>/dev/nulli
then
PRIMARY_DOWN=0
else
PRIMARY_DOWN=1
fi
else
PRIMARY_DOWN=1
fi
if ping -I "$BACKUP_IF" -c1 -W1 "$CHECK_IP1" &>/dev/null
then
if ping -I "$BACKUP_IF" -c1 -W1 "$CHECK_IP2" &>/dev/null
then
BACKUP_DOWN=0
else
BACKUP_DOWN=1
fi
else
BACKUP_DOWN=1
fi
if [ $PRIMARY_DOWN -eq 0 ]
then
echo Primary Interface is up
if is_gateway "$BACKUP_IF"
then
echo Switch back to Primary Interface
ip route del default via "$BACKUP_GW" dev "$BACKUP_IF"
ip route add default via "$PRIMARY_GW" dev "$PRIMARY_IF"
curl --silent --header 'Access-Token: ' \
--header 'Content-Type: application/json' \
--data-binary '{"body":"Socky Primary Interface is back online","title":"Socky switched back to Primary Interface","type":"note"}' \
--request POST https://api.pushbullet.com/v2/pushes > /dev/null
fi
elif [ $BACKUP_DOWN -eq 0 ]
then
echo Primary Interface is down
echo Backup Interface is up
if is_gateway "$PRIMARY_IF"
then
echo Switch to Backup Interface
ip route del default via "$PRIMARY_GW" dev "$PRIMARY_IF"
ip route add default via "$BACKUP_GW" dev "$BACKUP_IF"
curl --silent --header 'Access-Token: ' \
--header 'Content-Type: application/json' \
--data-binary '{"body":"Socky Primary Interface is down","title":"Socky switched to Backup Interface","type":"note"}' \
--request POST https://api.pushbullet.com/v2/pushes > /dev/null
fi
else
echo All Interface are down
fi
done
// https://github.com/douglascrockford/monad
function MONAD(){
return function unit(value) {
var monad = Object.create(null);
monad.bind = function (func) {
return func(value);
}
return monad;
}
}
var unit = MONAD();
var monad = unit("Hello monad!");
monad.bind(console.log);
const crypto = require('crypto')
const fetch = require('node-fetch')
const { execSync } = require('child_process')
const names = {
'10002000': 'ゆの',
'11002000': '野々原ゆずこ',
'12002000': '丈槍由紀',
'13002000': 'トオル',
'14002000': '九条カレン',
'15002000': '涼風青葉',
'16002000': '本田珠輝',
'17002000': '千矢',
}
const sessionId = '77ae1cef-3243-4ff7-8ff3-4b4aa1d5ff57'
const hash = '1b985f1c8ff88890f1fef6f7a6fc1206787d8f2f96faff8c18c23e996c9fffff'
async function draw() {
const url = 'https://krr-prd.star-api.com/api/player/gacha/draw'
const headers = {
'Host': 'krr-prd.star-api.com',
'X-STAR-SESSION-ID': sessionId,
'X-STAR-REQUESTHASH': hash,
'Accept': '*/*',
'X-Unity-Version': '5.5.4f1',
'Unity-User-Agent': 'app/0.0.0; Android OS 6.0.1 / API-23 23.5.A.1.292/3701784398; Sony SGP628',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-us',
'Content-Type': 'application/json; charset=UTF-8',
'Content-Length': '53',
'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 6.0.1; SGP628 Build/23.5.A.1.292)',
'X-STAR-AB': '3',
}
const body = '{"gachaId":1,"drawType":3,"stepCode":0,"reDraw":true}'
const text = await fetch(url, {method: 'POST', headers, body})
const res = await text.json()
if (res.resultCode !== 0 && res.resultCode !== 105) {
execSync(`sendemail -f "demo@gmail.com" -t "demo@gmail.com" -u "kirara draw failed" -s "smtp.gmail.com:587" -o tls=yes -xu "demo@gmail.com" -xp "ftwfazvfqtghjzw" -m "server return resultCode: ${res.resultCode}"`)
return true
}
let characters = []
if (res.managedCharacters) {
characters = res.managedCharacters.map(c => {
const {characterId, levelLimit} = c
const ret = {characterId, levelLimit}
if (names[characterId]) {
ret.name = names[characterId]
}
if (levelLimit === 40) {
ret.SILVER = true
}
if (levelLimit === 50) {
ret.GOLD = true
}
return ret
})
}
const golds = characters.filter(c => !!c.GOLD).length
const silvers = characters.filter(c => !!c.SILVER).length
const unknownGold = characters.filter(c => !!c.GOLD && !c.name).length
// const stop = characters.filter(c => c.characterId === 17002000).length > 0 && characters.filter(c => c.characterId === 10002000).length > 0
const stop = golds >= 3 ? true : false
const log = `${new Date()} code ${res.resultCode.toString().padStart(3, " ")}, ${golds} Gold ${silvers} Silver, ${characters.filter(c => !!c.GOLD).map(c => names[c.characterId])}`
console.log(log)
if (stop) {
console.log(characters)
execSync(`sendemail -f "demo@gmail.com" -t "demo@gmail.com" -u "kirara draw completed" -s "smtp.gmail.com:587" -o tls=yes -xu "demo@gmail.com" -xp "ftwfazvfqtghjzw" -m "${log}"`)
}
return stop
}
function sleep() {
return new Promise((resolve, reject) => {
setTimeout(resolve, Math.random() * 5000 + 15000)
})
}
async function main() {
let stop = false
while (!stop) {
stop = await draw()
await sleep()
}
}
main()
function MONAD(){
var proto = Object.create(null);
function unit(value) {
var monad = Object.create(proto);
monad.bind = function (func, ...args) {
return func(value, ...args);
}
return monad;
}
unit.lift = function (name, func) {
proto[name] = function (...args) {
return unit(this.bind(func, ...args));
};
return unit;
}
return unit;
}
var ajax = MONAD()
.lift('log', console.log)
.lift('warn', console.warn);
var monad = ajax("Hello monad!");
//monad.bind(console.log);
monad.log().warn();
function MONAD(modifier){
var proto = Object.create(null);
function unit(value) {
var monad = Object.create(proto);
monad.bind = function (func, ...args) {
return func(value, ...args);
}
if (typeof modifier === 'function') {
modifier(monad, value);
}
return monad;
}
unit.lift = function (name, func) {
proto[name] = function (...args) {
return unit(this.bind(func, ...args));
};
return unit;
}
return unit;
}
var maybe = MONAD(function (monad, value) {
if (value === null || value === undefined) {
monad.is_null = true;
monad.bind = function () {
return monad;
}
}
});
var monad = maybe("Hello monad!");
monad.bind(console.log);
var monad2 = maybe(null);
monad2.bind(console.log);
npm command dependencies devDependencies optionalDependencies
npm install yes yes yes
npm install --no-optional yes yes no
npm install --only=dev no yes no
npm install --only=dev --no-optional no yes no
npm install --only=prod yes no yes
npm install --only=prod --no-optional yes no no

Note: You have to ensure package-lock.json and npm-shrinkwrap.json does not exist before running npm install

Or you can to use --no-package-lock and --no-shrinkwrap to ignore these files

package main
import (
"sync"
"bufio"
"fmt"
"strings"
"os"
"os/exec"
"time"
)
func worker (id int, ipPools <-chan string, results chan<- string, wg *sync.WaitGroup) {
defer wg.Done()
for ip := range ipPools {
fmt.Printf("[Worker %d] started job %s\n", id, ip)
cmdName := "ping"
cmdArgs := []string{"-c", "3", ip}
cmd := exec.Command(cmdName, cmdArgs...)
cmdReader, err := cmd.StdoutPipe()
if err != nil {
fmt.Fprintln(os.Stderr, "Error creating StdoutPipe for Cmd", err)
os.Exit(1)
}
scanner := bufio.NewScanner(cmdReader)
go func() {
for scanner.Scan() {
str := fmt.Sprintf("[Worker %d] %s",id,strings.TrimSpace(scanner.Text()))
results <- str
}
}()
err = cmd.Start()
if err != nil {
fmt.Fprintln(os.Stderr, "Error starting Cmd", err)
os.Exit(1)
}
err = cmd.Wait()
fmt.Printf("[Worker %d] finished job %s\n", id, ip)
if err != nil {
fmt.Fprintln(os.Stderr, "Error waiting for Cmd", err)
os.Exit(1)
}
}
}
func main() {
// In order to use our pool of workers we need to send
// them work and collect their results. We make 2
// channels for this.
ips := []string{"8.8.8.8", "127.0.0.1", "192.168.1.1", "8.8.4.4"}
jobs := make(chan string, len(ips))
results := make(chan string, len(ips))
var wg sync.WaitGroup
for w := 0; w < 3; w++ {
wg.Add(1)
go worker(w, jobs, results, &wg)
}
fmt.Println("Waiting for jobs...")
time.Sleep(1000 * time.Millisecond)
for j := 0; j < len(ips); j++ {
jobs <- ips[j]
}
close(jobs)
go func(){
for str := range results {
fmt.Println(str)
}
}()
wg.Wait()
}
#!/usr/bin/env bash
message="Message"
link="http://example.com"
name="Name"
description="Description"
caption="Caption"
user_agent="Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"
login_uri="https://www.facebook.com/login.php?login_attempt=1"
auth_uri="https://www.facebook.com/dialog/oauth"
token_uri="https://graph.facebook.com/v2.10/oauth/access_token"
facebook_app_id="1472985981958128907423"
facebook_app_secret="cb86aa39287cb98a0981cba"
oauth_redirect_uri="http://example.com"
facebook_group_id="39148591085"
facebook_group_feed_url="https://graph.facebook.com/v2.10/$facebook_group_id/feed"
facebook_username="yourfacebookemail@example.com"
facebook_password="password"
session_file="/tmp/session.json"
rm $session_file
http --ignore-stdin --session=$session_file --print=H GET $login_uri "user-agent:$user_agent"
http --ignore-stdin --session=$session_file --print=H -f POST $login_uri \
"email=$facebook_username" \
"pass=$facebook_password"
code=$(http --ignore-stdin --session=$session_file --print=h GET $auth_uri \
"client_id==$facebook_app_id" \
"redirect_uri==$oauth_redirect_uri" \
| grep Location: \
| awk -F"code=" '{print $2}' \
)
#echo $code
access_token=$(http --ignore-stdin --session=$session_file -b GET $token_uri \
"client_id==$facebook_app_id" \
"redirect_uri==$oauth_redirect_uri" \
"client_secret==$facebook_app_secret" \
"code==$code" \
| jq --raw-output .access_token \
)
#echo $access_token
http --ignore-stdin --session=$session_file -v -f POST $facebook_group_feed_url \
"access_token==$access_token" \
"message=$message" \
"link=$link" \
"name=$name" \
"description=$description" \
"caption=$caption" \
mkdir "$(date "+%Y-%m-%d")"
flameshot full --raw | convert - -quality 90 "$(date "+%Y-%m-%d")"/"$(date "+%Y-%m-%d %H %M %S")".jpg
#crontab
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
MAILTO=""
* * * * * cd /home/soruly/printscreendiary/ && ./printscreen.sh && sleep 14 && ./printscreen.sh && sleep 14 && ./printscreen.sh && sleep 14 && ./printscreen.sh
#https://httpie.org/
#!/usr/bin/env bash
title="$(df -h /mnt/snowy/Data/ | tail -n 1 | tr -s ' ' | cut -d ' ' -f 4)B free space left"
body=""
http POST https://api.pushbullet.com/v2/pushes \
Access-Token:o.asiodhfoasdghaskldfhiuhaiuhfu \
title="$title" body="$body" type="note"
#!/usr/bin/env bash
title="$(df -h /mnt/snowy/Data/ | tail -n 1 | tr -s ' ' | cut -d ' ' -f 4)B free space left"
body=""
curl --header 'Access-Token: o.asiodhfoasdghaskldfhiuhaiuhfu' \
--header 'Content-Type: application/json' \
--data-binary '{"body":"'"$body"'","title":"'"$title"'","type":"note"}' \
--request POST \
https://api.pushbullet.com/v2/pushes
#echo 201 t1 >> /etc/iproute2/rt_tables
#echo 202 t2 >> /etc/iproute2/rt_tables
ip rule del table t1
ip rule del table t2
ip route add 192.168.1.0/24 dev enp5s0 src 192.168.1.10 table t1
ip route add 192.168.2.0/24 dev enp4s0 src 192.168.2.10 table t2
ip route add default via 192.168.1.1 table t1
ip route add default via 192.168.2.1 table t2
ip rule add from 192.168.1.10 table t1
ip rule add from 192.168.2.10 table t2
#nmcli connection show
#nmcli connection modify "Wired connection 1" ipv4.never-default true
#!/usr/bin/env bash
while IFS= read -rd '' file; do
dirname="${file%/*}"
basename="${file##*/}"
mv --backup=numbered -- "${file}" "${dirname}/${basename//|/_}"
done < <(find /run/media/soruly/Data/music -depth -name '*|*' -print0)

Various scripts for demo

parallel-ping.go

Ping a few IP address in parallel with Go routine

sanitize-filename.sh

Check malformed filenames and rename with _

post_to_facebook_group.sh

Post a message to facebook group in shell script using HTTPie and jq

failover.sh

Switch to secondary network interface and secondary default gateway when primary interface has no internet connection. Also sent a pushbullet notification for the event.

#!/usr/bin/env bash
push () {
title="$1"
body="$2"
curl --header 'Access-Token: o.uuuuuuuuuuuuuuuuuuuuuuuuuuuuu' \
--header 'Content-Type: application/json' \
--data-binary '{"body":"'"$body"'","title":"'"$title"'","type":"note"}' \
--request POST \
https://api.pushbullet.com/v2/pushes
}
export -f push
num_of_new_sukebei=$(find /mnt/data/download/sukebei/ -mindepth 1 -maxdepth 1 -type d -mmin -60 | wc -l)
if [[ $num_of_new_sukebei -gt "0" ]] ; then
find /mnt/data/download/sukebei/ -mindepth 1 -maxdepth 1 -type d -mmin -60 -exec bash -c 'push "$0" "$(basename $1)"' "New Sukebei released" {} \;
fi
num_of_new_anime=$(find /mnt/data/anime/ -type f -name "*.mp4" -mmin -360 | wc -l)
if [[ $num_of_new_anime -eq "0" ]] ; then
push "No new anime last 6 hours" $(find /mnt/data/download/anime/)
fi
num_of_new_hash=$(find /mnt/data/anilist_hash/ -type f -name "*.xml.xz" -mmin -240 | wc -l)
if [[ $num_of_new_hash -eq "0" ]] ; then
push "No new hash last 4 hours" ""
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment