You are not logged in.

#3326 2020-02-18 16:39:34

schard
Forum Moderator
From: Hannover
Registered: 2016-05-06
Posts: 2,111
Website

Re: Post your handy self made command line utilities

I just created this alias to see who's using up most of the disk space.

alias dutop='du -hs /home/* | sed "s:/home/::g" | grep -E $(getent passwd | cut -d: -f 1 | paste -sd "|" -) | sort -hr'

Last edited by schard (2020-02-18 16:42:58)


Inofficial first vice president of the Rust Evangelism Strike Force

Offline

#3327 2020-02-18 16:59:42

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

Re: Post your handy self made command line utilities

No, after the edit still not, 'du -s' would give you a grand total and sort --hr' would give the smallest as last output.
So at least it would be something like 'du -h /home/* | sort -h' in my HO wink

Offline

#3328 2020-02-18 17:27:48

schard
Forum Moderator
From: Hannover
Registered: 2016-05-06
Posts: 2,111
Website

Re: Post your handy self made command line utilities

The alias works as intended for me. The edit just changed the name of the alias and moved sorting to the end for performance.


Inofficial first vice president of the Rust Evangelism Strike Force

Offline

#3329 2020-02-18 17:45:01

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

Re: Post your handy self made command line utilities

It just gives a grand total at the end, which is to be expected since you use 'du -s' and if I don't remove the '-r' from sort I would get a reversed list which gives me the smallest as last output.
Since I think you would like to see the biggest numbers as last the '-r' should be removed...
Also 'sed "s:/home/::g" | grep -E $(getent passwd | cut -d: -f 1 | paste -sd "|" -) ' is not very useful in my HO as it removes a lot of output which you would like to see ...

Offline

#3330 2020-02-18 18:01:25

schard
Forum Moderator
From: Hannover
Registered: 2016-05-06
Posts: 2,111
Website

Re: Post your handy self made command line utilities

Did you actually try the alias, or are you just assuming? Of course I want the total disk usage *for each directory in /home*. Hence the -hs and the wildcard on du.
And as expected from a program named *top, the biggest values come first.


Inofficial first vice president of the Rust Evangelism Strike Force

Offline

#3331 2020-02-18 18:05:37

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

Re: Post your handy self made command line utilities

Yes I did I won't say it if it wouldn't be so wink
Actually these 2 lines would bring me much closer to what you expect me to see

