You are not logged in.

#3201 2018-10-03 13:58:49

eschwartz
Fellow
Registered: 2014-08-08
Posts: 4,097

Re: Post your handy self made command line utilities

Trilby wrote:

Eschwartz, to be fair, they didn't sed pacman.conf themselves.  They read pacman.conf line by line in a clumsy and pointless loop and sed''ed part of each line for no reason only to check whether it matched 'IgnorePkg' and then only to oddly and conditionally append a space then a value to a simple variable when an array would be much easier needing no conditional or spaces.

And this is you being "fair"... tongue

Honest, yes, I will grant you that. But generally the phrase "to be fair" is used by people extending mercy, not additional objections. big_smile

If pacman-conf were not an option, that entire loop could just be:

IGNORE=$(sed -n 's/^IgnorePkg[^=]*=//p' /etc/pacman.conf)
# or better as an array
IGNORE=($(sed -n 's/^IgnorePkg[^=]*=//p' /etc/pacman.conf))

If it comes to that, matching on 'IgnorePkg222 = nope' and finding that the "nope" package should be ignored, is rather erroneous...

Don't match:

^IgnorePkg[^=]*=

Do match:

^IgnorePkg[[:space:]]*=

Managing AUR repos The Right Way -- aurpublish (now a standalone tool)

Offline

#3202 2018-10-03 14:01:01

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 30,330
Website

Re: Post your handy self made command line utilities

Good revision to my sed command.  To be fair, I'm an idiot. tongue


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#3203 2018-10-03 15:31:43

Crouze
Member
Registered: 2017-10-04
Posts: 13

Re: Post your handy self made command line utilities

And to be fair, learned something new again today. Of course there was an easier way wink

Offline

#3204 2018-10-05 08:47:36

kokoko3k
Member
Registered: 2008-11-14
Posts: 2,420

Re: Post your handy self made command line utilities

I've found this nice site that is missing an rss but gives you updates about new free games, so i wrote a little script that checks it and send me a notification when there is a new free game; didn't tested it deeply... yet!
It uses the handy "sendemail" tool from aur.

#!/bin/bash
wdir=/koko/scripts/gamecheck
f1="$wdir/1.txt"
f2="$wdir/2.txt"
mkdir "$wdir" &>/dev/null
interval=7200 #secs

function notify() {
	 /usr/bin/sendEmail \
		-f source_email@gmail.com \
		-t dest_email@gmail.com \
		-s smtp.gmail.com:25 \
		-xu gmail_username \
		-xp gmail_password \
		-u "GameCheck" \
		-m "New updates on: https://givemekey.com/?s=" 
}

function check_out() {
	curl "https://givemekey.com/?s=" |\
		tr "<" "\n"|\
		grep free |\
		grep "title\=" |\
		cut -d \" -f 2
}

check_out > "$f1"

while true ; do
	sleep $interval
	check_out > "$f2"
	if [ $(<"$f1") != $(<"$f2") ] ; then
		notify "$f2"
	fi
	cp "$f2" "$f1"
done

...and a systemd service as well

[Unit]
Description=Check for free games

[Service]
Type=simple
ExecStart=/home/koko/scripts/gamecheck.sh

[Install]
WantedBy=default.target

Last edited by kokoko3k (2018-10-05 08:55:15)


Help me to improve ssh-rdp !
Retroarch User? Try my koko-aio shader !

Offline

#3205 2018-10-24 13:28:47

kokoko3k
Member
Registered: 2008-11-14
Posts: 2,420

Re: Post your handy self made command line utilities

This one will set the same "custom" refresh and resolution for all of the connected monitors.
I use it as a convenient way to play games with lower refresh rates when my GPU can't handle more.

#!/bin/bash

