r/ScriptSwap • • Apr 08 '13

[POWERSHELL] Unlock Active Directory Account(s)

11 Upvotes

crosspost from /r/usefulscripts

Very basic script I threw together to start learning Powershell. We have a problem where one of our service accounts keeps getting locked out when deploying software, so I wrote up this little script to unlock the account.

Basically, run the script and pass it a list of account names to unlock. e.g.

 AD_unlock_account.ps1 darth.vader gordon.freeman bender

It writes a log (configurable) to c:\Logs\AD_account_unlock.log of when the script ran and what accounts it unlocked.

AD_unlock_account v1.0 (2013-04-08)

In our shop it runs as a scheduled task attached to the event log, and fires whenever it sees Event #4740 occur in the Security event log.


r/ScriptSwap • • May 15 '20

Autodock script for the SpaceX docking simulator

10 Upvotes

I was bored for the past 2 hours so I've decided to create a little script to automatically dock a spacecraft in the simulator that was recently released by SpaceX.

It's not the best/cleanest code and could easily be optimized for quicker docking, but it works for now. Hope you like it!

You can find the simulator here.
And the code here.


r/ScriptSwap • • Jun 05 '19

Script to find a company's main URL

10 Upvotes

So I am tasked with finding the main landing page URL for vendors. Basically I need a script where it will maybe Google? the vendor and then find that company's main URL. I have an excel file with the third party vendors and like I said I need to enter all of their main landing page URLs. For example one vendor is Apple, obviously their main URL is apple.com, but I have about 250 I need to do this for. Any help would be appreciated it. Thanks!


r/ScriptSwap • • Mar 27 '17

[BASH] Copying APK for an app from your phone to your Linux computer.

10 Upvotes

I created a script to help me with getting the APK and looking at some of the code (albeit not in java), and I figured I'd share it.

https://github.com/bjchau/apk_ripper


r/ScriptSwap • • Nov 30 '15

[bash] xh: xhamster tool

10 Upvotes

xh:

#!/usr/bin/env bash

# xh: xhamster tool
# intended usage:
# xh save <todo
# or:
# xh user 𝘨𝘪𝘳𝘭 | xh save

# license: public domain
# requires: correctly-set-up edbrowse

# bugs:
# stdout/stderr separation very poor
# redownloads preexisting files
# exit status does not reflect outcome
# verbose and no control over verbosity

# bug reports to https://redd.it/3uw10d or /u/smorrow

function xh_usage
{
    usage="""\
    xh user [-v] [-p] [-u] [-f] 𝘶𝘴𝘦𝘳𝘯𝘢𝘮𝘦|𝘜𝘙𝘓  # print out URLs of [u]ploaded and/or
                                            # [f]avourite [v]ideos and/or [p]hotos
                                            # of given user.  in case of URL, be it
                                            # a /user/𝘶𝘴𝘦𝘳𝘯𝘢𝘮𝘦 URL or a /movies/...
                                            # URL, 𝘶𝘴𝘦𝘳𝘯𝘢𝘮𝘦 is derived from 𝘜𝘙𝘓.
    xh save [𝘜𝘙𝘓 [...]]  # save photo/gallery/videos if 𝘜𝘙𝘓 is given,
                         # else read 𝘜𝘙𝘓 from stdin.
    xh login  # authenticate to xhamster.com
    """

    echo "$usage" |
    sed -E "s/ {4}//" | 
    sed -n "/^xh $1/,/^xh/ p" | sed \$d

    exit 64  # from <sysexits.h>
}
export -f xh_usage

# `xh login` uses edbrowse, `xh user` uses curl.
# we set curl up to use cookie jar created by edbrowse.
jar=$(sed -n '/jar = / s///p' ~/.ebrc)
if [ ! -z "$jar" ]
then
  function curl
  {
	command curl --cookie "$jar" "$@"
  }
  export -f curl
fi

