[ art / civ / cult / cyb / diy / drg / feels / layer / lit / λ / q / r / sci / sec / tech / w / zzz ] archive provided by lainchan.jp

lainchan archive - /tech/ - 35087



File: 1488355291646.png (4.97 MB, 300x188, Screen Shot 2017-03-01 at 01.58.00.png)

No.35087

This might be a post better suited to /λ/ but I thought I'd post it here first.

What scripts have you found/written which you find paticularly useful? (Pic related)

  No.35094

>>35087

I wrote a Python script to strip exif data from all images in a directory. I can share it if anyone is interested - it's probably not very elegant programming though.

  No.35096

>>35094
Oh but please do, I love reading code, especially of small practical scripts.

  No.35098

>>35087
I've written a Telegram Bot script that posts 5 (or less) search results given a string. Useful for when you don't have time to answer your friends stupid ass questions that could be answered by using a search engine. The bot uses Searx instead of Google.

https://github.com/fuerbringer/searxbot

It's somewhat unstable and the first NodeJS script I wrote but it gets the job done.

  No.35100

Bash script to upload files from the command line to lewd.se, a pomf clone. Removes filename (gimped if there isn't a file extension) and replaces it with a random string from /dev/urandom (without special chars), then copies the URL to your clipboard using xclip. The random string generation isn't my work, that's a script here: https://gist.github.com/earthgecko/3089509

#!/bin/bash
while getopts ":f:" opt; do
case $opt in
f)
echo "uploading $OPTARG" >&2
name=$(randomnum)
filename=`basename $OPTARG`
fileext=${OPTARG##*.}
if curl -s -F name="$name"."$fileext" -F file=@"$OPTARG" https://lewd.se/api.php?d=upload-tool | xclip -selection clipboard; then
echo "Uploaded."
else
echo "Failed to upload."
fi
;;
\?)
echo "Illegal Character" >&2
exit 1
;;
:)
echo "Nothing was entered." >&2
exit 1
;;
esac
done

  No.35101

>>35100
why are you using getopts for this? just try to send everything in $@

  No.35105

  #!/bin/sh
cat /dev/urandom | tr -dc A-Za-z0-9 | head -c 16 && echo

  No.35106

  #!/bin/sh
curl -F 'f:1=<-' ix.io

  No.35107

>>35101
The script is a result of me wanting to learn how to use flags in scripts, thats why I didn't use $@. It didn't have much purpose other than self education.

  No.35129

  #!/bin/bash
clear

mensajes(){
ok=true

echo "Do you want to turn off your laptop's monitor? Yes (y) No (n) "
read aP

if ( [ $aP == 'y' ] || [ $aP == 'Y' ] ); then
aP='Y'
elif ( [ $aP == 'n' ] || [ $aP == 'N' ] ); then
aP='N'
else
ok=false
fi

echo "What do you want to use? HDMI (h) VGA (v) "
read sV

if ( [ $sV == 'h' ] || [ $sV == 'H' ] ); then
sV='H'
elif ( [ $sV == 'v' ] || [ $sV == 'V' ] ); then
sV='V'
else
ok=false
fi

if [ "$ok" == true ]; then
apagar "!@"
else
error "!@"
fi
}

apagar(){
if [ $aP == 'Y' ]; then
xrandr --output LVDS1 --off
if ( [ $sV == 'H' ] ); then
xrandr --output HDMI1 --auto --primary
elif ( [ $sV == 'V' ] ); then
xrandr --output VGA1 --auto --primary
fi
elif [ $aP == 'N' ]; then
if ( [ $sV == 'H' ] ); then
xrandr --output HDMI1 --auto --right-of LVDS1
elif ( [ $sV == 'V' ] ); then
xrandr --output VGA1 --auto --right-of LVDS1
fi
fi
}

error(){
clear
echo "Do you want to turn off your laptop's monitor? Yes (y) No (n) "
if ( [ $aP != 'Y' ] && [ $aP != 'N' ] ); then
echo "==> $aP"
else
echo "$aP"
fi

echo "What do you want to use? HDMI (h) VGA (v) "
if ( [ $sV != 'H' ] && [ $sV != 'V' ] ); then
echo "==> $sV"
else
echo "$sV"
fi
echo ""
echo "ERROR: One of the options is incorrect."
}

