Tag Archives: bash

limit user bash shell with python

Simple use bdsh.py:

#!/usr/bin/python
# Copyright (C) 2013 - Remy van Elst

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program. If not, see .

# This script can act as a shell for a user, allowing specific commands only.
# It tries its best to only allow those comamnds and strip possibly dangerous
# things like ; or >. But it won't protect you if you allow the vim command
# and the user executes !bash via vim (and such). It also logs everything to
# syslog for audit trailing purposes.

# It currently only checks commands, no parameters. This is on purpose.

import getpass, os, re, sys, syslog, signal, socket, readline

# format of whitelist: one command or regex per line
command_whitelist = "/etc/bdsh_whitelist.conf"
username = getpass.getuser()
hostname = socket.gethostname()

def log_command(command, status):
"""Log a command to syslog, either successfull or failed. """
global username
logline_failed = "[RESTRICTED SHELL]: user \"" + username + "\" NOT allowed for " + command
logline_danger = "[RESTRICTED SHELL]: user \"" + username + "\" dangerous characters in " + command
logline_success = "[RESTRICTED SHELL]: user \"" + username + "\" executed " + command
if status == "success":
syslog.syslog(logline_success)
elif status == "failed":
syslog.syslog(logline_failed)
elif status == "danger":
syslog.syslog(logline_danger)

def dangerous_characters_in_command(command):
# via http://www.slac.stanford.edu/slac/www/resource/how-to-use/cgi-rexx/cgi-esc.html
danger = [';', '&', '|', '>', '<', '*', '?', '`', '$', '(', ')', '{', '}', '[', ']', '!', '#'] for dangerous_char in danger: for command_char in command: if command_char == dangerous_char: return True def entire_command_scanner(command): danger = ["&&"] for dangerous_char in danger: if re.findall(dangerous_char, command): return True def execute_command(command): """First log, then execute a command""" log_command(command, "success") # try: # subprocess.call(command, shell=False) # except OSError: # pass os.system(command) def command_allowed(command, whitelist_file=command_whitelist): """Check if a command is allowed on the whitelist.""" try: with open(whitelist_file, mode="r") as whitelist: for line in whitelist: # We are reading commands from a file, therefore we also read the \n. if command + "\n" == line: return True else: continue except IOError as e: sys.exit("Error: %s" % e) def interactive_shell(): global username global hostname while True: prompt = username + "@" + hostname + ":" + os.getcwd() + " $ " try: if sys.version_info[0] == 2: command = raw_input(prompt) else: command = input(prompt) # Catch CRTL+D except EOFError: print("") sys.exit() if command == "exit" or command == "quit": sys.exit() elif command: if not entire_command_scanner(command): if command_allowed(command.split(" ", 1)[0]): for chars in command: if dangerous_characters_in_command(chars): log_command(command, "danger") # Don't let the user know via an interactive shell and don't exit command="" execute_command(command) if __name__ == "__main__": ## Catch CTRL+C / SIGINT. s = signal.signal(signal.SIGINT, signal.SIG_IGN) arguments = "" for args in sys.argv: if dangerous_characters_in_command(args): log_command(args, "danger") sys.exit() ## No Arguments? Then we start an interactive shell. if len(sys.argv) < 2: interactive_shell() else: ## Check if we are not launched via the local shell with a command (./shell.py ls) if sys.argv[1] and sys.argv[1] != "-c" and command_allowed(sys.argv[1].split(" ", 1)[0]) and not entire_command_scanner(sys.argv[1]): for arg in sys.argv[1:]: arguments += arg arguments += " " execute_command(arguments) ## Check if we are launched via the local shell and the command is not allowed elif len(sys.argv) < 3: for arg in sys.argv: arguments += arg arguments += " " log_command(arguments, "failed") elif sys.argv[2] and command_allowed(sys.argv[2].split(" ", 1)[0]) and not entire_command_scanner(sys.argv[2]): for arg in sys.argv[2:]: arguments += arg arguments += " " execute_command(arguments) else: for arg in sys.argv: arguments += arg arguments += " " log_command(arguments, "failed") # Debug use # print("\"" + arguments + "\"") ## Give back the CTRL+C / SIGINT signal.signal(signal.SIGINT, s)

bash bytes coneverter to human

b2h()
{
# By: Simon Sweetwater
# Spotted Script @: http://www.linuxjournal.com/article/9293?page=0,1
# Convert input parameter (number of bytes)
# to Human Readable form
#
SLIST="bytes,KB,MB,GB,TB,PB,EB,ZB,YB"

POWER=1
VAL=$( echo "scale=2; $1 / 1" | bc)
VINT=$( echo $VAL / 1024 | bc )
while [ ! $VINT = "0" ]
do
let POWER=POWER+1
VAL=$( echo "scale=2; $VAL / 1024" | bc)
VINT=$( echo $VAL / 1024 | bc )
done

echo $VAL$( echo $SLIST | cut -f$POWER -d, )
}