if [ ! $# = 2 ] ; then
	echo Example $(basename $0) 1280x1024 75
	exit
fi

w=$(cut -d "x" -f 1 <<< "$1")
h=$(cut -d "x" -f 2 <<< "$1")
hz=$2

#Genera la modeline
	GTF_OUT=$(gtf $w $h $hz|grep Modeline)
	MODE_NAME=koko_"$w"x"$h"_"$hz"
	TIMINGS=$(grep Modeline <<< $GTF_OUT |cut -d \" -f 3)
	MODELINE="$MODE_NAME $TIMINGS"

#aggiungo al pool:
	xrandr --newmode $MODELINE
	
#Aggiunge e setta il modo custom a tutti i monitor
	MONITORS=$(xrandr|grep " conne"|cut -d " " -f 1|tr \\n " ") 

	for MONITOR in $MONITORS ; do
		xrandr --addmode $MONITOR $MODE_NAME
		xrandr --output $MONITOR --mode $MODE_NAME
	done

	echo "Press ENTER in 10 seconds to keep settings"
	read -n 1 -t 10
	if [ ! $? == 0 ]; then
		#Cleanup:
		for MONITOR in $MONITORS ; do
			xrandr --output $MONITOR --preferred
			xrandr --delmode $MONITOR $MODE_NAME
			xrandr --rmmode $MODE_NAME
		done
	fi

EDIT:
removed 2 useless echo, before someone pointed it out; ready for the next tongue

Last edited by kokoko3k (2018-10-24 13:33:43)


Help me to improve ssh-rdp !
Retroarch User? Try my koko-aio shader !

Offline

#3206 2018-10-24 13:59:36

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 30,330
Website

Re: Post your handy self made command line utilities

You seem to do a lot of munging of variables only to undo it later.  For example, you have a subshell and pipeline to extract the width an height from $1, but then later you use "$w"x"$h" to put them back together.  You only need the individual width and height values once, so just extract them there, and use shell builtins to do it, e.g.:

timings=$(gtf ${1%x*} ${1#*x} $2 | awk '/Modeline/ { print $3; }')

Also note, the use of awk instead of grep and cut.
I can't test it, but the following should do the same thing as your script:

#!/bin/sh

if [ ! $# = 2 ] ; then
	echo Example $(basename $0) 1280x1024 75
	exit
fi

modename="koko_$1_$2"

xrandr --newmode $modename "$(gtf ${1%x*} ${1#*x} $2 |  awk '/Modeline/ { $1=""; $2=""; print; }')"

monitors=$(xrandr | awk '/ connected/ { print $1; }')

for monitor in $monitors; do
	xrandr --addmode $monitor $modename
	xrandr --output $monitor --mode $modename
done

read -p "Press ENTER in 10 seconds to keep settings" -n 1 -t 10 && exit

for monitor in $monitors; do
	xrandr --output $monitor --preferred
	xrandr --delmode $monitor $modename
done
xrandr --rmmode $modename

One thing that stands out is that almost all of the output of gtf is completely ignored - only the timing value is extracted and passed to xrandr's --newmode.  Is this really how that should work? (edit: ah, I misunerstood your cut pipeline, I've modified my version to get the equivalent output from gtf.)

Last edited by Trilby (2018-10-24 14:05:48)


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#3207 2018-10-24 14:19:26

kokoko3k
Member
Registered: 2008-11-14
Posts: 2,420

Re: Post your handy self made command line utilities

Trilby wrote:

You seem to do a lot of munging of variables only to undo it later.

D'oh, you're right ^_^

Also note, the use of awk instead of grep and cut.

Unfortunately i'm not really familiar with it; i've to sort it out.

...apart from that, i prefer to use more and descriptive variables so that i'll not spend too much time next time to understand what i wrote.


Help me to improve ssh-rdp !
Retroarch User? Try my koko-aio shader !

Offline

#3208 2018-10-24 14:39:22

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 30,330
Website

Re: Post your handy self made command line utilities

You can still name variables and be more verbose than my examples without needing to use subshells with long pipelines:

...

width=${1%x*}
height=${1#*x}

timings=$(gtf $width $height ...)

My personal style is to never create a variable for something that will only be used once, unless the calculation of the value is pretty complex so that splitting off the calculation (and assignment) to a new line makes it easier to read.  In this case "${1%x*}" is quite short, and never reused, so I'd personally not use a variable for it - but that's a stylistic choice.


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#3209 2018-11-13 12:25:00

sjmulder
Member
Registered: 2018-11-13
Posts: 11

Re: Post your handy self made command line utilities

Man I just love writing little programs. Here's a few that may be useful:

json-yaml

Converts JSON to YAML for easy reading (or further processing):

$ curl -s http://api.icndb.com/jokes/random | ./json-yaml
type: success
value:
  id: 415
  joke: When Chuck Norris wants an egg, he cracks open a chicken.
  categories: []
nostt

A command line NOS Teletekst reader (a Dutch teletext system, like BBC's Ceefax).

within

My favourite one. Run a command in other directories:

$ within code/* - git status
code/json-yaml: nothing to commit, working tree clean
code/nostt: nothing to commit, working tree clean
code/within: nothing to commit, working tree clean
code/dated: nothing to commit, working tree clean
dated

Adds a timestamp to every line:

$ tail -f test.txt | dated
11/07/18 21:28:31 Hello
11/07/18 21:28:40 World!
$ tail -f test.txt | dated -f "[%H:%M] "
[21:32] Hello
[21:33] World!

Of course there are AUR packages for all of them big_smile

Offline

#3210 2018-11-25 21:33:33

brett
Member
Registered: 2018-04-21
Posts: 4

Re: Post your handy self made command line utilities

I like to have these functions loaded at login (i have them in my .aliases file) to have them at the ready:

This one helps me quickly fire up a new database to quickly start a new project

function mkdb() {
echo
if [ 2 -gt  $# ] ;then 
      echo "mkdb - invalid parameters"
      echo "** usage: mkdb database_name [user_name] password"
      echo "** if user_name is not specified database_name will be used also for user_name"
else
	db_name=$1

	if [ $# -gt 2 ]
	then
		user_name=$2
		pass=$3
	else
		user_name=$1
		pass=$2
	fi

	echo
	echo "Creating database '$db_name' and user '$user_name' and granting access to database to the new user."
	
	mysql -u root  --execute="CREATE USER IF NOT EXISTS '$user_name'@'localhost' IDENTIFIED BY '$pass';GRANT USAGE ON *.* TO '$user_name'@'localhost' REQUIRE NONE WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;CREATE DATABASE IF NOT EXISTS $db_name;GRANT ALL PRIVILEGES ON $db_name.* TO '$user_name'@'localhost';"
fi
echo 
}

This one I use to swap hosts lists based on my needs: when developing I like to have all my project domains pointing to 127.0.0.1, and when I deploy i like to see them live. This makes the deploy easier, no need to search and replace for 'localhost' in the project files (or db dump).

#rotate hosts files
function chost {
  set -e # stop running if we encounter an error
  if [[ ! -f  /etc/hostssecondary ]]; then
      sudo \touch /etc/hostssecondary
  fi  
  echo
  echo --------------------------------------------
  sudo \mv -f /etc/hosts /etc/hoststempname
  sudo \mv -f /etc/hostssecondary /etc/hosts
  sudo \mv -f /etc/hoststempname /etc/hostssecondary
  set +e
  cat /etc/hosts
  echo
  echo --------------------------------------------
  echo
}

Offline

#3211 2018-11-25 21:48:11

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 30,330
Website

Re: Post your handy self made command line utilities

You could just set pass to the last argument, user to the first argument, then really simplify that conditional to a single line:

[ $# -gt 2 ] && user_name=$2

If you are using BASH getting the last argument is just array manipulation, but from the single [ I'd gather you may not be using (exclusively) BASH, so you can use a for loop:

db_name= $1
user_name=$1
[ $# -gt 2 ] && user_name=$2
for arg; do :; done
pass=$arg

Last edited by Trilby (2018-11-25 22:40:08)


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#3212 2018-11-25 21:59:01

brett
Member
Registered: 2018-04-21
Posts: 4

Re: Post your handy self made command line utilities

great tips, thanks

for the first one, i'd normally add the optional parameter at the end, but in this case I rather wanted to have the natural flow of thought on usage, even if it meant I'd have to do a bit of code acrobatics for this end.

Offline

#3213 2018-12-03 10:22:11

Stencon281
Member
Registered: 2016-09-21
Posts: 40

Re: Post your handy self made command line utilities

I use emacs with transparency enabled and this script helps me follow tutorials / documentation more easily.

Seems a little esoteric, but it's really nice being able to switch focus to your webbrowser without losing site of your text editor and switch tabs, play/pause a video, go to a url, etc...

I have it bound to Hyper-w, pressing it once will switch focus to firefox, pressing it consecutively is the same as alt-tab selecting firefox.

#!/bin/bash

focus="$(xdotool getwindowfocus)"

# if firefox exists in the current desktop
firefox="$(xdotool search --desktop "$(xdotool get_desktop)" --name "Firefox")"

# if firefox is running
firefoxExists="$(wmctrl -l | grep Firefox)"

if [[ -z $firefoxExists ]];then
  # firefox isn't running, launch it
  firefox &
  wmctrl -a "Firefox"
  wmctrl -r "Firefox" -N "$BROWSER"
  
  # delay to account for button debounce
  
  sleep .5

elif [[ $firefox ]];then
  
  # firefox is running and exists in the current desktop
  
  visible="$(xdotool search --desktop "$(xdotool get_desktop)" --onlyvisible --name "Firefox")"
  exists="$(xdotool search --desktop "$(xdotool get_desktop)" --name "Firefox")"

  if (($firefox != $focus)); then
    
    # firefox isn't focused (or it could be minimized), raise it without
    # bringing it to the front of the window stack
    
    wmctrl -r "Firefox" -b add,below

  elif (($firefox == $focus)); then
    
    # firefox is focused, make it the top most window
    
    wmctrl -r "Firefox" -b remove,below
    xdotool search --desktop "$(xdotool get_desktop)" --name "Firefox" windowraise
  fi
  
  # select window with the name "Firefox"
  
  wmctrl -a "Firefox"
fi

# wmctrl -r "Firefox" -N $BROWSER

Offline

#3214 2018-12-03 15:02:00

jasonwryan
Anarchist
From: .nz
Registered: 2009-05-09
Posts: 30,424
Website

Re: Post your handy self made command line utilities

Just install a tiling window manager tongue


Arch + dwm   •   Mercurial repos  •   Surfraw

Registered Linux User #482438

Offline

#3215 2018-12-03 15:09:46

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 30,330
Website

Re: Post your handy self made command line utilities

emacs is a tiling window manager among many other things, isn't it?

Install a good tiling window manager (and a text edtior while you're at it! tongue )

Last edited by Trilby (2018-12-03 15:10:11)


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#3216 2018-12-04 08:24:47

Stencon281
Member
Registered: 2016-09-21
Posts: 40

Re: Post your handy self made command line utilities

jasonwryan wrote:

Just install a tiling window manager tongue

i just use xfwm since i prefer my windows full screened, seeing spaces between windows distracts me.

Trilby wrote:

emacs is a tiling window manager among many other things, isn't it?

Install a good tiling window manager (and a text edtior while you're at it! tongue )

the defaults for all text editors are bad, i use my own superior version of emacs, which is more of a work of art (as intended) than it is some finely tuned work tool with the specifications of its original maker

all in all my script could use a little work now that i'm looking closely at it... hrmmmm..... also using terminal text editors feels so clunky after i've experienced the full power of the gui!

Offline

#3217 2018-12-04 15:57:19

quequotion
Member
From: Oita, Japan
Registered: 2013-07-29
Posts: 814
Website

Re: Post your handy self made command line utilities

Stencon281 wrote:

i just use xfwm since i prefer my windows full screened, seeing spaces between windows distracts me.

In compiz, you can use the "Place" and "Window Rules" plugins to mandate certain programs to open on specific viewports and always be fullscreen. It also has a handy drop-zone tiling plugin, and you can see through windows using the "Opacity, Brightness, and Saturation" plugin. In addition, all desktop and window management can be mouse-operated smile *never used emacs in my life*

more of a work of art (as intended) than it is some finely tuned work tool

For the artist who makes or modifies his own tools, is there a difference?

Last edited by quequotion (2018-12-04 15:58:29)

Offline

#3218 2018-12-04 20:49:55

InvisibleRasta
Member
Registered: 2017-04-12
Posts: 111

Re: Post your handy self made command line utilities

This is a script that i wrote for maintaining my gentoo boxes at home.nothing fancy, just makes everything a bit faster.

#!/bin/bash

# each item you want to prompt about in order
order=(eix revdep world depclean update ecleanpkg ecleandist news)

# prompt string hash for each item
declare -A prompts=(
	[eix]="Sync custom package repository and the Gentoo ebuild repository using eix"
	[revdep]="Check for and rebuild missing libraries (not normally needed)"
	[world]="Update world"
	[depclean]="Remove packages no longer needed"
	[update]="Manage configuration changes after an emerge completes"
	[ecleanpkg]="Cleaning packages"
	[ecleandist]="Clean the source files directory by passing the distfiles argument"
    [news]="Read news."
)

# the command for each item
eix=(eix-sync)
revdep=(revdep-rebuild -i -- -av)
world=(emerge -avuND @world)
depclean=(emerge -avc)
update=(etc-update)
ecleanpkg=(eclean-pkg)
ecleandist=(eclean-dist)
news=(eselect news read)

for item in "${order[@]}" ; do
	prompt="${prompts[$item]}"

	# don't try this at home
	eval "command=(\"\${$item[@]}\")"

	while read -n 1 -r -p "$prompt: (Y/n): " ; do
		case "$REPLY" in
			# permit the user to hit enter to get the default behavior
			[Yy]|'')
				# commands are always run with sudo
				sudo "${command[@]}"
				break
			;;
			[Nn])
				echo
				break
			;;
			*)
				printf '\nUnrecognized response "%s". please use Y or N\n' "$REPLY"
			;;
		esac
	done
done
 

Offline

#3219 2018-12-09 15:34:44

ugjka
Member
From: Latvia
Registered: 2014-04-01
Posts: 1,862
Website

Re: Post your handy self made command line utilities

Getting root ssh on my LTE modem/router https://github.com/ugjka/B593s-22_SSH


https://ugjka.net
paru > yay | vesktop > discord
pacman -S spotify-launcher
mount /dev/disk/by-...

Offline

#3220 2018-12-10 18:17:13

ackt1c
Banned
From: Visalia, California
Registered: 2012-10-10
Posts: 241

Re: Post your handy self made command line utilities

I'm still deciiding on a terminal emulator.

Last edited by ackt1c (2022-11-05 12:37:57)

Offline

#3221 2018-12-10 21:20:29

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 30,330
Website

Re: Post your handy self made command line utilities

Note that there is no need for those semicolons.  Nor is there a need for an exit command at the end of a script.  And with those two points there becomes no need for the script.  Just bind the command you want:

urxvt -g 20x8+1280 -e sh -c "cal && sleep 7"

"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#3222 2018-12-27 15:24:43

ugjka
Member
From: Latvia
Registered: 2014-04-01
Posts: 1,862
Website

Re: Post your handy self made command line utilities

wrote my own network speedtest server/client https://github.com/ugjka/speed
probably not the most advanced thing, but unlike speedtest-cli i can see the results in real time
also it was a fun exercise


https://ugjka.net
paru > yay | vesktop > discord
pacman -S spotify-launcher
mount /dev/disk/by-...

Offline

#3223 2019-01-10 16:50:07

qinohe
Member
From: Netherlands
Registered: 2012-06-20
Posts: 1,494

Re: Post your handy self made command line utilities

Hello Archers, it's been a while.
This is for using TCPLAY with multiple containers & paths, 1 or no key(mixed) and can (un)mount multiple containers, one by one!
There exist quite a few scripts for TCPLAY but far as I can tell, none of them handle key/key-less & multiple volumes in one go.
I use this for my NAS, which hasn't seen an update in almost 4 years:(.
It's also usable for local containers.

Edit this variable values:
cryptpath: where the encrypted containers are stored, do not remove parentheses.
mountp:    where the container will be mounted to, default is /mnt
keypath:   where your keys are stored, leaf empty for no keys
                 if you provide a keypath, you can still use key-less containers.
delay:       if your containers are on a NAS, the disks may enter 'sleep-state'
                example: mine needs less the 3 seconds to wake I set 'delay=3'

Alien files in the same directory with your containers will clutter the mount output(select)!
Containers with the same name in different directories are left out of 'mount' results until unmount.
For mount or unmount I show the encrypted containers name + path & f.i. not the mount point!

Have fun;) mark

#!/bin/bash
#set -xe
user=${SUDO_USER:-$(whoami)}

# edit the mext 4 values
cryptpath=(/home/"$user"/seahole/owned
           /home/"$user"/ctainers)
mountp=/mnt
keypath=
delay=0

# Edit with care below this line
trap 'rm -f "$tmpdev"' 0 1 2
tmpdev=$(tmpdev 2> /dev/null) || tmpdev=/tmp/tmpdev

[[ $EUID = 0 ]] || exit 1

# finds containers
_crmnt() {
   shopt -s nullglob
    mapfile -t crmnt < <( find "${cryptpath[@]}" -type f )
   shopt -u nullglob
 }

# choice list && final variables
_crdev() {
  select mnt in "${crmnt[@]}" exit; do
    case $mnt in
      exit) exit;;
         *) printf "%s\\n" "$mnt" > "$tmpdev"; break;;
    esac
  done
  cryptdev=$(basename "$(<"$tmpdev")")
  crpath=$(dirname "$(<"$tmpdev")")
}

_mount() {
  _crmnt

  mounted=$(find /dev/mapper -type l | awk -F '/' '{print $1 $NF}')

  for mnt in $mounted; do
    crmnt=(${crmnt[@]/*${mnt}*/})
  done

   _crdev

  loopdev=$(losetup -f)
  losetup "$loopdev" "$crpath"/"$cryptdev" || exit 1

  [[ -n $keypath ]] && read -r -s -p "key to use? [Enter for no key]: " key
  if [[ ! -z $key ]]; then
    tcplay -m "$cryptdev" -d "$loopdev" -k "$keypath"/"$key" || exit 1
  else
    tcplay -m "$cryptdev" -d "$loopdev" || exit 1
  fi

  [[ -d $mountp/$cryptdev ]] || mkdir "$mountp"/"$cryptdev"
  mount -o nodev,noexec /dev/mapper/"$cryptdev" "$mountp"/"$cryptdev"
}

_unmount() {
  _crmnt

  mounted=$(losetup -a | awk '{gsub(/\(|\)/,"",$3);print $3}')

  crmnt=()
  for mnt in $mounted; do
  for crt in "${crmnt[@]}"; do
    [[ $mnt == "$crt" ]] && continue 2
  done
    crmnt+=( "$mnt" )
  done

  _crdev

  umount "$mountp"/"$cryptdev" && sleep "$delay" || exit 1
  dmsetup remove "$cryptdev" || exit 1
  losetup -d "$(losetup -j "$crpath"/"$cryptdev" | awk -F ':' '{print $1}')"
}

if [[ $1 == m  ]]; then
  _mount
elif [[ $1 == u ]]; then
  _unmount
else
  printf "%s\\n" "Options: [ m <mount> ] [ u <unmount> ]"
fi

exit 0

Last edited by qinohe (2019-01-10 16:51:01)

Offline

#3224 2019-01-20 15:14:40

qinohe
Member
From: Netherlands
Registered: 2012-06-20
Posts: 1,494

Re: Post your handy self made command line utilities

Forgot to post this boot script I use together with the tcplay script in the previous post, it's for i3 and uses dmenu.
It prevents to reboot/poweroff if an device was found in '/dev/mapper' (function _inwork)

You would need to change things if you encrypt parts of the system, but since I don't...
Of course you don't need to use it this way but may give you an idea;)

#!/bin/sh
set -xe

if [ -f "$XDG_CONFIG_HOME"/dmenu/dmenurc ];then
  . "$XDG_CONFIG_HOME"/dmenu/dmenurc
else
  demcmdp='dmenu'
fi

_mounted() {
  eval|
  dmenu -fn 'Monospace-40:normal' -nb '#222222' -sb '#222222' \
  -sf '#da691c' -p 'cryptainer-mounted' -w '640' -x '660' -y '500'
}

_inwork() {
  [ ! -n "$(find /dev/mapper -type l)" ] && return || _mounted && exit 1
}

_pwr() {
pwr=$(echo "exit
logout
lock

reboot
suspend
hibernate

poweroff" \
| $demcmdp -l 10 -p 'Power:' -w '280')
}
_pwr

if [ "$pwr" = reboot ] || [ "$pwr" = poweroff ]; then
  _inwork
  systemctl "$pwr"
elif [ "$pwr" = logout ];then
  i3-msg exit
elif [ "$pwr" = exit ]; then
  pkill -15 -t tty"$XDG_VTNR" Xorg
elif [ "$pwr" = lock ]; then
  i3lock -u -c 222222 -i ~/scrot.png
elif [ "$pwr" = suspend ]; then
  i3lock && systemctl suspend
elif [ "$pwr" = hibernate ]; then
  i3lock && systemctl hibernate
fi

exit 0

Offline

#3225 2019-01-21 22:23:37

teckk
Member
Registered: 2013-02-21
Posts: 524

Re: Post your handy self made command line utilities

In the US, AT&T widely uses an Arris BGW210-700 Broadband
Gateway (home portal) for it's residential broadband VDSL,
and fiber customers. So it's likely that an arch user has one.

This simple script will view/save the firewall log out of it
without having to navigate the web interface for it, and
without having a syslog client running for it.

Bash, curl, and awk:

#! /usr/bin/bash

#Display firewall log data from Arris BGW210-700

#url of the gateway
url="http://192.168.0.1"

read -p $'Firewall log viewer for BGW210\n
View log or save to file? v or s: ' vs

case $vs in 
    [Vv]* ) curl "$url"/cgi-bin/logs.ha |
            awk -v OFS='\t' -F '[<|>]'\
                '/td/{print $9, $13, $17, $21, $25}'
            ;;
            
    [Ss]* ) curl "$url"/cgi-bin/logs.ha | 
            awk -v OFS='\t' -F '[<|>]'\
                '/td/{print $9, $13, $17, $21, $25}'\
                    >> BGW210_fwalllog.txt
            ;;
esac

Simple python script for it using Python3, urllib and html.parser

#! /usr/bin/python

#View firewall log from BGW210-700

import urllib.request
from html.parser import HTMLParser

#url of the gateway
url = 'http://192.168.0.1'

req = urllib.request.Request((url)+'/cgi-bin/logs.ha')
doc = urllib.request.urlopen(req).read()
log = []

class Parser(HTMLParser):    
    keep_tag = False
    
    def handle_starttag(self, tag, attrs):
        if tag == 'td':
            self.keep_tag = True

    def handle_data(self, data):
        if self.keep_tag:
            log.append(data)
            self.keep_tag = False

Parser().feed(str(doc))

#Simple format output 
a = 0; b = 6; c = len(log)
while True:
    if b > c:
        break
    print (log[(a):(b)])
    a = a + 6; b = b + 6

   
Simple python script for it using Python3, urllib and lxml.html

#! /usr/bin/python

import urllib.request
import lxml.html

#url of the gateway
url = 'http://172.16.0.1'

req = urllib.request.Request((url)+'/cgi-bin/logs.ha')
html = urllib.request.urlopen(req).read()
root = lxml.html.fromstring(html)

log = []

for i in root.xpath('//td'):
    log.append(i.text_content())
    
a = 0; b = 6; c = len(log)
while True:
    if b > c:
        break
    print (log[(a):(b)])
    a = a + 6; b = b + 6

As you can see all they do is parse the <td></td> tags.

If you want a continuous log for the BGW210 then look at
pacman -Si syslog-ng
https://wiki.archlinux.org/index.php/Syslog-ng

A most basic config that I've tested/works for it at time
of writing.
/etc/syslog-ng/syslog-ng.conf

@version: 3.18
@include "scl.conf"
options {time-reap(30); mark-freq(10); keep-hostname(yes); };

source s_network { syslog(ip(0.0.0.0) transport(udp) port(514)); };

destination d_logs { file("/var/log/BGW210.log" owner("root") group("root") perm(0777)); };

log { source(s_network); destination(d_logs); };

You will of course have to enable syslog on port 514 on the BGW210.

Offline

Board footer

Powered by FluxBB