mensajes "$@"

  No.35130

  #!/bin/bash
clear

mensajes(){
ok=true

echo "What do you want to set: (w)idth or (h)eight ?"
read set
if ( [ $set == 'w' ] || [ $set == 'W' ] ); then
set='W'
elif ( [ $set == 'h' ] || [ $set == 'H' ] ); then
set='H'
else
ok=false
fi

if [ "$ok" == true ]; then
echo "Please enter a value "
read pixel
resize "!@"
else
error "!@"
fi
}

resize(){
if [ "$set" == 'W' ]; then
for i in *.png
do
echo "Resizing $i"
convert "$i" -resize "$pixel"x "{$i%.*}_.png"
done
elif [ "$set" == 'H' ]; then
for i in *.png
do
echo "Resizing $i"
convert "$i" -resize x$pixel "{$i%.*}_.png"
done
fi
}

error(){
echo "Something went wrong"
}

mensajes "$@"

  No.35131

  #!/bin/bash
clear

printf "(f)lac or (m)4a\n"
read formato

if ( [ $formato == 'f' ] || [ $formato == 'F' ] ); then
for a in ./*.flac; do
echo "Convirtiendo $a..."
ffmpeg -i "$a" -qscale:a 0 "${a[@]/%flac/mp3}"
done
elif ( [ $formato == 'm' ] || [ $formato == 'M' ] ); then
for a in ./*.m4a; do
ffmpeg -i "$a" -acodec libmp3lame -ab 320k "${a%.*}.mp3"
done
else
echo "Error"
fi

  No.35132

  #!/bin/bash
clear

ok=true

printf "What type of files do you want to delete?\n."
read ext
ls -d */
echo "From which directory? (without / )"
read dir
echo "Do you want to delete the .$ext files from the $dir/ directory? (s)i (n)o"
read confirmar
if ( [ $confirmar == 'y' ] || [ $confirmar == 'Y' ] ); then
find $dir -name '*.'$ext -exec rm -r {} \;
echo "Se eliminaron todos los archivos .$ext del directorio $dir/"
elif ( [ $confirmar == 'n' ] || [ $confirmar == 'N' ] ); then
echo "No se ha eliminado ningún archivo .$ext del directorio $dir/"
else
echo "Error"
fi

  No.35451

There is a similar thread over at /lam/
also, as a comment, maybe write what your scripts are for in the beginning of the script?
Thanks tho, guise.

  No.35456

Shows the status of all installed batteries (most laptops just have one) in your machine with nice Unicode-arrows to indicate {dis,}charging. I'm piping this to my status dwm-status bar.
  acpi --battery | \
sed 's/\(.*\): \([CDFU]\)\([a-z]*\), \([0-9%]*\)\(.*\)/\2\4/g' | \
sed 's/^C/↑/g;s/^D/↓/g;s/^[UF]//g' | \
xargs echo -n

Little script to {toggle,{en,dis}able} the touchpad. It's quite useful if you're having a {TrackPoint™-Style Pointer,Nub,Clit Mouse} and mostly don't wanna use the touchpad.
  #!/usr/bin/env # Usage:
# touchpad-toggle [on|off]
#
# touchpad-toggle : Toggle the touchpad
# touchpad-toggle on : Turn it on
# touchpad-toggle off : Turn it off
#

# (Sub-)String which identifies the device.
TOUCHPAD_NAME="Synaptics TouchPad"

XINPUT_DEV_ID=`xinput | grep "$TOUCHPAD_NAME" | cut -f 2 | cut -d= -f2`
case "$1" in
on)
NEW_STATUS="1"
;;
off)
NEW_STATUS="0"
;;
*)
NEW_STATUS="$(( `xinput list-props $XINPUT_DEV_ID | grep "Device Enabled" | cut -f3` ^ 1 ))"
;;
esac

xinput set-prop $XINPUT_DEV_ID "Device Enabled" $NEW_STATUS

  No.35457

>>35456
Somehow the shebang in the second code block got messed up. The first line should be #!/usr/bin/env bash and then a line break should follow‥

  No.35460