k2h()
{
# Convert input parameter (number of kilobytes)
# Spotted Script @: http://www.linuxjournal.com/article/9293?page=0,1
# to Human Readable form
# MODIFIED BY kossboss
SLIST="bytes,KB,MB,GB,TB,PB,EB,ZB,YB"
POWER=1
VAL=$( echo "scale=2; $1 * 1024 / 1" | bc)
VINT=$( echo $VAL / 1024 | bc )
while [ ! $VINT = "0" ]
do
let POWER=POWER+1
VAL=$( echo "scale=2; $VAL / 1024" | bc)
VINT=$( echo $VAL / 1024 | bc )
done
echo $VAL$( echo $SLIST | cut -f$POWER -d, )
}

bash menu box

Bash dialog box constructing:

#!/bin/bash
# utilitymenu.sh - A sample shell script to display menus on screen
# Store menu options selected by the user
INPUT=/tmp/menu.sh.$$

# Storage file for displaying cal and date command output
OUTPUT=/tmp/output.sh.$$

# get text editor or fall back to vi_editor
vi_editor=${EDITOR-vi}

# trap and delete temp files
trap "rm $OUTPUT; rm $INPUT; exit" SIGHUP SIGINT SIGTERM

#
# Purpose - display output using msgbox
# $1 -> set msgbox height
# $2 -> set msgbox width
# $3 -> set msgbox title
#
function display_output(){
local h=${1-10} # box height default 10
local w=${2-41} # box width default 41
local t=${3-Output} # box title
dialog --backtitle "Linux Shell Script Tutorial" --title "${t}" --clear --msgbox "$(<$OUTPUT)" ${h} ${w} } # # Purpose - display current system date & time # function show_date(){ echo "Today is $(date) @ $(hostname -f)." >$OUTPUT
display_output 6 60 "Date and Time"
}
#
# Purpose - display a calendar
#
function show_calendar(){
cal >$OUTPUT
display_output 13 25 "Calendar"
}
#
# set infinite loop
#
while true
do

### display main menu ###
dialog --clear --help-button --backtitle "Linux Shell Script Tutorial" \
--title "[ M A I N - M E N U ]" \
--menu "You can use the UP/DOWN arrow keys, the first \n\
letter of the choice as a hot key, or the \n\
number keys 1-9 to choose an option.\n\
Choose the TASK" 15 50 4 \
Date/time "Displays date and time" \
Calendar "Displays a calendar" \
Editor "Start a text editor" \
Exit "Exit to the shell" 2>"${INPUT}"

menuitem=$(<"${INPUT}") # make decsion case $menuitem in Date/time) show_date;; Calendar) show_calendar;; Editor) $vi_editor;; Exit) echo "Bye"; break;; esac done # if temp files found, delete em [ -f $OUTPUT ] && rm $OUTPUT [ -f $INPUT ] && rm $INPUT

apache add virtualhost from cli

This works for Debian and Ubuntu apache create/delete virtual host:

#!/bin/bash
### Set Language
TEXTDOMAIN=virtualhost

### Set default parameters
action=$1
domain=$2
rootdir=$3
owner=$(who am i | awk '{print $1}')
email='webmaster@localhost'
sitesEnable='/etc/apache2/sites-enabled/'
sitesAvailable='/etc/apache2/sites-available/'
userDir='/var/www/'
sitesAvailabledomain=$sitesAvailable$domain.conf

### don't modify from here unless you know what you are doing ####

if [ "$(whoami)" != 'root' ]; then
echo $"You have no permission to run $0 as non-root user. Use sudo"
exit 1;
fi

if [ "$action" != 'create' ] && [ "$action" != 'delete' ]
then
echo $"You need to prompt for action (create or delete) -- Lower-case only"
exit 1;
fi

while [ "$domain" == "" ]
do
echo -e $"Please provide domain. e.g.dev,staging"
read domain
done

