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.
Related
I could use some help figuring out why the elif in the following script is not working. The first part of the if works, and the else part of the statement works, but the elif does not. In other words, when I login as 'root' I get the DNS address I am expecting. And if I log in as Guest, I get the DNS address I was expecting, but not if I login as any of the students listed in the elif.
#!/bin/bash
\# Setting DNS by User
\# Get variables. $3 is logging in user.
user=$3
\# Root and Admin should be wide open
if [ $user = "root" ] || [ $user = "admin" ]; then
networksetup -setdnsservers Wi-Fi 8.8.8.8
networksetup -setdnsservers Ethernet 8.8.8.8
\# Older students get an open, but filtered experience:
elif
\# Adams class
[ $user = "Student01" ] ||
[ $user = "Student02" ] ||
[ $user = "Student03" ] ||
[ $user = "Student04" ] ||
\# Mariannes class:
[ $user = "Student05" ] ||
[ $user = "Student06" ] ||
[ $user = "Student07" ] ||
[ $user = "Student08" ]
then
networksetup -setdnsservers Wi-Fi 8.8.4.4
networksetup -setdnsservers Ethernet 8.8.4.4
\# Everyone else gets whitelisted DNS
else
networksetup -setdnsservers Wi-Fi 208.67.222.222
networksetup -setdnsservers Ethernet 208.67.222.222
fi
exit 0
My first thought is this is not really a maintainable approach. This is (in
my opinion) not the way to use the if / elif / if / fi structure.
That said, I have going to throw some advanced script at you that will do what
you want and is far more supportable.
First, I recommend keeping admin and student names in bash arrays. Eventually,
you can populate those arrays from another source (such as a file: shown in
comments). This will make the if / elif tests much simpler as shown.
#! /usr/bin/env bash
# Setting DNS by User
# Get variables. $3 is logging in user.
user=$3
# admin_list=$HOME/admin.list
# declare -a admins
# if [[ -f "$admin_list" ]] ; then
# IFS=$'\n' read -d '' -r -a admins < <(sed -e 's/#.*$//' "$admin_list")
#
# wait $! || return $?
# else
# echo "$admin_list not found: skipping"
# fi
declare -a admins=( root admin )
# special_list=$HOME/special.list
# declare -a special
# if [[ -f "$special_list" ]] ; then
# IFS=$'\n' read -d '' -r -a special < <(sed -e 's/#.*$//' "$special_list")
#
# wait $! || return $?
# else
# echo "$special_list not found: skipping"
# fi
declare -a special=(
# Adams class
"Student01"
"Student02"
"Student03"
"Student04"
# Mariannes class:
"Student05"
"Student06"
"Student07"
"Student08"
)
# Root and Admin should be wide open
if [[ " ${admins[#]} " =~ " $user " ]] ; then
echo Admin
# networksetup -setdnsservers Wi-Fi 8.8.8.8
# networksetup -setdnsservers Ethernet 8.8.8.8
elif [[ " ${special[#]} " =~ " $user " ]] ; then
# Older students get an open, but filtered experience:
# Adams class
echo Special
# networksetup -setdnsservers Wi-Fi 8.8.4.4
# networksetup -setdnsservers Ethernet 8.8.4.4
else
echo "Everyone else"
# Everyone else gets whitelisted DNS
# networksetup -setdnsservers Wi-Fi 208.67.222.222
# networksetup -setdnsservers Ethernet 208.67.222.222
fi
exit 0
Note: I commented out the nerworksetup from your script and added an echo
for each condition for testing. You can remove the echo lines and uncomment the
networksetup lines.
I tested it as:
$ script a1 a2 root
Admin
$ script a1 a2 Student02
Special
$ script a1 a2 Student1000
Everyone else
I hope this helps.
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
I am using akamai purge script from the Link and modified a little bit, so variables are in the file itself. This code successfully runs and purges object on win10, but when I run it on linux it does not purge, also it displays in console same text. I am not that fimiliar with shell scripts, any ideas what is wrong?
## Functions ------------------------------------------------------------------
function _get_property {
[ "$#" -lt 2 ] && return 1
local RC=$1
local PROP=$2
local value=$(cat ${RC} | sed "/^\s*#/d;s/\s*#[^\"']*$//" | grep ${PROP} | tail -n 1 | cut -d '=' -f2- )
if [ -z "${value}" ]; then
return 1
else
echo ${value}
return 0
fi
}
function get_properties {
local file="${1}"
declare -A aka_props
aka_props[client_secret]=$( _get_property "${file}" client_secret )
[ -z "${aka_props[client_secret]}" ] && { >&2 echo "ERROR: Please, set variable client_secret in file ${file}!!!"; exit 1; }
aka_props[client_token]=$( _get_property "${file}" client_token )
[ -z "${aka_props[client_token]}" ] && { >&2 echo "ERROR: Please, set variable client_token in file ${file}!!!"; exit 1; }
aka_props[access_token]=$( _get_property "${file}" access_token )
[ -z "${aka_props[access_token]}" ] && { >&2 echo "ERROR: Please, set variable access_token in file ${file}!!!"; exit 1; }
aka_props[host]=$( _get_property "${file}" host )
[ -z "${aka_props[host]}" ] && { >&2 echo "ERROR: Please, set variable host in file ${file}!!!"; exit 1; }
aka_props[network]=$( _get_property "${file}" network )
[ -z "${aka_props[network]}" ] && aka_props[network]="staging"
aka_props[action]=$( _get_property "${file}" action )
[ -z "${aka_props[action]}" ] && aka_props[network]="invalidate"
aka_props[type]=$( _get_property "${file}" type )
[ -z "${aka_props[type]}" ] && aka_props[network]="type"
declare -p aka_props | cut -d '=' -f2-
return 0
}
declare -A AKA_PROPS
AKA_PROPS[client_secret]=<client_secret>
AKA_PROPS[client_token]=<client_token>
AKA_PROPS[access_token]=<access_token>
AKA_PROPS[host]=<host>
AKA_PROPS[network]="production"
AKA_PROPS[action]="delete"
AKA_PROPS[type]="url"
function mk_nonce {
local s=$1
if [ -z ${s} ]; then s=$( date -u +'%Y%m%dT%H:%M:%S%z' ); fi
echo -n "${s}" | md5sum | cut -d ' ' -f1 | sed 's/.\{4\}/&-/g' | sed 's/.$//'
}
function base64_hmac_sha256 {
[ "$#" -lt 2 ] && return 1
local key=$1
local value=$2
echo -ne "${value}"| openssl sha256 -binary -hmac "${key}" | openssl base64
}
function base64_sha256 {
[ "$#" -lt 1 ] && return 1
local value=$1
echo -ne "${value}" | openssl dgst -binary -sha256 | openssl base64
}
function mk_auth_header {
[ "$#" -lt 3 ] && return 1
local -n aka_props=$1
local timestamp=$2
local nonce=$3
echo -n "EG1-HMAC-SHA256 client_token=${AKA_PROPS[client_token]};access_token=${AKA_PROPS[access_token]};timestamp=${timestamp};nonce=${nonce};"
#echo -n "EG1-HMAC-SHA256 client_token=${aka_props[client_token]};access_token=${aka_props[access_token]};timestamp=${timestamp};nonce=${nonce};"
}
function sign_data {
[ "$#" -lt 2 ] && return 1
local key=$1
local -n data_to_sign=$2
#local data="${data_to_sign[method]}\t${data_to_sign[scheme]}\t${data_to_sign[host]}\t${data_to_sign[request_uri]}\t${data_to_sign[canonical_headers]}\t${data_to_sign[hash_content]}\t${data_to_sign[auth_header]}"
local data="${data_to_sign[method]}\t${data_to_sign[scheme]}\t${data_to_sign[host]}\t${data_to_sign[request_uri]}\t\t${data_to_sign[hash_content]}\t${data_to_sign[auth_header]}"
base64_hmac_sha256 "${key}" "${data}"
}
function mk_body {
local type="${1}"
local objects="${2}"
local domain="${3}"
local arr_objects
local objs
IFS=',' read -r -a arr_objects <<< "${objects}"
for i in ${!arr_objects[#]}
do
local tmp=$( echo ${arr_objects[i]} | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's,/,\\/,g' )
if [ "${type}" == "cpcode" ]; then
objs="${objs},${tmp}"
else
objs="${objs},\"${tmp}\""
fi
done
objs=$( echo "${objs}" | sed 's/^,//' )
if [ "${type}" == "url" ]; then
echo "{\"hostname\":\"${domain}\",\"objects\":[${objs}]}"
else
echo "{\"objects\":[${objs}]}"
fi
}
## Options --------------------------------------------------------------------
P_NAME=${0##*\/}
#CONF=./.akarc
#[ ! -f ${CONF} ] && CONF=./.akarc
#[ ! -f ${CONF} ] && { >&2 echo "ERROR: configuration file not found (~/.akarc or /etc/.akarc)"; exit 1; }
#declare -A AKA_PROPS=$( get_properties "${CONF}" );
usage() {
cat << EOF
usage: ${P_NAME} [OPTIONS] -o <obj1[,obj2,obj3,...]>
Purge the Akamai cache via CCU REST API v3.
REMARKS
Please create a config file in ~/.akarc or /etc/.akarc
PARAMETERS:
-o | --objects List of objects to purge (with comma separated values)
OPTIONS:
-t | --type Type of objects
Possible values: url, cpcode or tag
Default: ${AKA_PROPS[type]}
-d | --domain Domain site (es. your.domain.com).
To use with type=url
-a | --action The desired action to manage the cache
Possible values: invalidate or delete
Default: ${AKA_PROPS[action]}
-n | --network The network on which you want to invalidate or delete content
Possible values: staging or production
Default: ${AKA_PROPS[network]}
-h | --help Show this message
-v | --version Show version
CONFIG FILE:
In the config file the following values have to been declared:
client_secret = <your client secret>
client_token = <your client token>
access_token = <your access token>
host = <your akamai host>
There is the possibility to set the default values:
network = <staging | production>
action = <invalidate | delete>
type = <url | cpcode | tag>
If no values are declared the default ones are:
network = staging
action = invalidate
type = url
EOF
}
ARGS=$( getopt -o "d:t:o:a:n:hv" -l "domain:,type:,objects:,action:,network:,help,version" -n "$0" -- "$#" )
eval set -- "$ARGS"
VERSION=0.2
NETWORK=${AKA_PROPS[network]}
ACTION=${AKA_PROPS[action]}
TYPE=${AKA_PROPS[type]}
while true; do
case "$1" in
-d | --domain )
DOMAIN=${2}
shift 2
;;
-t | --type )
TYPE=${2}
shift 2
;;
-o | --objects )
OBJECTS=${2}
shift 2
;;
-a | --action )
ACTION=${2}
shift 2
;;
-n | --network )
NETWORK=${2}
shift 2
;;
-h | --help )
usage
exit 0
;;
-v | --version )
echo $0 version: $VERSION
exit 0
;;
-- )
shift
break
;;
* )
>&2 echo "Internal error!"
exit 1
;;
esac
done
## Main -----------------------------------------------------------------------
[ -z "${TYPE}" ] || [ -z "${OBJECTS}" ] && { usage; exit 1; }
[ "${TYPE}" == "url" ] && [ -z "${DOMAIN}" ] && { usage; exit 1; }
[ "${TYPE}" != "url" ] && [ ! -z "${DOMAIN}" ] && { echo "WARNING: type is different of url then -d,--domain will be ignored ..."; }
[ "${TYPE}" != "url" ] && [ "${TYPE}" != "cpcode" ] && [ "${TYPE}" != "tag" ] && { >&2 echo "ERROR: Possible value of OBJECT TYPE is url, cpcode or tag"; exit 1; }
[ "${NETWORK}" != "staging" ] && [ "${NETWORK}" != "production" ] && { >&2 echo "ERROR: Possible value of NETWORK is staging or production"; exit 1; }
[ "${ACTION}" != "invalidate" ] && [ "${ACTION}" != "delete" ] && { >&2 echo "ERROR: Possible value of ACTION is invalidate or delete"; exit 1; }
BODY=$( mk_body "${TYPE}" "${OBJECTS}" "${DOMAIN}" )
[ $(echo -ne "${BODY}" | wc -c ) -gt 131072 ] && { >&2 echo "ERROR: The body size is greater than 131072!!!" exit 1; }
TIMESTAMP=$( date -u +'%Y%m%dT%H:%M:%S%z' )
NONCE=$( mk_nonce ${TIMESTAMP} )
SIGN_KEY=$( base64_hmac_sha256 ${AKA_PROPS[client_secret]} ${TIMESTAMP} )
AUTH_HEADER=$( mk_auth_header AKA_PROPS ${TIMESTAMP} ${NONCE} )
declare -A DATA_TO_SIGN=( [method]="POST"
[scheme]="https"
[host]="${AKA_PROPS[host]}"
[request_uri]="/ccu/v3/${ACTION}/${TYPE}/${NETWORK}"
[hash_content]=$( base64_sha256 "${BODY}" )
[auth_header]=$( mk_auth_header AKA_PROPS ${TIMESTAMP} ${NONCE}) )
SIGNED_DATA=$( sign_data "${SIGN_KEY}" DATA_TO_SIGN )
SIGNED_AUTH_HEADER="Authorization: ${AUTH_HEADER}signature=${SIGNED_DATA}"
H_JSON="Content-Type: application/json"
echo curl -s -H \"Expect:\" \
-H \"User-Agent:${P_NAME}\" \
-H \"Accept:${H_JSON}\" \
-H \"${H_JSON}\" \
-H \"${SIGNED_AUTH_HEADER}\" \
-X POST -d \'${BODY}\' \"${DATA_TO_SIGN[scheme]}://${DATA_TO_SIGN[host]}${DATA_TO_SIGN[request_uri]}\" | bash -x | jq .
exit 0
In
AKA_PROPS[client_secret]=<client_secret>
Hope you're replacing <client_secret> with its actual value as in Linux, the </> is meant for redirection. Apart from that, I would suggest below things.
Add a shebang(#!/bin/bash) to the top of the file
Then run dos2unix script_name
Finally run the script.
Associative arrays like ${AKA_PROPS[network]} are available for bash 4.0 or newer so first hing to do is to check bash version on your Linux against the version on Window$.
bash --version
GNU bash, version 4.3.42(1)-release (x86_64-suse-linux-gnu)
Another good thing to do is to add your changes after line 119 on the original script. Make sure values are properly quoted and that all values in .akarc file are present in your script.
#declare -A AKA_PROPS=$( get_properties "${CONF}" );
declare -A AKA_PROPS
AKA_PROPS[client_secret]=<client_secret>
AKA_PROPS[client_token]=<client_token>
AKA_PROPS[access_token]=<access_token>
AKA_PROPS[host]=<host>
AKA_PROPS[network]="production"
AKA_PROPS[action]="delete"
AKA_PROPS[type]="url"
You can test with -h option since AKA_PROPS values will be shown in the help text (e.g. Default: ${AKA_PROPS[type]}).
#!/bin/bash
# portcheck tool
usage()
{
echo -e "\n USAGE: ./${0##*/} [host|ip] \n"
exit
}
check_port()
{
local host=${1}
local port=${2}
if [ nc -w 5 -z host port ] && [ nc -w 5 -z host port ]
then
echo -e "\a\n => Port ${port} at ${host} is open"
else
echo -e "\a\n => Port ${port} at ${host} is closed"
fi
}
[[ $# -ne 2 ]] && usage
check_port ${1} ${2}
When I run the following command:
bash portOpenBash.sh 127.0.0.1 434
I get the following error:
portOpenBash.sh: line 14: [: too many arguments
I try to put quotes between the macro expression, but I get the same error.
Problem seems to be in your if conditions here:
if [ nc -w 5 -z host port ] && [ nc -w 5 -z host port ]
You probably want to check for non empty output of both commands like this:
if [ -n "$(nc -w 5 -z $host $port)" ] && [ -n "$(nc -w 5 -z $host $port)" ]
OR in BASH:
if [[ -n "$(nc -w 5 -z $host $port)" && -n "$(nc -w 5 -z $host $port)" ]]
EDIT:
OR else if you just want to check return codes then remove surrounding [ and ]:
if nc -w 5 -z $host $port && nc -w 5 -z $host $port
Need some extra eyes for this one...
dns_lookup() {
ip_set
if [ `ip_ping ${ip_address}` -eq 0 ]
then
host=""
dig +short -x ${ip_address} | sed 's/\.$//g' | while read host
do
if [ -z "${host}" ]
then
host="unknown"
fi
echo "${ip_address},${host}"
done
fi
}
I get desired results if ip is pingable and has a dns name. I do not get results if the ip is pingable but does not have a dns name.
ip_set() {
ip_address="${a}.${b}.${c}.${d}"
}
ip_ping() {
timeout ${delay} ping -q -c 1 -i 1 -W 1 -w 4 $1 > /dev/null 2>&1 ; echo $?
}
Perhaps this is what you need. Tell me if you need revisions.
dns_lookup() {
ip_set
if [ `ip_ping ${ip_address}` -eq 0 ]
then
host=""
dig +short -x ${ip_address} | sed 's/\.$//g' | {
hashosts=false
while read host
do
if [ -n "${host}" ]
then
hashosts=true
echo "${ip_address},${host}"
fi
done
[ "${hashosts}" = false ] && echo "${ip_address},unknown"
}
fi
}
I would have also suggested the change of function ip_ping but that_other_guy already did it.
You don't get a result when there's no hostname because your while read loop never runs when there are no lines to read. You should make your printing code run regardless:
host=$(dig +short -x "${ip_address}" | sed 's/\.$//g')
if [ -z "${host}" ]
then
host="unknown"
fi
printf "${ip_address},%s\n" $host
Also, you're going about your condition wrong. You shouldn't echo the exit status and compare it as text. You should just let your command's exit status be your function's exit status:
ip_ping() {
timeout ${delay} ping -q -c 1 -i 1 -W 1 -w 4 $1 > /dev/null 2>&1
# functions implicitly 'return $?' if you don't specify anything else
}
Now you can easily check your function:
if ip_ping "$ip_address"
then
echo "It worked"
else
echo "It failed.."
fi