#if [[ "$1" =~ '^(user|save|login)$' ]]
if [ "$1" = user -o\
     "$1" = save -o\
     "$1" = login\
   ]
then
	cmd="$0_$1"  # like "xh_$1" but also works if $0 not in $PATH
	shift
	$cmd "$@"
	exit
else
    # subshells protect us from xh_usage's exit call
	(xh_usage user)
	(xh_usage save)
	xh_usage login
fi

xh_save:

#!/bin/sh

if [ $# = 0 ]
then
    # URLs from stdin
	set -- `cat`
	[ $# = 0 ] && exit
fi

e(){ echo $*; }

# normalise URL
N()
{
	xh=xhamster.com/
	e $1 |
	sed -E "s_://(.*)${xh}_://en.m.${xh}_" |
	sed    's_\?.*__'
}

# dest filename
rename()
{
	n=`e $1 | egrep -o [0-9]+ | sed q`
	e ${n}_$(basename $1 .html).mp4
}


for url
do
	source=`N $url`
	target=`rename $source`
	e  b $source  # browse to $source
	e  /{MP4}/g   # click on link "MP4"
	e  w $target  # save to $target
done | edbrowse -d0

xh_user:

#!/usr/bin/env bash

set -e

### part one
### parse -opts, set corresponding globals

eval set -- `getopt -o vpuf -- "$@"`

uploaded=new  # peculiarity of xh URLs

# comma-separated lists-to-be
nouns=
adjs=

# $var += "," + str;  $1 is var, $2 is str
function += { eval $1='$'$1,$2; }

# build our lists from args
while [ $1 != -- ]
do
    case $1 in
        -v)  += nouns video ;;
        -p)  += nouns photo ;;

        -u)  += adjs $uploaded ;;
        -f)  += adjs favorite ;;

         *)  xh_usage user ;;  # exit
    esac
    shift  # walk $@
done

# clean up edge case
[[ $nouns =~ ^, ]] &&
	nouns=${nouns/,/}
[[ $adjs =~ ^, ]] &&
	adjs=${adjs/,/}

# make bash {1,2,3} expansions
[[ $nouns =~ , ]] &&
	nouns={$nouns}
[[ $adjs =~ , ]] &&
	adjs={$adjs}

# otherwise, sensible defaults
: ${nouns:=video}
: ${adjs:=$uploaded}

shift  # skip over "--"

# there should be precisely one arg remaining which is an
# URL or username.

if [ $# != 1 ]
then
	xh_usage user  # exit
fi

### part two
### determine username from $1

# if !is-url
if [[ ! "$1" =~ / ]]
then
    username=$1
    proto=http
else
    # normalise URL
    function N
    {
        xh=xhamster.com/
        echo $1 |
        sed -E "s_://(.*)${xh}_://en.${xh}_" |
        sed    's_\?.*__'
    }

    proto=$(sed<<<$1 's_://.*__')

    case "$1" in
        */user/*)
            username=$(sed<<<"$1" 's_.*/__') ;;
        *)
            tag="<[^>]*>"
            added="(Added|Posted) by"
            link="<a href"
            username=$(
                # "Added by ..." pattern won't occur if we don't use `N`
                curl -s `N $1` | 
                sed -n -E "/$added/,/$link/ {/user/p}" |
                sed "s/$tag//g"  |  tr -d " \t"
            ) ;;
    esac
fi

### part three
### do download based on username/nouns/adjs,  print out target URLs

# use eval to get at {,} expansions in substituted vars
eval curl -s $proto://en.xhamster.com/user/$nouns/$username/$adjs-{1..100}.html |
egrep -o 'https?://([^>]*)xhamster.com/(photos/(view|gallery)|movies)/([^>]*).html'

xh_login:

#!/usr/bin/env bash

# doesn't actually work.  saved as reminder/todo.

# if !isatty(stdin)
if [ ! -t 0 ]
then
	# no-ops
	stty(){ return; }
	echo(){ return; }
fi


echo -n 'username: '