if [ "$rootdir" == "" ]; then
rootdir=${domain//./}
fi

if [ "$action" == 'create' ]
then
### check if domain already exists
if [ -e $sitesAvailabledomain ]; then
echo -e $"This domain already exists.\nPlease Try Another one"
exit;
fi

### check if directory exists or not
if ! [ -d $userDir$rootdir ]; then
### create the directory
mkdir $userDir$rootdir
### give permission to root dir
chmod 755 $userDir$rootdir
### write test file in the new domain dir
if ! echo "" > $userDir$rootdir/phpinfo.php
then
echo $"ERROR: Not able to write in file $userDir/$rootdir/phpinfo.php. Please check permissions"
exit;
else
echo $"Added content to $userDir$rootdir/phpinfo.php"
fi
fi

### create virtual host rules file
if ! echo "

ServerAdmin $email
ServerName $domain
ServerAlias $domain
DocumentRoot $userDir$rootdir

AllowOverride All


Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require all granted

ErrorLog /var/log/apache2/$domain-error.log
LogLevel error
CustomLog /var/log/apache2/$domain-access.log combined
" > $sitesAvailabledomain
then
echo -e $"There is an ERROR creating $domain file"
exit;
else
echo -e $"\nNew Virtual Host Created\n"
fi

### Add domain in /etc/hosts
if ! echo "127.0.0.1 $domain" >> /etc/hosts
then
echo $"ERROR: Not able to write in /etc/hosts"
exit;
else
echo -e $"Host added to /etc/hosts file \n"
fi

if [ "$owner" == "" ]; then
chown -R $(whoami):$(whoami) $userDir$rootdir
else
chown -R $owner:$owner $userDir$rootdir
fi

### enable website
a2ensite $domain

### restart Apache
/etc/init.d/apache2 reload

### show the finished message
echo -e $"Complete! \nYou now have a new Virtual Host \nYour new host is: http://$domain \nAnd its located at $userDir$rootdir"
exit;
else
### check whether domain already exists
if ! [ -e $sitesAvailabledomain ]; then
echo -e $"This domain does not exist.\nPlease try another one"
exit;
else
### Delete domain in /etc/hosts
newhost=${domain//./\\.}
sed -i "/$newhost/d" /etc/hosts

### disable website
a2dissite $domain

### restart Apache
/etc/init.d/apache2 reload

### Delete virtual host rules files
rm $sitesAvailabledomain
fi

### check if directory exists or not
if [ -d $userDir$rootdir ]; then
echo -e $"Delete host root directory ? (y/n)"
read deldir

if [ "$deldir" == 'y' -o "$deldir" == 'Y' ]; then
### Delete the directory
rm -rf $userDir$rootdir
echo -e $"Directory deleted"
else
echo -e $"Host directory conserved"
fi
else
echo -e $"Host directory not found. Ignored"
fi

### show the finished message
echo -e $"Complete!\nYou just removed Virtual Host $domain"
exit 0;
fi

bash simple network meeter

#!/bin/bash
IF=$1
if [ -z "$IF" ]; then
IF=`ls -1 /sys/class/net/ | head -1`
fi
RXPREV=-1
TXPREV=-1
echo "Listening $IF..."
while [ 1 == 1 ] ; do
RX=`cat /sys/class/net/${IF}/statistics/rx_bytes`
TX=`cat /sys/class/net/${IF}/statistics/tx_bytes`
if [ $RXPREV -ne -1 ] ; then
let BWRX=$RX-$RXPREV
let BWTX=$TX-$TXPREV
echo "Received: $BWRX B/s Sent: $BWTX B/s"
fi
RXPREV=$RX
TXPREV=$TX
sleep 1
done

bash colors cheat

Black 0;30 Dark Gray 1;30
Blue 0;34 Light Blue 1;34
Green 0;32 Light Green 1;32
Cyan 0;36 Light Cyan 1;36
Red 0;31 Light Red 1;31
Purple 0;35 Light Purple 1;35
Brown/Orange 0;33 Yellow 1;33
Light Gray 0;37 White 1;37

echo -e “\e[;31mI love \e[;1;32mcolors\e[0m \e[;0;34m so \e[;1;30m much. \e[0m”

\e[0m -> No Color

You can also use tput:

echo “$(tput setaf 1)Red text $(tput setab 7)and white background$(tput sgr 0)”

Foreground & background color commands:
tput setab [1-7] # Set the background colour using ANSI escape
tput setaf [1-7] # Set the foreground colour using ANSI escape

Colors are as follows:

Num Colour #define R G B

0 black COLOR_BLACK 0,0,0
1 red COLOR_RED 1,0,0
2 green COLOR_GREEN 0,1,0
3 yellow COLOR_YELLOW 1,1,0
4 blue COLOR_BLUE 0,0,1
5 magenta COLOR_MAGENTA 1,0,1
6 cyan COLOR_CYAN 0,1,1
7 white COLOR_WHITE 1,1,1

rsync error: protocol incompatibility (code 2) at compat.c(171) [sender=3.0.6]

If you have this kind of error:

tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified
protocol version mismatch — is your shell clean?
(see the rsync man page for an explanation)
rsync error: protocol incompatibility (code 2) at compat.c(171) [sender=3.0.6]

Fix.

vi /root/.bashrc

if [[ $- != *i* ]] ; then
# Shell is non-interactive. Be done now!
return
fi