du -h /home/* | sort -h | sed "/[0-9]K/d"
or
du -h /home/* | sort -h | sed "/\([0-9]K\\|[0-9]M\)/d"

Offline

#3332 2020-02-18 22:39:32

schard
Forum Moderator
From: Hannover
Registered: 2016-05-06
Posts: 2,111
Website

Re: Post your handy self made command line utilities

That'll give you the file size of anything under /home. Not just the accumulated file size of every home directory. And it's not event sorted so that the biggest file would be on TOP.
My goal was to find the users who consume most of the disk space in their home directory. Hence also the filter through gentent passed. Since there may be directories in /home which do not belong to a particular user, but contain shared data.


Inofficial first vice president of the Rust Evangelism Strike Force

Offline

#3333 2020-02-18 23:46:30

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

Re: Post your handy self made command line utilities

Yes, now I get the picture. That is actually quite useful on a multi-user system.
Tested it on a system with multiple users works fine. Added to file size script;)
Sorry for completely misunderstanding in the first place.

edit: Looked in the man and I still think there's a better way because du has it's own;)
It may not be exactly what you like but it's too close to justify that pipeline...

du -h -d1 /home

if you don't like the output you can even exclude them..

du -h -d1 --exclude='/home/lost+found' --exclude='/home/.Trash-0'

Last edited by qinohe (2020-02-19 11:02:20)

Offline

#3334 2020-02-20 12:32:50

neol09
Member
Registered: 2020-02-13
Posts: 13

Re: Post your handy self made command line utilities

qinohe wrote:

@neol09
A keyboard switcher in dmenu

That's in all honesty more than anything I've written for dmenu,
Not that i don't love dmenu, I just default to the terminal before giving it any thought.


unset kbd && exit 0

brilliant if it does what i think it does. I Will implement it somewhere so i don't forget :-)

 $dmindex -p 'prompt' -w 240 

What does the windowid 240 represent tho? Is it possible to assign windows to specific id's or?

 # a snippet, gets the active window for use with dmenu -w $id
id=$(xprop -root | sed -n '/^_NET_ACTIVE_WINDOW/{s/.* //p}')

Offline

#3335 2020-02-20 12:45:56

schard
Forum Moderator
From: Hannover
Registered: 2016-05-06
Posts: 2,111
Website

Re: Post your handy self made command line utilities

qinohe wrote:

It may not be exactly what you like but it's too close to justify that pipeline...

du -h -d1 /home

This is actually more elegant than the wild card.
The disadvantage is, that it also calculates the total for /home.
Also for my use case, I do not save a pipeline, since I still need to get rid of the /home prefix, non-user-named directories and have to sort.


Inofficial first vice president of the Rust Evangelism Strike Force

Offline

#3336 2020-02-20 15:11:16

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

Re: Post your handy self made command line utilities

neol09 wrote:

Not that i don't love dmenu, I just default to the terminal before giving it any thought.

I love dmenu and run a few dozen scripts with it. Have a peek in the dmenu thread, there are some nice implements there;)

unset kbd && exit 0

brilliant if it does what i think it does. I Will implement it somewhere so i don't forget :-)

Together with the trap it removes what was bound to the kbd variable & will always exit '0' in the end as it should.

 $dmindex -p 'prompt' -w 240 

What does the windowid 240 represent tho? Is it possible to assign windows to specific id's or?

smile It's the width of the dmenu field.

Offline

#3337 2020-02-20 15:56:49

neol09
Member
Registered: 2020-02-13
Posts: 13

Re: Post your handy self made command line utilities

qinohe wrote:

I love dmenu and run a few dozen scripts with it. Have a peek in the dmenu thread, there are some nice implements there;)

I've a fancy for wrapping tput in read loops, I'll post some of the stuff i made if i ever polish it up :-)

qinohe wrote:

Together with the trap it removes what was bound to the kbd variable & will always exit '0' in the end as it should.

But does it release the keyboard? I've come across this glitch in dmenu under specific conditions where upon termination with <C-c> the keyboard remains locked ( window manager isn't getting keystrokes ) That was a while ago, don't remember the details unfortunately

qinohe wrote:

smile It's the width of the dmenu field.

Not for me it isn't ^^' Tho i have to admit being able to set the width sounds great, too.
I'd post a screenshot if i had known any decent hosts these days.

Offline

#3338 2020-02-20 16:30:04

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

Re: Post your handy self made command line utilities

neol09 wrote:

But does it release the keyboard? I've come across this glitch in dmenu under specific conditions where upon termination with <C-c> the keyboard remains locked ( window manager isn't getting keystrokes ) That was a while ago, don't remember the details unfortunately

'INT' yes, at least I think it should - see 'man 7 signal' or https://mywiki.wooledge.org/SignalTrap

Not for me it isn't ^^' Tho i have to admit being able to set the width sounds great, too.
I'd post a screenshot if i had known any decent hosts these days.

It should set the width of the field, if you use

echo 'trough' |dmenu -i -l 10 -fn 'DejaVuSansMono-11' -nb '#2e3032' -nf '#f4f8f4' -sb '#2e3032' -sf '#8f8f8c' -p 'keyboard layout:' -w 600

does it work then?

You can use 'imgbb.com' or 'imgur.com' for the screenshots

Offline

#3339 2020-02-20 18:00:03

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

Re: Post your handy self made command line utilities

schard wrote:

The disadvantage is, that it also calculates the total for /home.
Also for my use case, I do not save a pipeline, since I still need to get rid of the /home prefix, non-user-named directories and have to sort.

Yes I think you're right, I could come up with all kind of sed/awk lines but I think you know best what output you need for the follow up;)

Offline

#3340 2020-02-20 18:17:02

neol09
Member
Registered: 2020-02-13
Posts: 13

Re: Post your handy self made command line utilities

qinohe wrote:

'INT' yes, at least I think it should - see 'man 7 signal' or https://mywiki.wooledge.org/SignalTrap

yep familiar with them, good article tho will recommend :-)


echo 'trough' |dmenu -i -l 10 -fn 'DejaVuSansMono-11' -nb '#2e3032' -nf '#f4f8f4' -sb '#2e3032' -sf '#8f8f8c' -p 'keyboard layout:' -w 600

does it work then?

Nope, It does about as much work as i do lol
20-02-20-009.png

Offline

#3341 2020-02-20 18:44:52

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

Re: Post your handy self made command line utilities

neol09 wrote:

Nope, It does about as much work as i do lol

Haha, yes use dmenu2(AUR) it's a fork of dmenu patched with some nice capabilities...
I was wondering.. where does he get the 'windowid' from;)

Offline

#3342 2020-02-20 18:56:17

neol09
Member
Registered: 2020-02-13
Posts: 13

Re: Post your handy self made command line utilities

qinohe wrote:

Haha, yes use dmenu2(AUR) it's a fork of dmenu patched with some nice capabilities...
I was wondering.. where does he get the 'windowid' from;)

i wouldn't even know what you mean ^^

however dmenu 4.9-1 appears to be part of the community repo not the AUR.
should i be worried? or did you compile yours straight from suckless.org?

Offline

#3343 2020-02-20 19:10:21

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

Re: Post your handy self made command line utilities

neol09 wrote:
qinohe wrote:

Haha, yes use dmenu2(AUR) it's a fork of dmenu patched with some nice capabilities...
I was wondering.. where does he get the 'windowid' from;)

i wouldn't even know what you mean ^^

Meaning it has abilities the default dmenu from the repo has not, including 'w=width'

however dmenu 4.9-1 appears to be part of the community repo not the AUR.
should i be worried? or did you compile yours straight from suckless.org?

No you should not be worried, I used the PKGBUILD provided in the AUR, https://aur.archlinux.org/cgit/aur.git/ … D?h=dmenu2
If you use PKGBUILD's from 'others, always check if they are correct, human failure is always a risk, but so is using a package from the official repo they can have problems too which are spotted too late(openssh news...)

Offline

#3344 2020-02-20 19:44:49

neol09
Member
Registered: 2020-02-13
Posts: 13

Re: Post your handy self made command line utilities

qinohe wrote:

Meaning it has abilities the default dmenu from the repo has not, including 'w=width'

Thought you were referring to the innerworkings, nvm

qinohe wrote:

No you should not be worried, I used the PKGBUILD provided in the AUR

You had me this close to shredding my harddrive. o/

Offline

#3345 2020-02-20 20:13:28

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

Re: Post your handy self made command line utilities

Always use a PKGBUILD and if you can only find source create one so pacman can keep track of installed packages.
In the case of dmenu2 it has a very decent makefile provided with uninstall but still use a PKGBUILD.
Read up on https://wiki.archlinux.org/index.php/Ar … Repository

Offline

#3346 2020-02-22 01:32:30

neol09
Member
Registered: 2020-02-13
Posts: 13

Re: Post your handy self made command line utilities

Here's something random and old i've glanced over today, may it serve as a case study if nothing else

#!/bin/bash

ee=$(tput cols)  # screen End
mm=$((ee / 2))   # screen Middle
ss=0             # screen Start
# lw=32            # logo width
hw=16            # half width
b="$(tput setaf 6)"
n="$(tput sgr0)"
logo='
               -@                
              .##@               
             .####@              
             @#####@             
           . *######@            
          .##@o@#####@           
         /############@          
        /##############@         
       @######@**%######@        
      @######`     %#####o       
     @######@       ######%      
   -@#######h       ######@.`    
  /#####h**``       `**%@####@   
 @H@*`                    `*%#@  
*`                            `* '

trap 'tput reset; tput cnorm; exit' HUP INT

while read -r line; do
	fig[$((++row))]="$b${line} "
done < <(figlet <<< "${1:-Hello Arch linux }" | sed -n '$q;p' )

for a in $(seq 1 15); do
	r1[$a]=$((- a + hw - 1))
	r2[$a]=$((  a * 2  + 2))
done

row=0
while IFS= read -r line; do ((++row))
	out+="\e[20C${fig[$row]:0:$(( ee - hw ))}"
	out+="\e[$row;$((ss              ))H$b${line:${r1[$row]}:${r2[$row]}}"
	out+="\e[$row;$((mm - row     - 1))H$n${line:${r1[$row]}:${r2[$row]}}"
	out+="\e[$row;$((ee - row * 2 - 1))H$b${line:${r1[$row]}:${r2[$row]}}\n"
done < <( tail -n +2 <<< "$logo" )

tput init
tput civis
clear
echo -en "$out"

[ "$2" ] && read -n1 || read -n1 -t .2

tput cup "$(tput lines)"
for line in $(seq 1 $hw)
do
	sleep .03
	echo -en '\n'
done

tput reset
tput cnorm
exit

screensaver / login banner, i guess.
credit for the logo goes to someone on the wiki if i recall correctly

Offline

#3347 2020-02-22 15:01:36

arch_jsb
Member
Registered: 2010-03-13
Posts: 28

Re: Post your handy self made command line utilities

evil wrote:

Here is what I use when batch renaming picture files

#!/usr/bin/python

import os, sys
from optparse import OptionParser

parser = OptionParser()
parser.add_option("-f", "--filetype", metavar="filetype",default=".jpg", help="Choose file type to rename", type="string", dest="ren_filetype")
parser.add_option("-p", "--prefix", metavar="prefix", default="Pictures", help="Choose a filename prefix", type="string", dest="ren_prefix")
parser.add_option("-s", "--startcount", metavar="startcount", default=1, help="Choose what number to start counting from", type="int", dest="ren_startcount")
parser.add_option("-d", "--directory", metavar="directory", default=".", help="Define a different directory besides the working directory", type="string", dest="ren_directory")

(options, args) = parser.parse_args()

ren_filetype = options.ren_filetype
ren_prefix = options.ren_prefix
ren_startcount = options.ren_startcount
ren_directory = options.ren_directory

ren_list=[]
ren_filecount=0

os.chdir(ren_directory)

for a in os.listdir('.'):
    if a.endswith(ren_filetype) == True:
        ren_filecount=ren_filecount+1
    ren_list.append(a)


ren_filecount='%(#)0' + str(len(str(ren_filecount + ren_startcount))) + 'd'

for b in ren_list:
    os.rename(b, ren_prefix + '-' + (ren_filecount % {"#" : ren_startcount}) + ren_filetype)
    ren_startcount=ren_startcount+1

and this is what I use in place of cd ../../../.. etc

#!/bin/bash
x=''
for i in $(seq $1)
do
x="$x../"
done
cd $x

I named the above script to cdup and then made an alias: alias up='source cdup' so i wouldn't have to constantly prefix a . or source to the command.

This last script I use to mess with my wife when she's on the tower pc. Let me show the script first:

#!/bin/bash

run_task() {
mytype=$(cut -d ' ' -f1 /home/lucian/scripts/xcutr_script/commander)
mytask=$(cut -d ' ' -f2- /home/lucian/scripts/xcutr_script/commander)

if [ "$mytype" == "msg" ]
 then
  notify-send "Message from Lucian" "$mytask"
  echo "Sent message: $mytask at $(date +%D) $(date +%r)" >> /home/lucian/scripts/xcutr_script/comm_log
  > /home/lucian/scripts/xcutr_script/commander
elif [ "$mytype" == "exec" ]
 then
  exec $mytask &
  echo "Ran command: $mytask at $(date +%D) $(date +%r)" >> /home/lucian/scripts/xcutr_script/comm_log
  > /home/lucian/scripts/xcutr_script/commander
fi

}

while :
 do
  if [  ! $(ls -l /home/lucian/scripts/xcutr_script/commander |cut -d ' ' -f5) -eq 0 ]
   then
    run_task
  fi
done

This script is ran on start-up on my tower pc, and is constantly running. It monitors a file named "commander" in the base directory of the script for any commands. So, I just ssh in to the tower and run something like: echo "msg how are you" > commander OR echo "exec firefox www.yahoo.com" > commander

The above will either send a notify-send on the tower pc or execute firefox (or open tab if already opened) to yahoo.com

The commander file has to exist (empty) prior to running and all commands will be logged to comm_log in the base directory as well with date and time.

  That python script will rename all files in the subdirectory it is run in.  Be sure one has backups...

Offline

#3348 2020-03-25 21:07:34

jbenge1
Member
From: Az
Registered: 2018-04-09
Posts: 151

Re: Post your handy self made command line utilities

I've been pretty bored in isolation, so I decided to build a password manager in python smile

#!/usr/bin/env python3
'''
 ----------------------------------------------------------------------------
 "THE BEER-WARE LICENSE" (Revision 42):
  As long as you retain this notice you can do whatever you want with this stuff. 
  If we meet some day, and you think this stuff is worth it, 
  you can buy me a beer in return.   Justin Benge
 ----------------------------------------------------------------------------

 @author: Justin Benge <justinbng36@gmail.com>
'''
import base64
import os
import sys, subprocess
import argparse
from cryptography.fernet import Fernet
from pathlib import Path
from getpass import getpass
import pyperclip
import time
import platform

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

VERSION = '3.0.0'

#UNICODE Vars
ELBOW='\u2514'
BAR='\u2500'
T_BAR='\u251c'
VERT_BAR='\u2502'

DIR_SLASH='/'
WINDOWS=platform.system() == 'Windows'
if(WINDOWS):
    DIR_SLASH = '\\'

    
PASS_STORE_LOCATION=str(Path.home()) + DIR_SLASH + '.passwords' + DIR_SLASH
PASS_FILE=str(Path.home()) + DIR_SLASH + '.passwords' + DIR_SLASH + '.pass'
KEY_FILE=str(Path.home()) + DIR_SLASH + '.key.key'
SALT_FILE=str(Path.home()) + DIR_SLASH + '.salt'
class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

def version():
 '''Prints the version number, and license info '''
 print('''
   /\/\\    
  / /  \\    /\\        pypass v'''+VERSION+'''
 / / /\ \\  /  \\  /\\   ''', end = '')
 print('''
 \ \/ / /  \\  /  \\/   Copyright (c) 2020-2021 Justin Benge
  \  / /    \\/    
   \/\/               This program may be freely redistributed under
		      the terms of the Beerware licence.
    ''')

def print_help():
    '''
    Prints how to use the pypass script
    '''
    print("""usage: pypass.py [-h] [-v] [--initialize] [-i INSERT] [-g GET] [--generate GENERATE] [-n LENGTH] [-c COPY]

optional arguments:
  -h, --help            show this help message and exit
  -v, --version
  --initialize
  -i INSERT, --insert INSERT
  -g GET, --get GET
  --generate GENERATE
  -n LENGTH, --length LENGTH
  -c COPY, --copy COPY""")

def print_pass_store(dirs_param=PASS_STORE_LOCATION, padding=0):
    if(padding==0):
        print('Password Store:')
        print_pass_store(dirs_param, padding+1)
    else:
        for dir_s in os.listdir(dirs_param):
            if(dir_s == '.pass'):
                continue
            dir_p = Path(dirs_param + DIR_SLASH + dir_s)
            if(dir_p.is_dir()):
                print(T_BAR + padding*BAR + dir_s)
                print_pass_store(str(dir_p), padding+1)
            else:
                print(VERT_BAR + (padding) *' ' + ELBOW + BAR + dir_s)
            

def create_key():
    password = getpass("Enter your key password: ").encode()
    salt_file = Path(SALT_FILE)
    if(salt_file.is_file()):
        with open(salt_file, "rb") as salt_fil:
            salt = salt_fil.read()
    else:
        salt = os.urandom(16)
        with open(salt_file, 'wb') as salt_fil:
            salt_fil.write(salt)

    kdf = PBKDF2HMAC(
         algorithm=hashes.SHA256(),
         length=32,
         salt=salt,
         iterations=100000,
         backend=default_backend()
    )
    key = base64.urlsafe_b64encode(kdf.derive(password))
    return key

def initialize_pass_store():
    '''
    Checks to see if a key is already stored somewhere,
    and creates a new one if one doesn't exist
    '''

    key_file = Path(KEY_FILE)
    if(not key_file.is_file()):
        yn = input('Create a key based off password? [Y/n]: ')
        with open(key_file, "wb") as key_file:
            if(yn.lower() == 'n'):
                key = Fernet.generate_key()
                key_file.write(key)
            else:
                key_file.write(create_key())
        print("Key generated :)")

    pass_dir = Path(PASS_STORE_LOCATION)
    pass_file = Path(PASS_FILE)
    if(not pass_dir.is_dir()):
        os.mkdir(PASS_STORE_LOCATION)
        if(WINDOWS):
            subprocess.run(["attrib", "+s", "+h", pass_dir])
        print('Created password store :)')

    if(not pass_file.is_file()):
        f = Fernet(load_key())
        password = getpass("Enter you master password (make sure it's a good one ;)): ")
        password = f.encrypt(password.encode())
        with open(str(pass_file), "wb") as fil:
            fil.write(password)
    else:
        print("Key file or password store already exists!")


def load_key():
    '''
    Gets the stored key for encrypting stuff
    '''
    return open(KEY_FILE, "rb").read()

def copy_to_clipboard(key, pass_name):
    text = pyperclip.paste()
    pyperclip.copy(get_password(key, pass_name))
    print("{0} copied to clipboard for 30 seconds".format(pass_name))
    time.sleep(30)
    pyperclip.copy(text)

def check_password(key):
    password_to_check = getpass("Enter your password:")
    password = get_master_password(key)
    if(password_to_check == password):
        return True
    return False

def get_master_password(key):
    f = Fernet(key)
    with open(str(PASS_FILE), "rb") as fil:
        return f.decrypt(fil.read()).decode("utf-8")

def store_password(key, pass_name, password=None):
    pass_file = Path(PASS_STORE_LOCATION + pass_name)
    if(pass_file.is_file()):
       yn = input("Password already exists for {0}. Do you want to overwrite it? [y/N]: ".format(pass_name))
       if yn.lower() == 'n':
           sys.exit(1)
    if(password == None):
        password = getpass('Enter password for {0}'.format(pass_name))
    f = Fernet(key)
    pass_file = str(pass_file)
    password = password.encode()
    with open(pass_file, "wb") as fil:
        fil.write(f.encrypt(password))

def store_password_2(key, pass_name, password=None):
    pass_names = pass_name.split('/')
    i=0
    dir_str_var = ''
    for i in range(len(pass_names) - 1):
        dir_str_var = dir_str_var + DIR_SLASH + pass_names[i]
        dir_path_var = Path(PASS_STORE_LOCATION + dir_str_var)
        if(not dir_path_var.is_dir()):
            os.mkdir(dir_path_var)
            if(WINDOWS):
                subprocess.run(["attrib", "+s", "+h", str(dir_path_var)])
    pass_file = Path(PASS_STORE_LOCATION + dir_str_var + DIR_SLASH + pass_names[i+1])
    if(pass_file.is_file()):
       yn = input("Password already exists for {0}. Do you want to overwrite it? [y/N]: ".format(pass_name))
       if yn.lower() == 'n':
           sys.exit(1)
    if(password == None):
        password = getpass('Enter password for {0}: '.format(pass_name))
    f = Fernet(key)
    pass_file = str(pass_file)
    password = password.encode()
    with open(pass_file, "wb") as fil:
        fil.write(f.encrypt(password))

def get_password(key, pass_name):
    pass_file = Path(PASS_STORE_LOCATION + pass_name)
    if(not pass_file.is_file()):
        print("Password for {0} does not exist :(".format(pass_name))
        sys.exit(2)
    
    if(not check_password(key)):
        print("Incorrect password >:(")
        sys.exit(255)
    f = Fernet(key)
    with open(str(pass_file), "rb") as fil:
        return f.decrypt(fil.read()).decode("utf-8")

def generate_password(key, pass_name, pass_len=20):
    password = os.urandom(pass_len)
    password = base64.b64encode(password).decode('utf-8')
    store_password(key,pass_name, password[0:pass_len]) 
    get_password(key, pass_name) 


parser = argparse.ArgumentParser()
parser.add_argument('-v','--version', action='count'   ) 
parser.add_argument('--initialize'  , action='count'   )
parser.add_argument('-i', '--insert', nargs=1, type=str)
parser.add_argument('-g', '--get'   , nargs=1, type=str)
parser.add_argument('--generate'    , nargs=1, type=str)
parser.add_argument('-n', '--length', nargs=1, type=int)
parser.add_argument('-c', '--copy'  , nargs=1, type=str)
args = parser.parse_args(sys.argv[1:])

if args.version:
    version()
elif args.initialize:
    initialize_pass_store()
elif args.insert:
    store_password_2(load_key(), args.insert[0])
elif args.get:
    print(get_password(load_key(), args.get[0]))
elif args.copy:
    copy_to_clipboard(load_key(), args.copy[0])
elif args.generate:
    if args.length:
        generate_password(load_key(), args.generate[0], args.length[0])
    else:
        generate_password(load_key(), args.generate[0])
elif not args.generate and args.length:
    print("Please specify --generate")
else:
    print_pass_store()

"Dr. Madden, why don't the natural numbers include 0?" -me
"....... Take a philosophy course" -Dr. Madden

Offline

#3349 2020-04-03 16:18:11

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

Re: Post your handy self made command line utilities

Forced to stay home with my familiy, my 7 years old baby is forced to study here, and she's doing times tables, which is really a PIT(in my)A.
So i made a bash script for her, it is in italian language.
First argument is the table you want to learn or "tutte" (means "all").
Hoping it will work...

#!/bin/bash

tabellina_del=$1
domande=10 ##how many questions
secondi=5 #how much seconds to timeout
log=/tmp/tabelline.log

##########################
esatte=0
sbagliate=0



countdown(){
	for i in $(seq $1 -1 1) ; do
		echo -ne "\033[s  \033[K \033[2B \033[100DMancano $i secondi \033[u"
		sleep 1
	done
}


reset
echo Ripetiamo la tabellina del $1.
echo "Hai $secondi secondi per rispondere alle $domande domande."
echo "Pronti?"
read
echo "VIA!"
sleep 1
reset

rm $log &>/dev/null
for t in $( seq 1 $domande ) ; do
	countdown $secondi &
	pid=$!
	risposta=""
	#f1
	if [ $tabellina_del = "tutte" ] ; then
		f_prev=$f1
	        while [ "$f_prev" = "$f1" ] ; do
        	        f1=$(( 2 + $RANDOM % 8 ))
        	done
			else
		f1=$tabellina_del
	fi

	#f2
	f_prev=$f2
	while [ "$f_prev" = "$f2" ] ; do
		f2=$(( 2 + $RANDOM % 8 ))
	done

	risultato=$(( $f1 * $f2))

	echo Domanda $t/$domande
	echo -n "$f1 x $f2 = "
	read -t $secondi risposta
	kill $pid &>/dev/null
	wait $! 2>/dev/null
	if [[ $risposta = "" ]] ; then echo ; fi
	if [ "$risposta" = "$risultato" ] ; then
		echo "Esatto!                                                                   "
		esatte=$(($esatte+1))
		echo "++ $f1 x $f2 = $risposta" >> $log
			else
		echo "Mannaggia!, $f1 x $f2 = $risultato"
		sbagliate=$(($sbagliate+1))
		echo "-- $f1 x $f2 = $risposta" >> $log
	fi
	echo "Premi invio                                                                   "
	read
	reset
done
echo Finito.

#Report:
cat $log | sort | columns --by-columns
echo Esatte: $esatte
echo Sbagliate: $sbagliate

#Giudizio
percentuale=$(echo "($esatte/$domande)*100" | bc -l|cut -d "." -f 1)
echo Hai risposto correttamente al "$percentuale"% delle domande.

if [ "$esatte" = "0" ] ; then echo "Peggio di così non si poteva..." ; exit ; fi
if [ $percentuale -lt 10 ] ; then echo "Mmmm, forse stavi dormendo?" ; exit ; fi
if [ $percentuale -lt 20 ] ; then echo "Ne hai indovinata qualcuna solo per fortuna, forse?" ; exit ; fi
if [ $percentuale -lt 30 ] ; then echo "Non ci siamo proprio!" ; exit ; fi
if [ $percentuale -lt 40 ] ; then echo "Eeh... qualcosa la sai, ma ancora troppo poco!" ; exit ; fi
if [ $percentuale -lt 50 ] ; then echo "Quasi sufficiente, va..." ; exit ; fi
if [ $percentuale -lt 60 ] ; then echo "Appena sufficiente, puoi fare di meglio!" ; exit ; fi
if [ $percentuale -lt 70 ] ; then echo "Benino" ; exit ; fi
if [ $percentuale -lt 80 ] ; then echo "Aaah, ora cominciamo a ragionare, brava" ; exit ; fi
if [ $percentuale -lt 90 ] ; then echo "Buono!"  ; exit ; fi
if [ $percentuale -lt 100 ] ; then echo "Tutto ottimo, quasi perfetto!"  ; exit ; fi
if [ $domande = "$esatte" ] ; then echo "Meglio di così è impossibile, BRAVA!" ; exit ; fi

...even such simple tasks can teach something, as
* how on earth suppress bash messages about background jobs being killed?
turns out "wait" has been developed for this specific task smile

Last edited by kokoko3k (2020-04-03 16:26:11)


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

Online

#3350 2020-04-03 16:55:40

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

Re: Post your handy self made command line utilities

Another one for her.

#! /usr/bin/env bash

#Multiplication table. 
#Terminal needs to be at least 100 char wide.

clear

NUM1=({0..15})
NUM2=({0..16})

printf "%55s %s\n %s\n" "Tabellina" 
printf "%6s" "${NUM1[@]}"
echo

BGC=(43m 45m 46m 43m 45m 46m 43m 45m 46m 43m 45m \
    46m 43m 45m 46m 43m)

for i in "${NUM1[@]}"; do
    if [ $i -lt 10 ]; then
        echo -en " "$i""
    else
        echo -en ""$i""
    fi
    
    A=0; index=0
    for j in "${BGC[@]}"; do
        A=$((${NUM2[$index]} * $i))
     
        if [ $A -lt 10 ]; then
            echo -en "\033[30m\033["$j"   "$A"  "

        elif [ $A -gt 9 -a $A -lt 100 ]; then
            echo -en "\033[30m\033["$j"  "$A"  "
            
        elif [ $A -gt 99 ]; then
            echo -en "\033[30m\033["$j" "$A"  "
        fi
        
        index=$(($index + 1))
        tput sgr0
    done
    echo
done

Offline

Board footer

Powered by FluxBB