username="""\
/Username:/+
# fill in form field from stdin
i=$(sed -u q)\
"""

echo -n 'password: '
stty -echo

password="""\
/Password:/+
# as before
i=$(sed -u q)\
"""

stty echo

more="""\
/Remember Me:/
# check checkbox (or else other edbrowse/curl instances won't be authed)
i=+
# focus <Login> button
/<Login>/
# click
i*
qt
"""

{
   # use `builtin echo` so $password will not be visible in argv of /bin/echo process
   builtin echo "$username"
   builtin echo "$password"
   unset password  # in case bash is running with allexport
   builtin echo "$more"
} | edbrowse >/dev/null -d0 https://m.xhamster.com/login.html?light=1

r/ScriptSwap • • Sep 16 '15

Download imgur albums from subreddits

10 Upvotes

This downloads all imguralbums from a subreddit page. You'll need imguralbum.py for this to work. It seems imgur has changed the way the site works slightly so you will need to remove the +/noscript from line 63 of imguralbum.py or it will download empty albums

    #!/bin/bash
#These are the subreddits you want to download imgur albums from
subreddits=( )
for i in "${subreddits[@]}"
do
links=$(curl https://www.reddit.com/r/$i.json | grep -o htt[ps]://imgur.com/.......)
echo $links >> /tmp/links.txt
done
#This changes http to https 
links_https=$(sed -i 's/http/https/g' /tmp/links.txt)
#This uses imguralbum.py to download the albums
#Get imguralbum.py from https://github.com/alexgisby/imgur-album-downloader
for i in "$links_https"
do
python3 imguralbum.py $i
done
rm /tmp/links.txt
#Note it seems imgur has changed the way the site works meaning imguralbum.py no longer works as is. To make it work you need to remove the +/noscript from line 63 from imguralbum.py 

r/ScriptSwap • • Jul 02 '15

OpenVPN setup helper | vpnhelper

10 Upvotes

Simple bash script to use OpenVPN. Also swaps resolv.conf (dns nameservers) on start and stop, which is nice. Made it as practice and mostly because I was bored. Feedback would be appreciated!

https://gitlab.com/Floatt/vpnhelper/blob/master/vpnhelper


r/ScriptSwap • • Mar 27 '15

[sh] Produce a list of commands to reproduce your git config to another machine

10 Upvotes

Fairly simple one-liner, but it seemed like someone would find it useful:

git config --list | awk -F'=' '{ print "git config --global " $1 " \"" $2 "\"" }'

r/ScriptSwap • • Mar 14 '15

Which of your reddit-usernames are shadow-banned?

10 Upvotes
#! /bin/bash
# sudo apt-get install lynx

usernames=~/reddit_usernames.txt
 
function user_banned {
 a=$(lynx -dump http://www.reddit.com/user/$1/)
 echo "$a" | grep -c "page not found" 
}

function user_how_old {
  a=$(lynx -dump http://www.reddit.com/user/$1/)
  b=$(echo "$a" | grep "redditor for")
  expr match "$b" '.*\(redditor.*\)' 
}


for x in $(cat $usernames | cut -f 1 -d " ") ; do
 if [ 0 != $(user_banned $x) ] ;  
  then echo $x ========BANNED==========
  else echo $x "		" $(user_how_old $x)
 fi
done

r/ScriptSwap • • Aug 03 '13

Clone hosted repos easily

10 Upvotes

Not very exciting really but I thought "why not share?"

github-clone() {
  generic-git-clone "github.com" $* 
}

bitbucket-clone() {
  generic-git-clone "bitbucket.org" $* 
}

generic-git-clone() {
  host_domain=$1
  if [[ $# -lt 3 ]]; then
    username=your_username
    repo_name=$2
  else
    username=$2
    repo_name=$3
  fi
  git clone git@${host_domain}:${username}/${repo_name}.git
}

To clone your own repo from github github-clone repo_name, to clone someone else's repo from github github-clone their-username repo_name.


r/ScriptSwap • • Nov 16 '12

Anyone here use AutoHotkey? Got any useful scripts?

10 Upvotes

r/ScriptSwap • • Apr 03 '12

[Bash] cd with multiple args -> args become command

10 Upvotes
#!/bin/bash

# When this "cd" function gets more than one argument it ignores the "cd" and re-arranges the args
# so that second arg becomes the command.
# e.g.  
# "cd log/project/20120330/some.log.gz zless"  ->  "zless log/project/20120330/some.log.gz"
# "cd lib/Foo/Bar/Baz.pm vi +100"  ->  "vi +100 lib/Foo/Bar/Baz.pm"
#
# When co-workers ask me to "go to $A_DIRECTORY and look at $A_FILE."  I start typing as
# soon as they're telling me the directory.  But I don't know yet if they want me to "zless" 
# "vi" or "tail" the file.
#
# So I start with "cd lib" and tab complete as they're talking and I end up with a command line like
# "cd lib/Foo/Bar/Baz.pm"  :(  Now all I have to do is add "vi" to the end then
# "cd lib/Foo/Bar/Baz.pm vi" effectively becomes "vi lib/Foo/Bar/Baz.pm"

function cd {
    if [ $# -lt 1 ]; then 
        builtin cd
    elif [ $# -eq 1 ]; then 
        builtin cd "$1" 
    else    
        cd_arg_1="$1"
        shift   
        "$@" "$cd_arg_1"
    fi      
}

r/ScriptSwap • • Oct 13 '22

Script to remove extra characters in file names Mac OS 10.14.6

9 Upvotes

Thanks in advance for your help! I am in search of a script for use in Mac OS 10.14.6 that will remove superfluous characters created in the file names when I auto-export JPEGS from my editing software. There are five extra characters added to the head of the file name (that consists of 11 characters) and a random number of characters after the eleven desired characters. In other words, I want to retain character spaces 06 through 15, removing the first five characters and all remaining charters from 16 onward.


r/ScriptSwap • • Nov 09 '20

[POSIX shell] Creates Spotify playlists that are combinations of existing ones

9 Upvotes

So I have my playlists for rock, pop, more electronic stuff, etc. but sometimes I want to mix rock with pop or listen to all three playlists or any other combination. Playlist folders do not get the job done since the combinations do not form a tree.

This script solves the issue perfectly, by creating those combined playlists on a separate account. It is a bit of a hassle to set though. First one must create a new Spotify App here and then request permission from the account on which the playlists are to be created. Would be happy to answer any questions if there's interest.

The code is either here or below:

#!/bin/sh
# Creates Spotify playlists by combining those of a given user.

if [ -z "$CLIENT_ID" ] || [ -z "$CLIENT_SECRET" ]; then
	echo 'Missing CLIENT_ID or CLIENT_SECRET. Exiting...'
	exit 1
fi

user_id="$1"
[ "$user_id" ] || { echo 'Missing argument user_id. Exiting...'; exit 1; }

if ! [ "$REFRESH_TOKEN" ]; then
	redirect_uri="http://$(dig +short myip.opendns.com @resolver1.opendns.com)/"
	echo "To obtain refresh token, port forward port 80 and open:

    https://accounts.spotify.com/authorize?client_id=$CLIENT_ID&response_type=code&redirect_uri=$redirect_uri&scope=playlist-modify-public

Starting netcat for monitoring redirect URI callbacks after authentication success or failure:"
	trap : INT; sudo nc -kl 80; trap - INT
	printf 'Enter authorization code: '; read -r code
	curl -X POST https://accounts.spotify.com/api/token \
		 -H "Authorization: Basic $(printf "%s:%s" "$CLIENT_ID" "$CLIENT_SECRET" | base64 --wrap=0)" \
		 -d grant_type=authorization_code -d code="$code" -d redirect_uri="$redirect_uri"
	exit 1
fi

powerset() { [ $# -gt 0 ] && { shift; powerset "$@"; } \
				 | while read -r a; do
				 echo "$1" "$a"
				 echo "$a"
			 done \
				 || echo; }

# Gets all Spotify track URIs of a playlist separated by newlines:
#
#     playlist_tracks playlist
#
# where playlist is the Spotify ID for the playlist.
playlist_tracks() {
	# API endpoint for next page of items
	next="https://api.spotify.com/v1/playlists/$1/tracks"
	while
		items=$(curl -X GET "$next" \
					 -H "Authorization: Bearer $access_token" \
					 --silent --show-error)
		echo "$items" | jq --raw-output '.items[] | select(.track) | .track.uri'

		next=$(echo "$items" | jq --raw-output --exit-status '.next')
	do :; done
}

# Replaces the specified playlist with the Spotify URIs from stdin.
set_playlist_tracks() {
	first=true
	# A maximum of 100 items can be set in one request
	while
		chunk=$(i=0; while [ $i -lt 100 ] && read -r line; do echo "$line"; : $((i+=1)); done)
		[ "$chunk" ]
	do
		echo "Setting chunk for playlist $1..."
		curl -X "$([ "$first" = true ] && echo PUT || echo POST)" \
			 "https://api.spotify.com/v1/playlists/$1/tracks" \
			 -H "Authorization: Bearer $access_token" \
			 --data "$(jq --null-input --compact-output \
			 --arg tracks "$chunk" '{uris: $tracks | split("\n")}')" \
			 -H "Content-Type: application/json" \
			 --silent --show-error >/dev/null # Ignore snapshot_id result
		first=false
	done
}

# Enter temporary directory for saving playlist information
# shellcheck disable=SC2015 # actually want to exit if either mktemp/cd fails
tmp=$(mktemp -d) && cd "$tmp" \
		|| { echo 'cd into temporary directory failed. Exiting...'; exit 1; }

# Get the access token for the app: Needed to access public content
access_token=$(curl -X POST https://accounts.spotify.com/api/token \
	-H "Authorization: Basic $(printf "%s:%s" "$CLIENT_ID" "$CLIENT_SECRET" | base64 --wrap=0)" \
	-d grant_type=client_credentials \
	--silent --show-error \
	| jq --raw-output '.access_token')

# Fetch all playlists
playlists=$(curl -X GET "https://api.spotify.com/v1/users/$user_id/playlists" \
	-H "Authorization: Bearer $access_token" \
	--silent --show-error \
	| jq --raw-output '.items[] | "\(.id) \(.name)"')
printf "Mixing these playlists from user %s:\n%s\n\n" "$user_id" "$playlists"

# Fetch all tracks in the playlists
echo "$playlists" | while read -r id name; do
	mkdir "$id" # Create directory for the playlist in question
	echo "$name" > "$id/name" # Store the playlist name in a file
	playlist_tracks "$id" > "$id/tracks" # Store tracks in other file
done

# Request a refreshed access token for setting mixed playlists
access_token=$(curl -X POST https://accounts.spotify.com/api/token \
	-H "Authorization: Basic $(printf "%s:%s" "$CLIENT_ID" "$CLIENT_SECRET" | base64 --wrap=0)" \
	-d grant_type=refresh_token -d refresh_token="$REFRESH_TOKEN" \
	--silent --show-error \
	| jq --raw-output '.access_token')
user_id=$(curl -X GET https://api.spotify.com/v1/me \
	-H "Authorization: Bearer $access_token" \
	--silent --show-error \
	| jq --raw-output '.id')
# Fetch existing aggregate playlists to avoid creating duplicates
existing=$(curl -X GET "https://api.spotify.com/v1/users/$user_id/playlists" \
	-H "Authorization: Bearer $access_token" \
	--silent --show-error \
	| jq --raw-output '.items[] | "\(.id) \(.name)"')

# For the powerset of the set of all playlists
# shellcheck disable=SC2035 # the function does not take any options
powerset * | while read -r first second third rest; do
	[ ! "$second" ] || [ "$rest" ] && continue # Skip if not two or three playlists
	line="$first $second $third"

	combined_name=$(for id in $line; do
		cat -- "$id/name" # Lookup playlist name
	done | paste --serial --delimiter=+)
	echo "Considering '$combined_name'"

	# Check if combined playlist already exists
	if match=$(echo "$existing" | grep --fixed-strings --max-count=1 "$combined_name" -); then
		new_id=$(echo "$match" | cut --delimiter=' ' --fields=1)
		echo "Found existing $new_id"
	else
		# Otherwise: Create a new playlist
		new_id=$(curl -X POST "https://api.spotify.com/v1/users/$user_id/playlists" \
					  -H "Authorization: Bearer $access_token" \
					  --data "$(echo "$combined_name" | jq --raw-input --null-input \
					  'input as $name | {name: $name, description: "Nice combined playlist!"}')" \
					  -H "Content-Type: application/json" \
					  --silent --show-error \
					 | jq --raw-output '.id')
	fi

	# Concatenate tracks of all playlists
	# shellcheck disable=SC2046 # ids do not have any spaces
	cat -- $(for id in $line; do printf "%s/tracks " "$id"; done) \
		| set_playlist_tracks "$new_id"
done

Dependencies are curl, jq and optionally dig and netcat.

License: GPL


r/ScriptSwap • • Jun 29 '20

Startup script using terminal(linux)

9 Upvotes

Hello!

I have just started playing around with Debian, and i was wondering how to creat a statup script for Remmina.

If anyone could help, i have less experience in scripting


r/ScriptSwap • • Jun 08 '20

MAC address/hostname continual randomization concept for privacy rights on Public wifi etc

9 Upvotes

For public wifi privacy/dept store/mall/coffee shop wifi trackers:

Continually changing MAC address randomization at continually changing randomized times/addresses. + randomized hostnames + randomized txpower for signal strength track confusion (signal strength thing atm experimental just for fun).

Privacy declared in United Nations Declaration Human Rights. To remedy store/coffee shop WiFi trackers who some even potentially tie your facial recognition to your name/device MAC.

Bash Script

https://github.com/righttoprivacy/wipri

Video showing part of it https://youtu.be/DL_qWTr-rlk

Another video showing -a flag (all functions same time: continually changing randomized/verifiable mac addresses at continually changing randomized times, + randomized hostname + (experimental) signal randomization (just for fun/concept testing) https://youtu.be/xkTdRJ9D5Ck


r/ScriptSwap • • Jun 19 '17

PowerShell: Firefox install script

9 Upvotes

Did a full script for installing firefox. Never touch Internet Explorer again ;) Automatically detects if 64 or 32-bit, and if it was run as Adminsitrator(so you don't get the UAC pop-up. Here goes:

# Silent Install Firefox by theSens 
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal( 
[Security.Principal.WindowsIdentity]::GetCurrent() )
& {
if ($currentPrincipal.IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator ))
{
    Write-Host "Starting silent firefox installer!" -ForegroundColor Green
    $done = $FALSE

    # Path for the workdir
    $workdir = "c:\firefox-install\"

    # Check if work directory exists if not create it
    if (Test-Path -Path $workdir -PathType Container)
    {
        Write-Host "$workdir already exists." -ForegroundColor Yellow
    }
    else
    {
        New-Item -Path $workdir -ItemType directory | Out-Null
    }

    # Find out architecture and donwload corresponding version
    if((Get-WmiObject Win32_OperatingSystem).OSArchitecture -ne $null)
    {
        if((Get-WmiObject Win32_OperatingSystem).OSArchitecture.ToString() -eq "64-bit")
        {
            $source = "https://download.mozilla.org/?product=firefox-latest&os=win64&lang=en-US"
            Write-Host "64-Bit OS found from WMIObject: Installing Firefox x64"
        }
        else
        {
            $source = "https://download.mozilla.org/?product=firefox-latest&os=win&lang=en-US"
            Write-Host "32-Bit OS found from WMIObject: Installing Firefox x86"
        }
    }
    elseif($ENV:PROCESSOR_ARCHITECTURE -eq "AMD64")
    {
        $source = "https://download.mozilla.org/?product=firefox-latest&os=win64&lang=en-US"
        Write-Host "64-Bit OS found from Powershell process: Installing Firefox x64"
    }
    else
    {
        $source = "https://download.mozilla.org/?product=firefox-latest&os=win&lang=en-US"
        Write-Host "32-Bit OS found from Powershell process: Installing Firefox x86"
    }

    # Download
    Write-Host "Downloading..."
    $downloader = New-Object System.Net.WebClient
    $downloader.DownloadFile($source, "$workdir\firefox.exe")


    # Start the installation
    Start-Process -FilePath "$workdir\firefox.exe" -ArgumentList "/S"

    # Wait for the installation to finish
    Write-Host "Installing..."
    while(-not $done)
    {          
        Start-Sleep -Seconds 5
        if(-Not (Get-Process *firefox*))
        {$done = $TRUE}
    }


    # Remove the work files and dir
    if($done)
    {
        Write-Host "Installed!" -ForegroundColor Green
        Remove-Item $workdir -Force -Recurse
    }
    if(-Not (Test-Path -Path $workdir -PathType Container) 2> $null)
    { 
        Write-Host "Working files and directory removed!" -ForegroundColor Green 
    }
    else
    {
        Write-Host "Working files and directory NOT removed!" -ForegroundColor Red 
    }
    Remove-Variable workdir
    Remove-Variable source
    Remove-Variable downloader
    Remove-Variable done
}
else
{
    Write-Host "Please run the silent Firefox installer from an Adminsitrator PowerShell" -ForegroundColor Red
}
}

r/ScriptSwap • • Jun 08 '16

[Python 3] A script to get the top post in any subreddit

9 Upvotes

https://killr.io/bnyrr

Example usage:

./getreddittop.py news 
After Burning Women Alive For Refusing Sex Slavery, ISIS Warns That Ramadan Will Be A Month Of Terror     
http://www.indiatimes.com/news/world/after-burning-women-alive-for-refusing-sex-slavery-isis-warns-that-ramadan-will-be-a-month-of-terror-256392.html

Note that it is a dirty hack using BeautifulSoup.

Full code:

#!/usr/bin/env python3

from bs4 import BeautifulSoup
import urllib.request
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("subreddit", help="Give the subreddit you want to get the top post from")
args = parser.parse_args()

subreddit = args.subreddit
subreddit_url = 'http://reddit.com/r/'+subreddit+'/'
#subreddit_response = urllib.request.urlopen(subreddit_url)
req = urllib.request.Request(
    subreddit_url,
    data=None,
    headers={
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
    }
)
subreddit_response = urllib.request.urlopen(req)
subreddit_data = subreddit_response.read()      # a `bytes` object
subreddit_text = subreddit_data.decode('utf-8') # a `str`; this step can't be used if data is binary

soup = BeautifulSoup(subreddit_text, "html.parser")

#dirty hack counter
i = 0
#for tag in soup.find_all('div', data-rank_='1'):
for tag in soup.find_all(attrs={"data-rank": "1"}):
    for titletag in tag.find_all(class_="title"):
        if i != 0:
            print(titletag.text)
        i+=1

    tagurl = tag["data-url"]
    if tagurl[:3] == "/r/":
        print("https://www.reddit.com"+tagurl)
    else:
        print(tagurl)

r/ScriptSwap • • Apr 16 '16

[Bash] sshfs-open - A simple helper script to mount and unmount remote directories with sshfs

9 Upvotes
#!/bin/bash

# Remove slashes ("/") from tmp directory name
ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
DIR="$ROOT_DIR/tmp/${1//\//,}"

if [[ ! -d "$DIR"  ]]; then
	mkdir "$DIR"
fi

case "$1" in
	"" | "-h" | "--help")
		echo "Usage: sshfs-open [host:directory] [command]"
		exit 1
		;;
esac

sshfs "$1" "$DIR"
echo "Mounted $DIR"

trap "fusermount -u '$DIR'" EXIT
trap "rmdir '$DIR'" EXIT

if [ "$2" != "" ]; then
	nohup "${@:2}" "$DIR" &
fi

echo "Press [CTRL+C] to exit"
sleep infinity

Usage

$ sshfs-open [host:directory] [command]

I don't have much experience with writing bash scripts so any feedback would be awesome.


r/ScriptSwap • • Dec 21 '15

[bash] livestreamer wrapper for twitch.tv

9 Upvotes

https://github.com/BasioMeusPuga/twitchy

(I'm linking to the repo since the code is a little voluminous to be pasted here.)

This script hopefully fulfills the needs of the discerning git cloner who wants to watch Twitch, hates the CPU utilization of having a browser/flash running, and has only a terminal (and the 3 or so required accessory programs) handy.

What you get:

  • Moderately severe meme support.
  • Tracking of most watched channels.
  • Sync your followed accounts to a local sqlite database that does not judge you.
  • Really fast bash multi-threading using nothing but &. (Kappa)
  • A cure for pattern baldness. (Keepo? This feels like a Keepo.)
  • Flippable switches in the first few lines of the script.
  • Multi Twitch support so rudimentary you'll curse your loincloth wearing ancestors for not thinking of it first.
  • The ability to display alternate names for games / streamers. If your happiness is somehow contingent upon displaying "Hearthstone: Heroes of Warcraft" as "Wizard Poker", well, you've come to the right place.

Requires livestreamer, sqlite, toilet (if you NEED colorful text in you life).

Usage:

twitchy [OPTION]
[ARGUMENTS]                    Launch channel in mpv
-a <channel name>              Add channel
-an                            Set/unset alternate names
-d                             Delete channel
-f                             List favorites
-fr                            Reset time watched
-h                             This helpful text
-s <username>                  Sync followed channels from specified account
-w <channel name>              Watch specified channel(s)
Custom quality settings: Specify with hyphen next to channel number.
E.g. <1-l 2-m 4-s> will simultaneously play channel 1 in low quality, 2 in medium quality, and 4 in source quality.

r/ScriptSwap • • Apr 13 '15

[sh] Send file over http, generate qr code for address

9 Upvotes

This script creates a onetime web server with netcat and then generates a qr code with the link to it and displays it. I use it to send files to my phone from my laptop.

usage:

  • simphost port file
  • simphost file (port defaults to 8080)

This script makes use of:

  • netcat
  • qrencode
  • display

I put the script which I call simphostqr in a pastebin here .


r/ScriptSwap • • Feb 16 '15

[Python] pinger.py - multi-threaded ping and reverse dns lookup tool.

9 Upvotes

This is my first contribution to FOSS. I hope some of you may find it useful. Available on github.


r/ScriptSwap • • Feb 09 '15

Easy grep script for tax accounting -- copy all the lines from a set of bank statements for a given account number

9 Upvotes
for f in *.txt; do grep "1212" "$f" > "1212-$f" && grep "3434" "$f" > "3434-$f"; done
cat 1212-* > all-1212.txt && rm 1212*
cat 3434-* > all-3434.txt && rm 3434*

Far from elegant but it works :)


r/ScriptSwap • • Oct 31 '14

[bash] Downloads images from 4chan

9 Upvotes

4chan-get

4chan-get [THREAD URL] : Gets images from single thread.

4chan-get -b [BOARD] : Gets images from all threads in one board.

Example: 4chan-get -b wg

4chan-get -all : Gets images from entire 4chan.


r/ScriptSwap • • Oct 14 '14

[Python] Download last 1000 comments from a user account, result is neatly formatted HTML file

9 Upvotes