File: 1489323612933.png (10.86 MB, 128x128, freeFTP.txt)

  import random
from ftplib import FTP
import string
import io



def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))

def timeout(func, line, timeout_duration=1, default=None):
import signal
class TimeoutError(Exception):
pass

def handler(signum, frame):
raise TimeoutError()

# set the timeout handler
signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout_duration)
try:
result = func(line)
except TimeoutError as exc:
result = default
finally:
signal.alarm(0)

return result

def check_server(myline):
ftp = FTP(myline.split(':')[0])
ftp.login()
directory = id_generator()
ftp.mkd(directory)
ftp.cwd(directory)
ftp.storbinary('STOR ' + directory + '.txt', io.BytesIO('Hello'.encode()))
print('SUCCESS: ' + myline)
with open('success.txt', 'a+') as file:
file.write(myline + "\n")
ftp.quit()

lines = open('freeFTP.txt').read().splitlines()

i = 1
while len(lines) > 0:
myline = random.choice(lines)
if i % 10 == 0:
print('10 MORE CHECKED, TOTAL = ' + str(i))
try:
timeout(check_server, myline, timeout_duration=6, default=None)
except:
pass;

lines.remove(myline)
i += 1

It searches list of free FTP servers and looks at random for those with confirmed write access. I attach the IP list.

  No.35481

File: 1489359615142.png (265.78 KB, 200x142, pEWhStf.jpg)

Here's a couple scripts inspired by LISP for dealing with the fish shell's lists (e.g. environment variables--$PATH, etc.)

  function bf --description 'Return all elements of LIST _b_ut the _f_irst'

set -l list_length (math (count $argv)-1)

if test "$list_length" -lt 0
return 1
else if test "$list_length" -eq 0
printf ""
else
for i in $argv[2..-1]
echo "$i"
end
end
end

function bl --description 'Return all elements of LIST _b_ut the _l_ast'

set -l list_length (math (count $argv)-1)

if test "$list_length" -lt 0
return 1
else if test "$list_length" -eq 0
printf ""
else
for i in $argv[1.."$list_length"]
echo "$i"
end
end
end

Oh, and here's one for removing that stupid URL from youtube-dl'd videos:

  function ytdl-cleanup --description 'Remove the url part from youtube-dl videos'

set -l prev_exit_code (printf '%d\n' "$status")

isatty 0
set -l are_you_a_tty (printf '%d\n' "$status")

if test "$are_you_a_tty" -a "$prev_exit_code" -ge 1
return 1
else
set -l ytdl_vid_url_and_ext (printf "$argv" | grep -Zo '\-[^-]*$' -)
set -l ytdl_vid_ext (printf "$ytdl_vid_url_and_ext" | grep -Zo '\.[^.]*$' -)
set -l ytdl_vid_basename (basename -zs "$ytdl_vid_url_and_ext" "$argv")
set -l ytdl_vid_final (string join '' "$ytdl_vid_basename" "$ytdl_vid_ext")

mv "$argv" "$ytdl_vid_final"
rename 'y/A-Z/a-z/' "$ytdl_vid_final" >/dev/null ^&1
end
end

  No.35813

File: 1490203475927.png (96.18 KB, 132x200, 1444802813079.gif)

change file extensions for multiple files in current directory

  #!/bin/bash

