I am currently testing a bash script to perform database migration.
The scripts basically accepts some parameters such as:
the name of the database to migrate
the server from which migrate it
the server to which migrate it
In the script there is a function which "builds" the mysql and mysqldump commands to be executed, depending on whether the server from/to is local/remote.
the function build_mysql_command is then used like this:
_query="$(build_mysql_command mysql from)"
_dump="$(build_mysql_command mysqldump from)"
_restore="$(build_mysql_command mysql to)"
However, when the function build_mysql_command has to call open_ssh_tunnel, it hangs on the last instruction, as I have tested by using the script with the -x switch.
If instead I put the SSH tunnel opening outside build_mysql_command, and remove the call from there, it works.
However, I do not think I made any mistake in the above functions, so I do not understand why the script would hang.
Here is a very stripped down example which shows the problem, where I replaced the actual IP address of the remote server with 1.2.3.4:
#!/bin/bash
set -x
set -o pipefail
# $1 = 'from' or 'to'
get_local_port() {
case "$1" in
from)
echo 30303
;;
to)
echo 31313
;;
*)
echo 0
;;
esac
}
# $1 = 'from' or 'to'
build_ssh_command() {
local _ssh="ssh -oUserKnownHostsFile=/dev/null -oStrictHostKeyChecking=no"
if [ ! -z "${params[password-$1]}" ] ; then
_ssh="sshpass -f ${params[password-$1]} $_ssh"
fi
echo "$_ssh"
}
# $1 = 'from' or 'to'
open_ssh_tunnel() {
# se non già aperto
if [ -z "${cleanup[ssh-tunnel-$1]}" ] ; then
local _port="$(get_local_port "$1")"
local _ssh="$(build_ssh_command "$1")"
local _pregp="fnNTL $_port:localhost:3306 ${params[migrate-$1]}"
local _command="$_ssh -$_pregp"
# tento apertura tunnel SSH
if ! $_command ; then
return 1
else
# salvo PID del tunnel così aperto
local _pid="$(pgrep -f "$_pregp" 2> /dev/null)"
if [ -z "$_pid" ] ; then
return 1
fi
cleanup["ssh-tunnel-$1"]="$_pid"
fi
fi
return 0
}
# verifica se un indirizzo fa riferimento alla macchina locale
# $1 = indirizzo da verificare
is_local_address() {
local _host="$(hostname)"
case "$1" in
localhost|"127.0.0.1"|"$_host")
return 0
;;
*)
return 1
;;
esac
}
# costruisce un comando di dump o restore MySQL
# $1 = comando di base
# $2 = tipo server ('from' o 'to')
build_mysql_command() {
local _command="$1 --user=root --password=xxx"
if is_local_address "${params[migrate-$2]}" ; then
# connessione tramite socket
_command="$_command --protocol=socket --socket=/opt/agews64/data/mysql/mysql.sock"
elif open_ssh_tunnel "$2" ; then
# altrimenti uso connessione tramite tunnel SSH
_command="$_command --protocol=tcp --host=localhost --port=$(get_local_port "$2")"
else
_command=""
fi
echo "$_command"
}
# parametri di esecuzione dello script
declare -A params=(
["migrate-from"]="localhost"
["migrate-to"]="1.2.3.4"
)
_query="$(build_mysql_command "mysql" "from")"
echo "_query = $_query"
_dump="$(build_mysql_command "mysqldump" "to")"
echo "_dump = $_dump"
# fine test
and here is the output when run:
+ set -o pipefail
+ params=(["migrate-from"]="localhost" ["migrate-to"]="1.2.3.4")
+ declare -A params
++ build_mysql_command mysql from
++ local '_command=mysql --user=root --password=xxx'
++ is_local_address localhost
+++ hostname
++ local _host=my.host.name
++ case "$1" in
++ return 0
++ _command='mysql --user=root --password=xxx --protocol=socket --socket=/opt/agews64/data/mysql/mysql.sock'
++ echo 'mysql --user=root --password=xxx --protocol=socket --socket=/opt/agews64/data/mysql/mysql.sock'
+ _query='mysql --user=root --password=xxx --protocol=socket --socket=/opt/agews64/data/mysql/mysql.sock'
+ echo '_query = mysql --user=root --password=xxx --protocol=socket --socket=/opt/agews64/data/mysql/mysql.sock'
_query = mysql --user=root --password=xxx --protocol=socket --socket=/opt/agews64/data/mysql/mysql.sock
++ build_mysql_command mysqldump to
++ local '_command=mysqldump --user=root --password=xxx'
++ is_local_address 1.2.3.4
+++ hostname
++ local _host=asp10.626suite-online.it
++ case "$1" in
++ return 1
++ open_ssh_tunnel to
++ '[' -z '' ']'
+++ get_local_port to
+++ case "$1" in
+++ echo 31313
++ local _port=31313
+++ build_ssh_command to
+++ local '_ssh=ssh -oUserKnownHostsFile=/dev/null -oStrictHostKeyChecking=no'
+++ '[' '!' -z '' ']'
+++ echo 'ssh -oUserKnownHostsFile=/dev/null -oStrictHostKeyChecking=no'
++ local '_ssh=ssh -oUserKnownHostsFile=/dev/null -oStrictHostKeyChecking=no'
++ local '_pregp=fnNTL 31313:localhost:3306 1.2.3.4'
++ local '_command=ssh -oUserKnownHostsFile=/dev/null -oStrictHostKeyChecking=no -fnNTL 31313:localhost:3306 1.2.3.4'
++ ssh -oUserKnownHostsFile=/dev/null -oStrictHostKeyChecking=no -fnNTL 31313:localhost:3306 1.2.3.4
Warning: Permanently added '1.2.3.4' (ECDSA) to the list of known hosts.
+++ pgrep -f 'fnNTL 31313:localhost:3306 1.2.3.4'
++ local _pid=8919
++ '[' -z 8919 ']'
++ cleanup["ssh-tunnel-$1"]=8919
++ return 0
+++ get_local_port to
+++ case "$1" in
+++ echo 31313
++ _command='mysqldump --user=root --password=xxx --protocol=tcp --host=localhost --port=31313'
++ echo 'mysqldump --user=root --password=xxx --protocol=tcp --host=localhost --port=31313'
As you can see, the script hangs at the very last line of build_mysql_command when it has opened the SSH tunnel to the remote server, but shows no problem when it builds the local command.
Related
Im trying to get openconnect vpn client on mac osx to use this default script, but im getting the following error.
/etc/vpnc/vpnc-script: line 730: syntax error: unexpected end of file
Script '/etc/vpnc/vpnc-script' returned error 2
I was getting a similar error before following a post explaining to use this formatting which I copy pasted exactly. I then ran chmod 777 on the file to give make it executable.
Thanks in advance for your help!
#!/bin/sh
# List of parameters passed through environment
#* reason -- why this script was called, one of: pre-init connect disconnect
#* VPNGATEWAY -- vpn gateway address (always present)
#* TUNDEV -- tunnel device (always present)
#* INTERNAL_IP4_ADDRESS -- address (always present)
#* INTERNAL_IP4_MTU -- mtu (often unset)
#* INTERNAL_IP4_NETMASK -- netmask (often unset)
#* INTERNAL_IP4_NETMASKLEN -- netmask length (often unset)
#* INTERNAL_IP4_NETADDR -- address of network (only present if netmask is set)
#* INTERNAL_IP4_DNS -- list of dns servers
#* INTERNAL_IP4_NBNS -- list of wins servers
#* INTERNAL_IP6_ADDRESS -- IPv6 address
#* INTERNAL_IP6_NETMASK -- IPv6 netmask
#* INTERNAL_IP6_DNS -- IPv6 list of dns servers
#* CISCO_DEF_DOMAIN -- default domain name
#* CISCO_BANNER -- banner from server
#* CISCO_SPLIT_INC -- number of networks in split-network-list
#* CISCO_SPLIT_INC_%d_ADDR -- network address
#* CISCO_SPLIT_INC_%d_MASK -- subnet mask (for example: 255.255.255.0)
#* CISCO_SPLIT_INC_%d_MASKLEN -- subnet masklen (for example: 24)
#* CISCO_SPLIT_INC_%d_PROTOCOL -- protocol (often just 0)
#* CISCO_SPLIT_INC_%d_SPORT -- source port (often just 0)
#* CISCO_SPLIT_INC_%d_DPORT -- destination port (often just 0)
#* CISCO_IPV6_SPLIT_INC -- number of networks in IPv6 split-network-list
#* CISCO_IPV6_SPLIT_INC_%d_ADDR -- IPv6 network address
#* CISCO_IPV6_SPLIT_INC_$%d_MASKLEN -- IPv6 subnet masklen
# FIXMEs:
# Section A: route handling
# 1) The 3 values CISCO_SPLIT_INC_%d_PROTOCOL/SPORT/DPORT are currently being ignored
# In order to use them, we'll probably need os specific solutions
# * Linux: iptables -t mangle -I PREROUTING <conditions> -j ROUTE --oif $TUNDEV
# This would be an *alternative* to changing the routes (and thus 2) and 3)
# shouldn't be relevant at all)
# 2) There are two different functions to set routes: generic routes and the
# default route. Why isn't the defaultroute handled via the generic route case?
# 3) In the split tunnel case, all routes but the default route might get replaced
# without getting restored later. We should explicitely check and save them just
# like the defaultroute
# 4) Replies to a dhcp-server should never be sent into the tunnel
# Section B: Split DNS handling
# 1) Maybe dnsmasq can do something like that
# 2) Parse dns packets going out via tunnel and redirect them to original dns-server
#env | sort
#set -x
# =========== script (variable) setup ====================================
PATH=/sbin:/usr/sbin:$PATH
OS="`uname -s`"
HOOKS_DIR=/etc/vpnc
DEFAULT_ROUTE_FILE=/var/run/vpnc/defaultroute
RESOLV_CONF_BACKUP=/var/run/vpnc/resolv.conf-backup
SCRIPTNAME=`basename $0`
# some systems, eg. Darwin & FreeBSD, prune /var/run on boot
if [ ! -d "/var/run/vpnc" ]; then
mkdir -p /var/run/vpnc
[ -x /sbin/restorecon ] && /sbin/restorecon /var/run/vpnc
fi
# stupid SunOS: no blubber in /usr/local/bin ... (on stdout)
IPROUTE="`which ip | grep '^/'`" 2> /dev/null
if ifconfig --help 2>&1 | grep BusyBox > /dev/null; then
ifconfig_syntax_inet=""
else
ifconfig_syntax_inet="inet"
fi
if [ "$OS" = "Linux" ]; then
ifconfig_syntax_ptp="pointopoint"
route_syntax_gw="gw"
route_syntax_del="del"
route_syntax_netmask="netmask"
else
ifconfig_syntax_ptp=""
route_syntax_gw=""
route_syntax_del="delete"
route_syntax_netmask="-netmask"
fi
if [ "$OS" = "SunOS" ]; then
route_syntax_interface="-interface"
ifconfig_syntax_ptpv6="$INTERNAL_IP6_ADDRESS"
else
route_syntax_interface=""
ifconfig_syntax_ptpv6=""
fi
if [ -r /etc/openwrt_release ] && [ -n "$OPENWRT_INTERFACE" ]; then
. /etc/functions.sh
include /lib/network
MODIFYRESOLVCONF=modify_resolvconf_openwrt
RESTORERESOLVCONF=restore_resolvconf_openwrt
elif [ -x /sbin/resolvconf ]; then # Optional tool on Debian, Ubuntu, Gentoo
MODIFYRESOLVCONF=modify_resolvconf_manager
RESTORERESOLVCONF=restore_resolvconf_manager
elif [ -x /sbin/netconfig ]; then # tool on Suse after 11.1
MODIFYRESOLVCONF=modify_resolvconf_suse_netconfig
RESTORERESOLVCONF=restore_resolvconf_suse_netconfig
elif [ -x /sbin/modify_resolvconf ]; then # Mandatory tool on Suse earlier than 11.1
MODIFYRESOLVCONF=modify_resolvconf_suse
RESTORERESOLVCONF=restore_resolvconf_suse
else # Generic for any OS
MODIFYRESOLVCONF=modify_resolvconf_generic
RESTORERESOLVCONF=restore_resolvconf_generic
fi
# =========== script hooks =================================================
run_hooks() {
HOOK="$1"
if [ -d ${HOOKS_DIR}/${HOOK}.d ]; then
for script in ${HOOKS_DIR}/${HOOK}.d/* ; do
[ -f $script ] && . $script
done
fi
}
# =========== tunnel interface handling ====================================
do_ifconfig() {
if [ -n "$INTERNAL_IP4_MTU" ]; then
MTU=$INTERNAL_IP4_MTU
elif [ -n "$IPROUTE" ]; then
MTUDEV=`$IPROUTE route get "$VPNGATEWAY" | sed -ne 's/^.*dev \([a-z0-9]*\).*$/\1/p'`
MTU=`$IPROUTE link show "$MTUDEV" | sed -ne 's/^.*mtu \([[:digit:]]\+\).*$/\1/p'`
if [ -n "$MTU" ]; then
MTU=`expr $MTU - 88`
fi
fi
if [ -z "$MTU" ]; then
MTU=1412
fi
# Point to point interface require a netmask of 255.255.255.255 on some systems
if [ -n "$IPROUTE" ]; then
$IPROUTE link set dev "$TUNDEV" up mtu "$MTU"
$IPROUTE addr add "$INTERNAL_IP4_ADDRESS/255.255.255.255" peer "$INTERNAL_IP4_ADDRESS" dev "$TUNDEV"
else
ifconfig "$TUNDEV" ${ifconfig_syntax_inet} "$INTERNAL_IP4_ADDRESS" $ifconfig_syntax_ptp "$INTERNAL_IP4_ADDRESS" netmask 255.255.255.255 mtu ${MTU} up
fi
if [ -n "$INTERNAL_IP4_NETMASK" ]; then
set_network_route $INTERNAL_IP4_NETADDR $INTERNAL_IP4_NETMASK $INTERNAL_IP4_NETMASKLEN
fi
# If the netmask is provided, it contains the address _and_ netmask
if [ -n "$INTERNAL_IP6_ADDRESS" ] && [ -z "$INTERNAL_IP6_NETMASK" ]; then
INTERNAL_IP6_NETMASK="$INTERNAL_IP6_ADDRESS/128"
fi
if [ -n "$INTERNAL_IP6_NETMASK" ]; then
if [ -n "$IPROUTE" ]; then
$IPROUTE -6 addr add $INTERNAL_IP6_NETMASK dev $TUNDEV
else
# Unlike for Legacy IP, we don't specify the dest_address
# here on *BSD. OpenBSD for one will refuse to accept
# incoming packets to that address if we do.
# OpenVPN does the same (gives dest_address for Legacy IP
# but not for IPv6).
# Only Solaris needs it; hence $ifconfig_syntax_ptpv6
ifconfig "$TUNDEV" inet6 $INTERNAL_IP6_NETMASK $ifconfig_syntax_ptpv6 mtu $MTU up
fi
fi
}
destroy_tun_device() {
case "$OS" in
NetBSD|FreeBSD) # and probably others...
ifconfig "$TUNDEV" destroy
;;
esac
}
# =========== route handling ====================================
if [ -n "$IPROUTE" ]; then
fix_ip_get_output () {
sed -e 's/ /\n/g' | \
sed -ne '1p;/via/{N;p};/dev/{N;p};/src/{N;p};/mtu/{N;p}'
}
set_vpngateway_route() {
$IPROUTE route add `$IPROUTE route get "$VPNGATEWAY" | fix_ip_get_output`
$IPROUTE route flush cache
}
del_vpngateway_route() {
$IPROUTE route $route_syntax_del "$VPNGATEWAY"
$IPROUTE route flush cache
}
set_default_route() {
$IPROUTE route | grep '^default' | fix_ip_get_output > "$DEFAULT_ROUTE_FILE"
$IPROUTE route replace default dev "$TUNDEV"
$IPROUTE route flush cache
}
set_network_route() {
NETWORK="$1"
NETMASK="$2"
NETMASKLEN="$3"
$IPROUTE route replace "$NETWORK/$NETMASKLEN" dev "$TUNDEV"
$IPROUTE route flush cache
}
reset_default_route() {
if [ -s "$DEFAULT_ROUTE_FILE" ]; then
$IPROUTE route replace `cat "$DEFAULT_ROUTE_FILE"`
$IPROUTE route flush cache
rm -f -- "$DEFAULT_ROUTE_FILE"
fi
}
del_network_route() {
NETWORK="$1"
NETMASK="$2"
NETMASKLEN="$3"
$IPROUTE route $route_syntax_del "$NETWORK/$NETMASKLEN" dev "$TUNDEV"
$IPROUTE route flush cache
}
set_ipv6_default_route() {
# We don't save/restore IPv6 default route; just add a higher-priority one.
$IPROUTE -6 route add default dev "$TUNDEV" metric 1
$IPROUTE -6 route flush cache
}
set_ipv6_network_route() {
NETWORK="$1"
NETMASKLEN="$2"
$IPROUTE -6 route replace "$NETWORK/$NETMASKLEN" dev "$TUNDEV"
$IPROUTE route flush cache
}
reset_ipv6_default_route() {
$IPROUTE -6 route del default dev "$TUNDEV"
$IPROUTE route flush cache
}
del_ipv6_network_route() {
NETWORK="$1"
NETMASKLEN="$2"
$IPROUTE -6 route del "$NETWORK/$NETMASKLEN" dev "$TUNDEV"
$IPROUTE -6 route flush cache
}
else # use route command
get_default_gw() {
# isn't -n supposed to give --numeric output?
# apperently not...
# Get rid of lines containing IPv6 addresses (':')
netstat -r -n | awk '/:/ { next; } /^(default|0\.0\.0\.0)/ { print $2; }'
}
set_vpngateway_route() {
route add -host "$VPNGATEWAY" $route_syntax_gw "`get_default_gw`"
}
del_vpngateway_route() {
route $route_syntax_del -host "$VPNGATEWAY" $route_syntax_gw "`get_default_gw`"
}
set_default_route() {
DEFAULTGW="`get_default_gw`"
echo "$DEFAULTGW" > "$DEFAULT_ROUTE_FILE"
route $route_syntax_del default $route_syntax_gw "$DEFAULTGW"
route add default $route_syntax_gw "$INTERNAL_IP4_ADDRESS" $route_syntax_interface
}
set_network_route() {
NETWORK="$1"
NETMASK="$2"
NETMASKLEN="$3"
del_network_route "$NETWORK" "$NETMASK" "$NETMASKLEN"
route add -net "$NETWORK" $route_syntax_netmask "$NETMASK" $route_syntax_gw "$INTERNAL_IP4_ADDRESS" $route_syntax_interface
}
reset_default_route() {
if [ -s "$DEFAULT_ROUTE_FILE" ]; then
route $route_syntax_del default $route_syntax_gw "`get_default_gw`" $route_syntax_interface
route add default $route_syntax_gw `cat "$DEFAULT_ROUTE_FILE"`
rm -f -- "$DEFAULT_ROUTE_FILE"
fi
}
del_network_route() {
case "$OS" in
Linux|NetBSD|Darwin|SunOS) # and probably others...
# routes are deleted automatically on device shutdown
return
;;
esac
NETWORK="$1"
NETMASK="$2"
NETMASKLEN="$3"
route $route_syntax_del -net "$NETWORK" $route_syntax_netmask "$NETMASK" $route_syntax_gw "$INTERNAL_IP4_ADDRESS"
}
set_ipv6_default_route() {
route add -inet6 default "$INTERNAL_IP6_ADDRESS" $route_syntax_interface
}
set_ipv6_network_route() {
NETWORK="$1"
NETMASK="$2"
route add -inet6 -net "$NETWORK/$NETMASK" "$INTERNAL_IP6_ADDRESS" $route_syntax_interface
:
}
reset_ipv6_default_route() {
route $route_syntax_del -inet6 default "$INTERNAL_IP6_ADDRESS"
:
}
del_ipv6_network_route() {
NETWORK="$1"
NETMASK="$2"
route $route_syntax_del -inet6 "$NETWORK/$NETMASK" "$INTERNAL_IP6_ADDRESS"
:
}
fi
# =========== resolv.conf handling ====================================
# =========== resolv.conf handling for any OS =========================
modify_resolvconf_generic() {
grep '^##VPNC_GENERATED#' /etc/resolv.conf > /dev/null 2>&1 || cp -- /etc/resolv.conf "$RESOLV_CONF_BACKUP"
NEW_RESOLVCONF="##VPNC_GENERATED# -- this file is generated by vpnc
# and will be overwritten by vpnc
# as long as the above mark is intact"
# Remember the original value of CISCO_DEF_DOMAIN we need it later
CISCO_DEF_DOMAIN_ORIG="$CISCO_DEF_DOMAIN"
# Don't step on INTERNAL_IP4_DNS value, use a temporary variable
INTERNAL_IP4_DNS_TEMP="$INTERNAL_IP4_DNS"
exec 6< "$RESOLV_CONF_BACKUP"
while read LINE <&6 ; do
case "$LINE" in
nameserver*)
if [ -n "$INTERNAL_IP4_DNS_TEMP" ]; then
read ONE_NAMESERVER INTERNAL_IP4_DNS_TEMP <<-EOF
$INTERNAL_IP4_DNS_TEMP
EOF
LINE="nameserver $ONE_NAMESERVER"
else
LINE=""
fi
;;
search*)
if [ -n "$CISCO_DEF_DOMAIN" ]; then
LINE="$LINE $CISCO_DEF_DOMAIN"
CISCO_DEF_DOMAIN=""
fi
;;
domain*)
if [ -n "$CISCO_DEF_DOMAIN" ]; then
LINE="domain $CISCO_DEF_DOMAIN"
CISCO_DEF_DOMAIN=""
fi
;;
esac
NEW_RESOLVCONF="$NEW_RESOLVCONF
$LINE"
done
exec 6<&-
for i in $INTERNAL_IP4_DNS_TEMP ; do
NEW_RESOLVCONF="$NEW_RESOLVCONF
nameserver $i"
done
if [ -n "$CISCO_DEF_DOMAIN" ]; then
NEW_RESOLVCONF="$NEW_RESOLVCONF
search $CISCO_DEF_DOMAIN"
fi
echo "$NEW_RESOLVCONF" > /etc/resolv.conf
if [ "$OS" = "Darwin" ]; then
case "`uname -r`" in
# Skip for pre-10.4 systems
4.*|5.*|6.*|7.*)
;;
# 10.4 and later require use of scutil for DNS to work properly
*)
OVERRIDE_PRIMARY=""
if [ -n "$CISCO_SPLIT_INC" ]; then
if [ $CISCO_SPLIT_INC -lt 1 ]; then
# Must override for correct default route
# Cannot use multiple DNS matching in this case
OVERRIDE_PRIMARY='d.add OverridePrimary # 1'
fi
fi
# Uncomment the following if/fi pair to use multiple
# DNS matching when available. When multiple DNS matching
# is present, anything reading the /etc/resolv.conf file
# directly will probably not work as intended.
#if [ -z "$CISCO_DEF_DOMAIN_ORIG" ]; then
# Cannot use multiple DNS matching without a domain
OVERRIDE_PRIMARY='d.add OverridePrimary # 1'
#fi
scutil >/dev/null 2>&1 <<-EOF
open
d.init
d.add ServerAddresses * $INTERNAL_IP4_DNS
set State:/Network/Service/$TUNDEV/DNS
d.init
# next line overrides the default gateway and breaks split routing
# d.add Router $INTERNAL_IP4_ADDRESS
d.add Addresses * $INTERNAL_IP4_ADDRESS
d.add SubnetMasks * 255.255.255.255
d.add InterfaceName $TUNDEV
$OVERRIDE_PRIMARY
set State:/Network/Service/$TUNDEV/IPv4
close
EOF
if [ -n "$CISCO_DEF_DOMAIN_ORIG" ]; then
scutil >/dev/null 2>&1 <<-EOF
open
get State:/Network/Service/$TUNDEV/DNS
d.add DomainName $CISCO_DEF_DOMAIN_ORIG
d.add SearchDomains * $CISCO_DEF_DOMAIN_ORIG
d.add SupplementalMatchDomains * $CISCO_DEF_DOMAIN_ORIG
set State:/Network/Service/$TUNDEV/DNS
close
EOF
fi
;;
esac
fi
}
restore_resolvconf_generic() {
if [ ! -f "$RESOLV_CONF_BACKUP" ]; then
return
fi
grep '^##VPNC_GENERATED#' /etc/resolv.conf > /dev/null 2>&1 && cat "$RESOLV_CONF_BACKUP" > /etc/resolv.conf
rm -f -- "$RESOLV_CONF_BACKUP"
if [ "$OS" = "Darwin" ]; then
case "`uname -r`" in
# Skip for pre-10.4 systems
4.*|5.*|6.*|7.*)
;;
# 10.4 and later require use of scutil for DNS to work properly
*)
scutil >/dev/null 2>&1 <<-EOF
open
remove State:/Network/Service/$TUNDEV/IPv4
remove State:/Network/Service/$TUNDEV/DNS
close
EOF
;;
esac
fi
}
# === resolv.conf handling via /sbin/netconfig (Suse 11.1) =====================
# Suse provides a script that modifies resolv.conf. Use it because it will
# restart/reload all other services that care about it (e.g. lwresd). [unclear if this is still true, but probably --mlk]
modify_resolvconf_suse_netconfig()
{
/sbin/netconfig modify -s vpnc -i "$TUNDEV" <<-EOF
INTERFACE='$TUNDEV'
DNSSERVERS='$INTERNAL_IP4_DNS'
DNSDOMAIN='$CISCO_DEF_DOMAIN'
EOF
}
# Restore resolv.conf to old contents on Suse
restore_resolvconf_suse_netconfig()
{
/sbin/netconfig remove -s vpnc -i "$TUNDEV"
}
# === resolv.conf handling via /sbin/modify_resolvconf (Suse) =====================
# Suse provides a script that modifies resolv.conf. Use it because it will
# restart/reload all other services that care about it (e.g. lwresd).
modify_resolvconf_suse()
{
FULL_SCRIPTNAME=`readlink -f $0`
RESOLV_OPTS=''
test -n "$INTERNAL_IP4_DNS" && RESOLV_OPTS="-n \"$INTERNAL_IP4_DNS\""
test -n "$CISCO_DEF_DOMAIN" && RESOLV_OPTS="$RESOLV_OPTS -d $CISCO_DEF_DOMAIN"
test -n "$RESOLV_OPTS" && eval /sbin/modify_resolvconf modify -s vpnc -p $SCRIPTNAME -f $FULL_SCRIPTNAME -e $TUNDEV $RESOLV_OPTS -t \"This file was created by $SCRIPTNAME\"
}
# Restore resolv.conf to old contents on Suse
restore_resolvconf_suse()
{
FULL_SCRIPTNAME=`readlink -f $0`
/sbin/modify_resolvconf restore -s vpnc -p $SCRIPTNAME -f $FULL_SCRIPTNAME -e $TUNDEV
}
# === resolv.conf handling via UCI (OpenWRT) =========
modify_resolvconf_openwrt() {
add_dns $OPENWRT_INTERFACE $INTERNAL_IP4_DNS
}
restore_resolvconf_openwrt() {
remove_dns $OPENWRT_INTERFACE
}
# === resolv.conf handling via /sbin/resolvconf (Debian, Ubuntu, Gentoo)) =========
modify_resolvconf_manager() {
NEW_RESOLVCONF=""
for i in $INTERNAL_IP4_DNS; do
NEW_RESOLVCONF="$NEW_RESOLVCONF
nameserver $i"
done
if [ -n "$CISCO_DEF_DOMAIN" ]; then
NEW_RESOLVCONF="$NEW_RESOLVCONF
domain $CISCO_DEF_DOMAIN"
fi
echo "$NEW_RESOLVCONF" | /sbin/resolvconf -a $TUNDEV
}
restore_resolvconf_manager() {
/sbin/resolvconf -d $TUNDEV
}
# ========= Toplevel state handling =======================================
kernel_is_2_6_or_above() {
case `uname -r` in
1.*|2.[012345]*)
return 1
;;
*)
return 0
;;
esac
}
do_pre_init() {
if [ "$OS" = "Linux" ]; then
if (exec 6<> /dev/net/tun) > /dev/null 2>&1 ; then
:
else # can't open /dev/net/tun
test -e /proc/sys/kernel/modprobe && `cat /proc/sys/kernel/modprobe` tun 2>/dev/null
# fix for broken devfs in kernel 2.6.x
if [ "`readlink /dev/net/tun`" = misc/net/tun \
-a ! -e /dev/net/misc/net/tun -a -e /dev/misc/net/tun ] ; then
ln -sf /dev/misc/net/tun /dev/net/tun
fi
# make sure tun device exists
if [ ! -e /dev/net/tun ]; then
mkdir -p /dev/net
mknod -m 0640 /dev/net/tun c 10 200
[ -x /sbin/restorecon ] && /sbin/restorecon /dev/net/tun
fi
# workaround for a possible latency caused by udev, sleep max. 10s
if kernel_is_2_6_or_above ; then
for x in `seq 100` ; do
(exec 6<> /dev/net/tun) > /dev/null 2>&1 && break;
sleep 0.1
done
fi
fi
elif [ "$OS" = "FreeBSD" ]; then
if [ ! -e /dev/tun ]; then
kldload if_tun
fi
elif [ "$OS" = "GNU/kFreeBSD" ]; then
if [ ! -e /dev/tun ]; then
kldload if_tun
fi
elif [ "$OS" = "NetBSD" ]; then
:
elif [ "$OS" = "OpenBSD" ]; then
:
elif [ "$OS" = "SunOS" ]; then
:
elif [ "$OS" = "Darwin" ]; then
:
fi
}
do_connect() {
if [ -n "$CISCO_BANNER" ]; then
echo "Connect Banner:"
echo "$CISCO_BANNER" | while read LINE ; do echo "|" "$LINE" ; done
echo
fi
set_vpngateway_route
do_ifconfig
if [ -n "$CISCO_SPLIT_INC" ]; then
i=0
while [ $i -lt $CISCO_SPLIT_INC ] ; do
eval NETWORK="\${CISCO_SPLIT_INC_${i}_ADDR}"
eval NETMASK="\${CISCO_SPLIT_INC_${i}_MASK}"
eval NETMASKLEN="\${CISCO_SPLIT_INC_${i}_MASKLEN}"
if [ $NETWORK != "0.0.0.0" ]; then
set_network_route "$NETWORK" "$NETMASK" "$NETMASKLEN"
else
set_default_route
fi
i=`expr $i + 1`
done
for i in $INTERNAL_IP4_DNS ; do
echo "$i" | grep : >/dev/null || \
set_network_route "$i" "255.255.255.255" "32"
done
elif [ -n "$INTERNAL_IP4_ADDRESS" ]; then
set_default_route
fi
if [ -n "$CISCO_IPV6_SPLIT_INC" ]; then
i=0
while [ $i -lt $CISCO_IPV6_SPLIT_INC ] ; do
eval NETWORK="\${CISCO_IPV6_SPLIT_INC_${i}_ADDR}"
eval NETMASKLEN="\${CISCO_IPV6_SPLIT_INC_${i}_MASKLEN}"
if [ $NETMASKLEN -lt 128 ]; then
set_ipv6_network_route "$NETWORK" "$NETMASKLEN"
else
set_ipv6_default_route
fi
i=`expr $i + 1`
done
for i in $INTERNAL_IP4_DNS ; do
if echo "$i" | grep : >/dev/null; then
set_ipv6_network_route "$i" "128"
fi
done
elif [ -n "$INTERNAL_IP6_NETMASK" -o -n "$INTERNAL_IP6_ADDRESS" ]; then
set_ipv6_default_route
fi
if [ -n "$INTERNAL_IP4_DNS" ]; then
$MODIFYRESOLVCONF
fi
}
do_disconnect() {
if [ -n "$CISCO_SPLIT_INC" ]; then
i=0
while [ $i -lt $CISCO_SPLIT_INC ] ; do
eval NETWORK="\${CISCO_SPLIT_INC_${i}_ADDR}"
eval NETMASK="\${CISCO_SPLIT_INC_${i}_MASK}"
eval NETMASKLEN="\${CISCO_SPLIT_INC_${i}_MASKLEN}"
if [ $NETWORK != "0.0.0.0" ]; then
# FIXME: This doesn't restore previously overwritten
# routes.
del_network_route "$NETWORK" "$NETMASK" "$NETMASKLEN"
else
reset_default_route
fi
i=`expr $i + 1`
done
for i in $INTERNAL_IP4_DNS ; do
del_network_route "$i" "255.255.255.255" "32"
done
else
reset_default_route
fi
if [ -n "$CISCO_IPV6_SPLIT_INC" ]; then
i=0
while [ $i -lt $CISCO_IPV6_SPLIT_INC ] ; do
eval NETWORK="\${CISCO_IPV6_SPLIT_INC_${i}_ADDR}"
eval NETMASKLEN="\${CISCO_IPV6_SPLIT_INC_${i}_MASKLEN}"
if [ $NETMASKLEN -eq 0 ]; then
reset_ipv6_default_route
else
del_ipv6_network_route "$NETWORK" "$NETMASKLEN"
fi
i=`expr $i + 1`
done
for i in $INTERNAL_IP6_DNS ; do
del_ipv6_network_route "$i" "128"
done
elif [ -n "$INTERNAL_IP6_NETMASK" -o -n "$INTERNAL_IP6_ADDRESS" ]; then
reset_ipv6_default_route
fi
del_vpngateway_route
if [ -n "$INTERNAL_IP4_DNS" ]; then
$RESTORERESOLVCONF
fi
destroy_tun_device
}
#### Main
if [ -z "$reason" ]; then
echo "this script must be called from vpnc" 1>&2
exit 1
fi
case "$reason" in
pre-init)
run_hooks pre-init
do_pre_init
;;
connect)
run_hooks connect
do_connect
run_hooks post-connect
;;
disconnect)
run_hooks disconnect
do_disconnect
run_hooks post-disconnect
;;
reconnect)
run_hooks reconnect
;;
*)
echo "unknown reason '$reason'. Maybe vpnc-script is out of date" 1>&2
exit 1
;;
esac
exit 0
****************************************************************************************
The HereDoc Delimiter must be placed at the beginning of the a line:
#!/bin/bash
hello() {
cat <<-EOF
Hallo There
EOF
}
hello()
instead of:
#!/bin/bash
hello() {
cat <<-EOF
Hallo There
EOF
}
hello
which results in:
./test.sh: line 9: warning: here-document at line 4 delimited by end-of-file (wanted `EOF')
./test.sh: line 10: syntax error: unexpected end of file
Your heredocs (e.g. scutil >/dev/null 2>&1 <<-EOF) are unterminated. When you use <<- you can only indent the terminator with tabs.
From man bash (version 5.0.18)
This type of redirection instructs the shell to read input from the
current source until a line containing only delimiter (with no
trailing blanks) is seen.
...
If the redirection operator is <<-, then
all leading tab characters are stripped from input lines and the line
containing delimiter.
Combine those together, and << requires the terminator to be completely unprefixed, while <<- allows tabs to prefix the terminator.
I am trying to source an auto-completion script as a non-root user but receive a 'Bad Substitution' error message.
I am able to source it as root though.
On a other server I am able to source the script as non-root user.
I am guessing it is not a permission issue since I receive the same error trying to source a copy of the script with full permissions.
I have tried to echo all the environment variables used in the script, no issue there.
As the auto-completion script is packaged with the software I use I would rather not modify it.
Anyone would have a hint on what could be missing to the user so I can source the script from it ?
Thanks in advance for any idea!
Edit1:
ps output:
PID TTY TIME CMD
3261 pts/0 00:00:00 bash
73620 pts/0 00:00:00 ps
Error only as non-root user:
/opt/splunk/share/splunk/cli-command-completion.sh: 7: /opt/splunk/share/splunk/cli-command-completion.sh: Bad substitution
Script:
# Vainstein K 12aug2013
# # # Check a few prereqs.
feature='"splunk <verb> <object>" tab-completion'
[ `basename $SHELL` != 'bash' ] && echo "Sorry, $feature is only for bash" >&2 && return 11
[ ${BASH_VERSINFO[0]} -lt 4 ] && echo "Sorry, $feature only works with bash 4.0 or higher" >&2 && return 12
[ `type -t complete` != 'builtin' ] && echo "Sorry, $feature requires a bash that supports programmable command completion" >&2 && return 13
die () {
echo "(exit=$?) $#" >&2 && exit 42
}
ifSourced () { # do NOT exit(1) from this function!
local readonly tempfile=`pwd`/tmp--cli-completion--$$
rm -f $tempfile
$BASH ${BASH_ARGV[0]} --populateTempfile $tempfile
[ $? -eq 0 ] || return
[ -e $tempfile ] || return
. $tempfile
rm -f $tempfile
# # # Associate the completion function with the splunk binary.
local readonly completionFunction=fSplunkComplete
complete -r splunk 2>/dev/null
complete -F $completionFunction splunk
# You can view the completion function anytime via: $ type fSplunkComplete
}
ifInvoked () { # all error checking happens in this function
local readonly debug=false
local readonly tempfile=$1
$debug && echo "Told that tempfile=$tempfile"
# # # If anything goes wrong, at least we don't pollute cwd with our tempfile.
$debug || trap "rm -f $tempfile" SIGINT SIGQUIT SIGTERM SIGABRT SIGPIPE
touch $tempfile || die "Cannot touch tempfile=$tempfile"
# # # Decide where SPLUNK_HOME is.
if [ "$(dirname $(pwd))" == 'bin' ]; then
local readonly splunkHome=$(dirname $(dirname $(pwd)))
elif [ -n "$SPLUNK_HOME" ]; then
local readonly splunkHome=$SPLUNK_HOME
else
die 'Cannot figure out where SPLUNK_HOME is'
fi
$debug && echo "Decided SPLUNK_HOME=$splunkHome"
# # # Check that splunk (the binary) exists.
local readonly splunkBinary=$splunkHome/bin/splunk
[ -e $splunkBinary -a -x $splunkBinary ] || die "Cannot find expected binary=$splunkBinary"
# # # Find the file with object->{verb1,verb2,...} map.
local readonly splunkrcCmdsXml=$splunkHome/etc/system/static/splunkrc_cmds.xml
[ -e $splunkrcCmdsXml ] || die "Cannot find expected file $splunkrcCmdsXml"
$debug && echo "Shall read verb-obj info from: $splunkrcCmdsXml"
# # # Parse the map file, and generate our internal verb->{objA,objB,...} map.
local -A verb_to_objects
local line object verb objectsForThisVerb lineNumber=0
local inItem=false
local readonly regex_depr='\<depr\>'
local readonly regex_verb='\<verb\>'
local readonly regex_synonym='\<synonym\>'
while read line; do
lineNumber=$((lineNumber+1))
if $inItem; then
if [[ $line =~ '</item>' ]]; then
$debug && echo "Exited item tag at line=$lineNumber; this was obj=$object"
inItem=false
object=''
elif [[ $line =~ '<cmd name' && ! $line =~ $regex_depr && ! $line =~ $regex_synonym ]]; then
[ -z "$object" ] && die "BUG: No object within item tag. (At line $lineNumber of $splunkrcCmdsXml)"
verb=${line#*\"} # remove shortest match of .*" from the front
verb=${verb%%\"*} # remove longest match of ".* from the back
[ "$verb" == '_internal' ] && continue # Why the... eh, moving on.
objectsForThisVerb=${verb_to_objects[$verb]}
objectsForThisVerb="$objectsForThisVerb $object"
verb_to_objects[$verb]=$objectsForThisVerb
$debug && echo "Mapped object=$object to verb=$verb at line=$lineNumber; now objectsForThisVerb='$objectsForThisVerb'"
fi
else # ! inItem
if [[ $line =~ '<item obj' && ! $line =~ $regex_depr && ! $line =~ $regex_verb && ! $line =~ $regex_synonym ]]; then
inItem=true
object=${line#*\"} # remove shortest match of .*" from the front
object=${object%%\"*} # remove longest match of ".* from the back
$debug && echo "Entered item tag at line=$lineNumber, parsed object=$object"
[ "$object" == 'on' ] && inItem=false # Do not expose Amrit's puerile jest.
[ "$object" == 'help' ] && inItem=false # Although 'help' is a verb, splunkrc_cmds.xml constructs it as an object; ugh. We'll deal with the objects (topics) of 'splunk help' separately, below.
fi
fi
done < $splunkrcCmdsXml
$debug && echo "Processed $lineNumber lines. Map keys: ${!verb_to_objects[*]}, values: ${verb_to_objects[#]}"
# # # Oh wait, '<verb> deploy-server' aren't in splunkrc_cmds.xml; thanks, Jojy!!!!!
for verb in reload enable disable display; do
objectsForThisVerb=${verb_to_objects[$verb]}
objectsForThisVerb="$objectsForThisVerb deploy-server"
verb_to_objects[$verb]=$objectsForThisVerb
done
# # # Find the file with topics understood by 'splunk help <topic>' command, and extract list of topics.
local readonly literalsPy=$splunkHome/lib/python2.7/site-packages/splunk/clilib/literals.py
[ -e $literalsPy ] || die "Cannot find expected file $literalsPy"
$debug && echo "Shall read help topics list from: $literalsPy"
local readonly helpTopics=$(sed '/^addHelp/! d; s/^addHelp//; s/,.*$//; s/[^a-zA-Z_-]/ /g; s/^[ ]*//; s/[ ].*$//; /^$/ d' $literalsPy | sort | uniq)
$debug && echo "Parsed help topics list as: $helpTopics"
#######################################################
# # # Write the completion function to tempfile: BEGIN.
local readonly completionFunction=fSplunkComplete
echo -e 'function '$completionFunction' () {' >> $tempfile
echo -e '\tlocal wordCur=${COMP_WORDS[COMP_CWORD]}' >> $tempfile
echo -e '\tlocal wordPrev=${COMP_WORDS[COMP_CWORD-1]}' >> $tempfile
echo -e '\tcase $wordPrev in' >> $tempfile
# # # What can follow 'splunk' itself? Verbs used in main.c to key the 'cmd_handlers' array; and verbs from splunkrc_cmds.xml; and 'help'.
local readonly keys__cmd_handlers='ftr start startnoss stop restart restartss status rebuild train fsck clean-dispatch clean-srtemp validate verifyconfig anonymize find clean createssl juststopit migrate --version -version version httpport soapport spool ftw envvars _RAW_envvars _port_check cmd _rest_xml_dump search dispatch rtsearch livetail _normalizepath _internal logout btool pooling _web_bootstart offline clone-prep-clear-config diag'
local allVerbs="${!verb_to_objects[*]}"
echo -e '\t\tsplunk)\n\t\t\tCOMPREPLY=( $(compgen -W "'$keys__cmd_handlers $allVerbs' help" -- $wordCur) ) ;;' >> $tempfile
# # # What can follow 'splunk _internal'? see cmd_internal() of main.c
local readonly actions_internal='http mgmt https pre-flight-checks check-db call rpc rpc-auth soap-call soap-call-auth prefixcount totalcount check-xml-files first-time-run make-splunkweb-certs-and-var-run-merged'
echo -e '\t\t_internal)\n\t\t\tCOMPREPLY=( $(compgen -W "'$actions_internal'" -- $wordCur) ) ;;' >> $tempfile
# # # Options to 'splunk clean' are in CLI::clean() of src/main/Clean.cpp; to 'splunk fsck', in usageBanner of src/main/Fsck.cpp; to 'splunk migrate', in CLI::migrate() of src/main/Migration.cpp
echo -e '\t\tclean)\n\t\t\tCOMPREPLY=( $(compgen -W "all eventdata globaldata userdata inputdata locks deployment-artifacts raft" -- $wordCur) ) ;;' >> $tempfile
echo -e '\t\tfsck)\n\t\t\tCOMPREPLY=( $(compgen -W "scan repair clear-bloomfilter make-searchable" -- $wordCur) ) ;;' >> $tempfile
echo -e '\t\tmigrate)\n\t\t\tCOMPREPLY=( $(compgen -W "input-records to-modular-inputs rename-cluster-app" -- $wordCur) ) ;;' >> $tempfile
# # # List the help topics.
echo -e '\t\thelp)\n\t\t\tCOMPREPLY=( $(compgen -W "'$helpTopics'" -- $wordCur) ) ;;' >> $tempfile
# # # What can follow 'splunk cmd'? any executable in SPLUNK_HOME/bin/
echo -e '\t\tcmd)\n\t\t\tCOMPREPLY=( $(compgen -o default -o filenames -G "'$splunkHome'/bin/*" -- $wordCur) ) ;;' >> $tempfile
# # # Finally, let each verb be completed by its objects.
for verb in $allVerbs; do
echo -e '\t\t'$verb')\n\t\t\tCOMPREPLY=( $(compgen -W "'${verb_to_objects[$verb]}'" -- $wordCur) ) ;;' >> $tempfile
done
# # # And if we've run out of suggestions, revert to bash's default completion behavior: filename completion.
echo -e '\t\t*)\n\t\t\tCOMPREPLY=( $(compgen -f -- $wordCur) ) ;;' >> $tempfile
echo -e '\tesac' >> $tempfile
echo -e '}' >> $tempfile
$debug && cp $tempfile $tempfile~bak
# # # Write the completion function to tempfile: DONE.
######################################################
# # # Sanity check: source the tempfile, make sure that the function we wrote can be parsed and loaded by the shell.
unset $completionFunction
. $tempfile
[ "`type -t $completionFunction`" == 'function' ] || die 'BUG: generated completion function cannot be parsed by bash'
}
if [ $SHLVL -eq 1 ]; then
[ $# -ge 1 ] && echo "Ignoring supplied arguments: $#" >&2
ifSourced
elif [ $SHLVL -eq 2 ]; then
if [ $# -eq 2 ] && [ $1 == '--populateTempfile' ]; then
ifInvoked $2
else
echo -e "This script must be sourced, like so:\n\n\t\033[1m. $0\033[0m\n"
fi
else
: # user is running screen(1) or something of the sort.
fi
# # # Clean up.
unset die ifSourced ifInvoked
Edit2:
xtrace output
++ feature='"splunk <verb> <object>" tab-completion'
+++ basename /bin/bash
++ '[' bash '!=' bash ']'
++ '[' 4 -lt 4 ']'
+++ type -t complete
++ '[' builtin '!=' builtin ']'
++ '[' 1 -eq 1 ']'
++ '[' 0 -ge 1 ']'
++ ifSourced
+++ pwd
++ local readonly tempfile=/home/splunk/tmp--cli-completion--12431
++ rm -f /home/splunk/tmp--cli-completion--12431
++ /bin/sh cli-command-completion.sh --populateTempfile /home/splunk/tmp--cli-completion--12431
+ feature="splunk <verb> <object>" tab-completion
+ basename /bin/bash
+ [ bash != bash ]
cli-command-completion.sh: 8: cli-command-completion.sh: Bad substitution
++ '[' 2 -eq 0 ']'
++ return
++ unset die ifSourced ifInvoked
Edit3:
When using
set -o verbose
set -o noglob
set -o noglob
and checking differences between OK (root) and failing (non-root) run.
OK side:
[...]
+++ basename /bin/bash
++ '[' bash '!=' bash ']'
[ ${BASH_VERSINFO[0]} -lt 4 ] && echo "Sorry, $feature only works with bash 4.0 or higher" >&2 && return 12
++ '[' 4 -lt 4 ']'
[...]
++ local readonly tempfile=/home/splunk/tmp--cli-completion--42064
++ rm -f /home/splunk/tmp--cli-completion--42064
++ /bin/bash cli-command-completion.sh --populateTempfile /home/splunk/tmp--cli-completion--42064
+ set -o verbose
set -o noglob
+ set -o noglob
# Vainstein K 12aug2013
[...]
[ ${BASH_VERSINFO[0]} -lt 4 ] && echo "Sorry, $feature only works with bash 4.0 or higher" >&2 && return 12
+ '[' 4 -lt 4 ']'
[...]
Failing side:
[...]
+++ basename /bin/bash
++ '[' bash '!=' bash ']'
[ ${BASH_VERSINFO[0]} -lt 4 ] && echo "Sorry, $feature only works with bash 4.0 or higher" >&2 && return 12
++ '[' 4 -lt 4 ']'
[...]
++ local readonly tempfile=/home/splunk/tmp--cli-completion--40686
++ rm -f /home/splunk/tmp--cli-completion--40686
++ /bin/sh cli-command-completion.sh --populateTempfile /home/splunk/tmp--cli-completion--40686
+ set -o verbose
set -o noglob
+ set -o noglob
# Vainstein K 12aug2013
# # # Check a few prereqs.
feature='"splunk <verb> <object>" tab-completion'
+ feature="splunk <verb> <object>" tab-completion
[ `basename $SHELL` != 'bash' ] && echo "Sorry, $feature is only for bash" >&2 && return 11
+ basename /bin/bash
+ [ bash != bash ]
[ ${BASH_VERSINFO[0]} -lt 4 ] && echo "Sorry, $feature only works with bash 4.0 or higher" >&2 && return 12
cli-command-completion.sh: 10: cli-command-completion.sh: Bad substitution
++ '[' 2 -eq 0 ']'
++ return
# # # Clean up.
unset die ifSourced ifInvoked
++ unset die ifSourced ifInvoked
Seems like as non-root, it runs as /bin/sh whereas as 'bash' as root.
Weird because I tried multiple things to force bash there, maybe not the right ones.
It also fail at line 7 even though the first loop succeeds.
This should do the trick (line 7):
[ $(type -t complete) != 'builtin' ] && echo "Sorry, $feature requires a bash that supports programmable command completion" >&2 && return 13
Turns out from trace output that /bin/sh was used instead of /bin/bash to launch the script because /bin/bash was not set as default shell.
I have changed the default shell to /bin/bash and it is all ok now :)
I have used this method to set /bin/bash as default shell :
Check:
grep /etc/passwd
Change:
chsh --shell /bin/bash
Check modification:
grep /etc/passwd
Thanks for the help!
I might be blind, but I can't find the errors my script got, maybe you guys got better eyes than me :). I use a busybox compiled linux on a embedded system, Kernel 4.18.0. I found the base script here: Gist-Template
the following error is at "start":
./daemon: line 195: arithmetic syntax error
when I try "stop" these messages appear, but i dont see a unknown operand at line 0:
sh: 0: unknown operand
* Stopping Monitoring
my script:
#!/bin/sh
daemonName="Monitoring"
pidDir="."
pidFile="$pidDir/$daemonName.pid"
pidFile="$daemonName.pid"
logDir="."
# To use a dated log file.
# logFile="$logDir/$daemonName-"`date +"%Y-%m-%d"`".log"
# To use a regular log file.
logFile="$logDir/$daemonName.log"
# Log maxsize in KB
logMaxSize=1024 # 1mb
runInterval=300 # In seconds
doCommands() {
# This is where you put all the commands for the daemon.
echo "Running commands."
}
############################################################
# Below are the command functions
############################################################
hw_temp() {
cpu_temp=$(sensors|grep CPU|awk '{print $3}'|awk '{print ($0-int($0)<0.499)?int($0):int($0)+1}')
env_temp=$(sensors|grep ENV|awk '{print $3}'|awk '{print ($0-int($0)<0.499)?int($0):int($0)+1}')
pcb_temp=$(sensors|grep PCB|awk '{print $3}'|awk '{print ($0-int($0)<0.499)?int($0):int($0)+1}')
echo "$cpu_temp $env_temp $pcb_temp" >> /opt/monitoring/bla
}
############################################################
# Below is the skeleton functionality of the daemon.
############################################################
myPid=`echo $$`
setupDaemon() {
# Make sure that the directories work.
if [ ! -d "$pidDir" ]; then
mkdir "$pidDir"
fi
if [ ! -d "$logDir" ]; then
mkdir "$logDir"
fi
if [ ! -f "$logFile" ]; then
touch "$logFile"
else
# Check to see if we need to rotate the logs.
size=$((`ls -l "$logFile" | cut -d " " -f 8`/1024))
if [[ $size -gt $logMaxSize ]]; then
mv $logFile "$logFile.old"
touch "$logFile"
fi
fi
}
startDaemon() {
# Start the daemon.
setupDaemon # Make sure the directories are there.
if [[ `checkDaemon` = 1 ]]; then
echo " * \033[31;5;148mError\033[39m: $daemonName is already running."
exit 1
fi
echo " * Starting $daemonName with PID: $myPid."
echo "$myPid" > "$pidFile"
log '*** '`date +"%Y-%m-%d"`": Starting up $daemonName."
# Start the loop.
loop
}
stopDaemon() {
# Stop the daemon.
if [[ `checkDaemon` -eq 0 ]]; then
echo " * \033[31;5;148mError\033[39m: $daemonName is not running."
exit 1
fi
echo " * Stopping $daemonName"
log '*** '`date +"%Y-%m-%d"`": $daemonName stopped."
if [[ ! -z `cat $pidFile` ]]; then
kill -9 `cat "$pidFile"` &> /dev/null
fi
}
statusDaemon() {
# Query and return whether the daemon is running.
if [[ `checkDaemon` -eq 1 ]]; then
echo " * $daemonName is running."
else
echo " * $daemonName isn't running."
fi
exit 0
}
restartDaemon() {
# Restart the daemon.
if [[ `checkDaemon` = 0 ]]; then
# Can't restart it if it isn't running.
echo "$daemonName isn't running."
exit 1
fi
stopDaemon
startDaemon
}
checkDaemon() {
# Check to see if the daemon is running.
# This is a different function than statusDaemon
# so that we can use it other functions.
if [ -z "$oldPid" ]; then
return 0
elif [[ `ps aux | grep "$oldPid" | grep "$daemonName" | grep -v grep` > /dev/null ]]; then
if [ -f "$pidFile" ]; then
if [[ `cat "$pidFile"` = "$oldPid" ]]; then
# Daemon is running.
# echo 1
return 1
else
# Daemon isn't running.
return 0
fi
fi
elif [[ `ps aux | grep "$daemonName" | grep -v grep | grep -v "$myPid" | grep -v "0:00.00"` > /dev/null ]]; then
# Daemon is running but without the correct PID. Restart it.
log '*** '`date +"%Y-%m-%d"`": $daemonName running with invalid PID; restarting."
restartDaemon
return 1
else
# Daemon not running.
return 0
fi
return 1
}
loop() {
# This is the loop.
now=`date +%s`
if [ -z $last ]; then
last=`date +%s`
fi
# Do everything you need the daemon to do.
doCommands
# Check to see how long we actually need to sleep for. If we want this to run
# once a minute and it's taken more than a minute, then we should just run it
# anyway.
last=`date +%s`
# Set the sleep interval
if [[ ! $((now-last+runInterval+1)) -lt $((runInterval)) ]]; then
sleep $((now-last+runInterval))
fi
# Startover
loop
}
log() {
# Generic log function.
echo "$1" >> "$logFile"
}
###############################################################
# Parse the command.
###############################################################
if [ -f "$pidFile" ]; then
oldPid=`cat "$pidFile"`
fi
checkDaemon
case "$1" in
start)
startDaemon
;;
stop)
stopDaemon
;;
status)
statusDaemon
;;
restart)
restartDaemon
;;
*)
echo "Error: usage $0 { start | stop | restart | status }"
exit 1
esac
exit 0
This is my Server-Code for now.
I just want to get Data from a Client, analyze it and send my answer.
Is there a way to call my function managedata() in nc? My Code, obviously doesn't work.
server.sh:
managedata()
{
echo $1
#do something with data
return $1
}
listen()
{
echo "Server listening.."
nc -l -p 1234 -c '$(read i && managedata $i && echo $?)'
}
#MAIN
while true;
do
listen
done
Client.sh:
send()
{
echo $1 | nc $ip $port -o 0
}
#
register()
{
read -p "Login: " usrname
echo -n "Password: "
read -s password | shasum > password
#Schleife zum encrypten des Passworts
#Count = n -> Leslie Lamport Alogrithmus
n=5
count=$n
while [ $count -ge 2 ]
do
password="$(cat password | shasum)"
((count--))
done
password=`cat password`
echo
echo $password
data="reg-$usrname-$n-$password"
send $data
}
#
log()
{
echo "..."
}
#
menue()
{
echo "====== Lab: Shell Programming (BS) ======"
echo " r Register"
echo " l Login"
echo " q Quit"
echo
read -p "your choice: " check
case "$check" in
r) register;;
l) log;;
q) exit;;
esac
}
#MAIN
ip=$1
port=$2
while true
do
menue
done
bash -x server.sh:
+ true
+ listen
+ echo 'Server listening..'
Server listening..
+ nc -l -p 1234 -c '$(read i && managedata $i && echo $?)'
sh: 1: managedata: not found
+ true
+ listen
+ echo 'Server listening..'
Server listening..
+ nc -l -p 1234 -c '$(read i && managedata $i && echo $?)'
Yep you should "tell" bash to treat managedata as command or function that can be executed.
BTW, you need to use $() to execute whole expression not only managedata:
nc -l -p 1234 -c $(read i && managedata $i && echo $?)
Also bash can't return strings, only integer error codes, so return $1 won't work if it's not integer in range of 0 - 255.
Replace to return 0
According to the knoppix-halt file, it mention that
Please remove CD, close cdrom drive and hit return [2 minutes]
I look through the file so many times but still could not find the 2 minutes setting. I know that sleep X will sleep for X seconds while usleep X will sleep for microsecond. So, I went to look for sleep 120 and usleep 120000000 but did not find any.
So, can someone enlighten me why the message say 2 minutes but I could not find inside the script file?
#!/bin/busybox sh
# This script does:
# - Kill all processes
# - umount/sync filesystems (and freeing loopback files)
# - Eventually eject CD-Rom (autoeject turned on)
PATH=/sbin:/bin:/usr/bin:/usr/sbin:/usr/local/sbin:/usr/local/bin
export PATH
cd /
NORMAL="\033[0;39m"
RED="\033[1;31m"
GREEN="\033[1;32m"
YELLOW="\033[1;33m"
BLUE="\033[1;34m"
MAGENTA="\033[1;35m"
CYAN="\033[1;36m"
WHITE="\033[1;37m"
GRAY="\033[1;38m"
[ -r /etc/default/locale ] && . /etc/default/locale
[ -r /etc/sysconfig/i18n ] && . /etc/sysconfig/i18n
case "$LANG" in
de*)
EJECTMSG="Bitte CD entfernen, Laufwerk schließen und Eingabetaste drücken [2 Minuten]"
COMPLETEMSG="Shutdown beendet."
;;
*)
EJECTMSG="Please remove CD, close cdrom drive and hit return [2 minutes]."
COMPLETEMSG="Shutdown complete."
;;
esac
# Read in boot parameters
read CMDLINE </proc/cmdline 2>/dev/null
echo 0 >/proc/sys/kernel/printk
PROGRESSBAR="/tmp/knoppix-halt.progress"
progress(){
local black="\033[0;0m \033[0m"
local p
local count=0
echo -n -e "\033[1mSystem Shutdown... \033[42;32m \033[0m"
type usleep >/dev/null 2>&1 && sleep="usleep 100000" || sleep="sleep 1"
[ -r "$PROGRESSBAR" ] && rm -f "$PROGRESSBAR" 2>/dev/null
touch "$PROGRESSBAR"
while [ -r "$PROGRESSBAR" ]; do
if [ "$count" -ge 55 ]; then
for p in "/" "-" "\\" "|"; do
echo -n -e "\b${p}"
$sleep
[ -r "$PROGRESSBAR" ] || break
done
else
echo -n -e "\b$black\b"
$sleep
fi
let count++
done
echo -e "\r\033[J\033[1m${COMPLETEMSG}\033[0m"
}
# Return 0 if there is active swap, but
# enough memory available to call swapoff, 1 otherwise.
checkswap(){
local free=0 buffers=0 cache=0 swaptotal=0 swapfree=0 info amount kb
while read info amount kb; do
case "$info" in
MemFree:) free="$amount";;
Buffers:) buffers="$amount";;
Cached:) cached="$amount";;
SwapTotal:) swaptotal="$amount";;
SwapFree:) swapfree="$amount";;
esac
done </proc/meminfo
avail="$((free + buffers + cached))"
swapused="$((swaptotal - swapfree))"
if [ "$swaptotal" -gt 0 -a "$avail" -gt "$swapused" ] >/dev/null 2>&1; then
return 0
else
return 1
fi
}
OMIT=""
for i in $(pidof ntfs-3g aufs aufsd fuse fuseblk cloop0 cloop1 cloop2 cloop3 cloop4 cloop5 cloop6 cloop7 klogd syslogd); do OMIT="$OMIT -o $i"; done 2>/dev/null
killall5 -15 $OMIT; sleep 2
case "$CMDLINE" in *nosound*|*noaudio*|*nostartsound*) true ;; *)
# Play sound if soundcard is alive and soundfile present
# (also giving running programs some more time to terminate)
[ -r /usr/share/sounds/shutdown.ogg -a -f /proc/asound/pcm ] && \
type -p ogg123 >/dev/null 2>&1 && \
{ ogg123 -q --audio-buffers 4096 /usr/share/sounds/shutdown.ogg 2>/dev/null & sleep 2; }
;;
esac
# Clean console i/o
exec >/dev/console 2>&1 </dev/console
stty sane
echo -n -e "\r\033[K"
# echo -e "\033[H\033[J"
# Start progress bar
[ -n "$DEBUG" ] || progress &
# Check which device is mounted as /mnt-system
system="$(awk '/ \/mnt-system /{print $1;exit 0}' /proc/mounts 2>/dev/null)"
# noprompt or noeject option?
NOPROMPT="yes"; NOEJECT="yes"
case "$CMDLINE" in
*noprompt*) ;;
*) # Check if we need to wait for /mnt-system to be ejected.
if [ -n "$system" ]; then
for cdrom in $(awk '/drive name:/{print $NF}' /proc/sys/dev/cdrom*/info 2>/dev/null); do
[ "$system" = "/dev/$cdrom" ] && { NOEJECT=""; NOPROMPT=""; break; }
done
fi
;;
esac
case "$CMDLINE" in *noeject*) NOEJECT="yes" ;; esac
DEBUG=""
case "$CMDLINE" in *\ debug\ *|*BOOT_IMAGE=debug*) DEBUG="yes" ;; esac
# turn off swap, then unmount file systems.
# should free ramdisk space first, check
if checkswap; then
swapoff -a >/dev/null 2>&1
fi
# Shut down network, if no nfs mounted
# Actually... Not needed.
# grep -q ' nfs' /proc/mounts || ifdown -a >/dev/null 2>&1
# Kill remaining processes
killall5 -9 $OMIT
# Turn on autoeject of CD-Roms
if [ -z "$NOEJECT" ]; then
for dev in /proc/sys/dev/cdrom*/lock; do [ -f "$dev" ] && echo 0 > "$dev"; done
for dev in /proc/sys/dev/cdrom*/autoeject; do [ -f "$dev" ] && echo 1 > "$dev"; done
fi
# Try to sync for 30 seconds max.
sync &
SYNCPID="$!"
for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
sleep 2
[ -d /proc/"$SYNCPID" ] || break
done
# Free modules
# Do we need to unload modules at all?
#
#while read module relax; do
# case "$module" in
# *eeepc*|*_laptop*) true ;; # Unloading eeepc_laptop disables WLAN in the BIOS. Why?
# *) rmmod "$module" ;;
# esac
#done </proc/modules >/dev/null 2>&1
# Remove all automatically added entries from /etc/fstab
sed -i -e "/^# Added by KNOPPIX/{N;d}" /etc/fstab
# Force sync, then umount.
tac /proc/mounts | while read d m f relax; do
[ -d "$d" ] || continue
case "$f" in tmpfs|proc|sysfs|devpts|usbfs|aufs) ;; *)
case "$f" in rootfs|nfs*) ;; *) blockdev --flushbufs "$d" 2>/dev/null; umount -l "$m" 2>/dev/null ;; esac
case "$d" in /dev/mapper/*) /sbin/dmsetup --force remove "$d" 2>/dev/null ;; esac
;;
esac
done
# We have to use /bin/umount here, since busybox umount does not accept -t no*
# /bin/umount -t notmpfs,noproc,nosysfs,nousbfs,norootfs,noaufs,nonfs -adrf 2>/dev/null
# Free loopback devices which may have been used but not mounted.
for i in /dev/loop* /dev/loop/*; do [ -b "$i" ] && losetup -d "$i" 2>/dev/null; done
# End progress bar
[ -f "$PROGRESSBAR" ] && { rm -f "$PROGRESSBAR" 2>/dev/null; sleep 1; }
sleep 1
echo ""
# Mount boot medium read-only
umount -r /mnt-system 2>/dev/null
# And finally, umount
umount -l /mnt-system 2>/dev/null
# (Harddisk-installation only): mount / read-only
umount -r / 2>/dev/null
# Enable sysrq feature (just in case someone has turned it off)
# echo -n -e '\033[s\033[8m' # No output, save cursor position
echo 1 > /proc/sys/kernel/sysrq
echo s > /proc/sysrq-trigger 2>/dev/null & # emergency sync
sleep 1
echo u > /proc/sysrq-trigger 2>/dev/null & # emergency remount-ro
sleep 1
# echo -n -e '\033[28m\033[u' # re-enable output, restore cursor position
# pre-load poweroff+halt+eject if not included in this shell
poweroff --help >/dev/null 2>&1
reboot --help >/dev/null 2>&1
eject --help >/dev/null 2>&1
if [ -z "$NOEJECT" ]; then
( eject -s $system >/dev/null 2>&1 || eject $system >/dev/null 2>&1 & )
if [ -z "$NOPROMPT" ]; then
echo -n -e "${CYAN}${EJECTMSG}${NORMAL} "
read -t 120 a
fi
fi
case "$0" in
*halt|*poweroff) { poweroff -f 2>/dev/null & sleep 8; } || echo o > /proc/sysrq-trigger 2>/dev/null ;;
*) { reboot -f 2>/dev/null & sleep 8; } || echo b > /proc/sysrq-trigger 2>/dev/null ;;
esac
# Should never be reached.
sleep 2
echo -n -e "\033[1mYou can now turn off your computer.\033[0m"
halt -f
sleep 1337
At the bottom it says:
echo -n -e "${CYAN}${EJECTMSG}${NORMAL} "
read -t 120 a
This writes the message, and then waits up to 120 seconds for you to press return.