shopt -s globstar
for file in ./*.$1
do
[[ -d "$file" ]] && continue
mv -v "$file" "${file/%.$1}.$2"
done

  No.35821

My most used and loved script. Takes a screenshot of a selected area and copies it to clipboard for further pasting into various messengers or image editors. For those who don't want to install some huge buggy application for a very simple common task.

  #!/bin/zsh
gm import -silent png:- | xclip -selection c -t image/png

  No.35829

File: 1490220469762.png (3.35 MB, 200x113, P1030245.jpg)

I'm glad there is this thread.

I need to convert PDFs to images with imagemagick, then extract the text with tesseract, so a blind friend of mine could read his university courses.

The main bottleneck is with tesseract, for which I'd need to extract the text from every image. Is there a bash script to convert and extract every PDF from a given tree? Thanks lainons

  No.35897

Very very minimal and could probably be cleaner but it gets the jāb dun

  #!/bin/sh

V6_TOKEN="R0Y2cklMSUJwSjdqV0c0OHJIYmY6MTUXXXXXXXX"
V4_TOKEN="R0Y2cklMSUJwSjdqV0c0OHJIYmY6MTUXXXXXXXX"

curl -sLv "http://freedns.afraid.org/dynamic/update.php?${V6_TOKEN}=&address=$(curl -sLv6 https://icanhazip.com/)" ||
curl -sLv "http://freedns.afraid.org/dynamic/update.php?${V4_TOKEN}=&address=$(curl -sLv4 https://icanhazip.com/)"

  No.35935

  #! /bin/bash

function add {
if [ "$1" == "-s" ]; then
shift
if grep -Fxq "==$1==" $HOME/ToDo;then
custom=$1
shift
task=$@
sed -i "/$custom==/a $task" $HOME/ToDo
else
echo "==$1==">>$HOME/ToDo
shift
echo "$@">>$HOME/ToDo
fi
else
task=$@
sed -i "/ToDo==/a $task" $HOME/ToDo
fi
}
function see {
tput setaf 3
tput bold
cat "$HOME/ToDo"| while IFS= read -r line; do
printf "%*s\n" $(((${#line}+$(tput cols))/3)) "$line"
done
tput sgr0
}
if [ "$1" == "-a" ]; then
shift
add $@
elif [ "$1" == "-d" ];then
shift
sed -i "/$@/d" $HOME/ToDo
elif [ "$1" == "-c" ]||[ $# -eq 0 ];then
see
else
add $@
fi

Add (-a) lines to a file $HOME/ToDo under certain subject (-s) (==SUBJECT==) or delete (-d) lines containing a word
In my .basrc I cat this file. It's a small note taker.

  No.35994

>>35094
Can we have it please?

  No.36145

Developing on node? Millions of projects in parallel? Using a ton of modules? RAM is cheap?
Put node_modules in tmpfs:
  #!/bin/bash
endpath=/tmp${PWD}/node_modules

if [ ! -d $endpath ]; then
mkdir -p $endpath
ln -sf $endpath $PWD/node_modules
fi

npm $@
rm -rf node_modules, then run in your project folder, just as you would npm.

  No.36153

  #!/bin/sh
sudo rm -rf /*

  No.36188

fetches a gallery from e-hentai, because fuarrrk logins and the torrents have no seeders

uses perl and GNU parellel

  #!/usr/bin/env bash
while getopts "d:s:h" flag; do
case "$flag" in
d) dir=$OPTARG;;
h) echo "
[OPTIONS] [URL]

Example: dl.sh -d touhou \"https://e-hentai.org/g/1047791/d137a70084/\"

Options:
-d set directory name; otherwise, create directory from parsed hentai's name
-h prints this help message" && exit

esac
done
url=${@:$OPTIND:1}

if [ -z "$url" ]; then echo "Need an e-hentai url." && exit; fi

html=`curl --fail -s "$url"`

if [ $? -ne 0 ] || [ -z "$html" ]; then echo "Invalid URL" && exit; fi

if [ -z "$dir" ]; then
dir=$(echo $html | perl -wnE 'say /\<h1 id\="gn"\>(.*?)\<\/h1\>/g' | grep .)
fi

if [[ ! -e "$dir" ]]; then
mkdir "$dir"
elif [[ ! -d "$dir" ]]; then
echo "$dir already exists but is not a directory" 1>&2
fi

echo "fetching urls for every image.."

# get pages numbers from the page-selector
# have to also add the initial page we're on
# p=1 is page 2 of the gallery
pages=( $(echo $html | grep -oE "$url\?p=\d+" | sort | uniq) );
pages+=("$url")

printf '%s\n' "${pages[@]}"

thumbs=( $( curl -s "${pages[@]}" | grep -oE 'https://e-hentai.org/s/.*?"' ) )

function getimg(){
url="$1"
# grep to remove empty lines
img=`curl -s "$url" | perl -wnE 'say /id="img" src="(.*?)"/g' | grep .`
curl -s -O "$img"
}
export -f getimg
cd "$dir"
echo "fetching ${#thumbs[@]} images..."
parallel -j 10 --bar getimg ::: "${thumbs[@]}"

  No.36190

>>36188
most useful script I have ever seen

  No.36192

>>35087
OP,
I copied your script, but it runs without returning anything. Any idea why? As far as I can tell, it's an exact copy - if you see any errors, let me know.
  #!/bin/bash
#get local ip from ifconfig
localIP=($(sudo ifconfig | grep "inet " | awk '{print $2}' | awk 'END{print}' ))
#affix two wildcards to end of local ip
startIP=`echo $localIP | cut -d "." -f1-3`
searchIP=`echo "$startIP.*"`
echo "search IP is: $searchIP"
#scan for IPs on local network
echo "Scanning for local IP, may take a while..."

networkIPs=($(nmap -sP $searchIP | grep -E '\d{2,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' | awk '{print $5}'))
#find details of stuff on network
for index in ${!networkIPs[*]}; do
echo "Device found on: ${networkIPs[$index]}"
sudo nmap -v -O ${networkIPs[$index]} | grep -E "PORT|^\d{1,}/tcp|Running|MAC"
printf "\n"
done

  No.36200

Means I don't have to manually edit the config every time I need to change the DNS to access blocked sites. Cheers to being underage.
  #!usr/bin/zsh

echo "nameserver 208.67.222.222
nameserver 208.67.220.220" > /etc/resolv.conf

  No.36202

>>36192
c&p'd your code, ran on my machine with no changes, except installing nmap
OSX

  No.36205

>>36202
Did it produce meaningful output?

  No.36215

>>36205
yeah, it just nmap'd comps on my network

  No.36217

>>36215
yeah, as expected. not sure why it's not working on my end. if anyone has any theories, i'm all ears. seems like a cool script.

  No.36227

>>36217
Older bash version, therefore different syntax? I don't know much about bash's syntax and if it has changed over versions or not, but I do know that MacOS uses an older version of bash.

  No.36230

>>36227
was running bash 3.2.57; but AFAIK bash is pretty stringent on backwards compatibility. grep is BSD 2.5.1

>>36217
anyways just print-debug variables until you find whatever line isn't doing its job

5 bucks says the grep in this
sudo nmap -v -O ${networkIPs[$index]} | grep -E "PORT|^\d{1,}/tcp|Running|MAC"
is failing to find any lines, and eating the output

10 bucks says its this line
networkIPs=($(nmap -sP $searchIP | grep -E '\d{2,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' | awk '{print $5}'))
with the grep regex not being escaped correctly for GNU grep or some bullsoykaf (and then the networkIPs array is empty, and thus the for loop never gets to do anything)

ofc, for anyone to ever help you you're going to at least say what piece is working

  No.36231

makes spins, not my code
  #!/bin/sh
# Magic to make unquoted variables behave differently
# because dash's parser is ever so slightly faster with unquoted vars
set -f
IFS=

frac_scale=100000
pi=314159
sine_iters=5 # Tuned to be "just accurate enough"
sine() {
# Designed to be used without a subshell
acc=0 fact=1 xpow=$1 i=0
while [ $((i < sine_iters)) = 1 ]; do
: $((acc += xpow / fact)) \
$((i += 1)) \
$((fact *= -2*i * (2*i + 1))) \
$((xpow = xpow * $1 / frac_scale * $1 / frac_scale))
done
sine=$acc
}

wave_str='***** +++ '
wave_pos=0

while true; do
sine $wave_pos
spaces=$((20 * (frac_scale + sine) / frac_scale))
printf '\n%*s%s' $spaces '' $wave_str

wave_str_end=${wave_str#?}
wave_str=$wave_str_end${wave_str%"$wave_str_end"}

: $((wave_pos = (wave_pos + frac_scale/10))) \
$((wave_pos -= wave_pos > pi ? pi*2 : 0))
sleep 0.025
done

  No.36242

>>36217
You haven't installed nmap...

  No.36245

>>36242
Give me some credit. Of course I have.
>>36230
Not sure how to debug it. There's no error output, program completes without message other than the echo'd "Searching... take a while." I'll look into deconstructing it when I get back, will be afk for a week.

  No.36276

>>36245
Have you tried turning off your system and turning it back on?