Skip to content

Instantly share code, notes, and snippets.

@0mark
Last active December 21, 2015 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0mark/6270373 to your computer and use it in GitHub Desktop.
Save 0mark/6270373 to your computer and use it in GitHub Desktop.
simple network script (dhcp, iwconfig, wpa_supplicant, ppp, pin, auth by ssh)
#!/bin/bash
sudo /usr/bin/quicklan $1 $2
#!/usr/bin/perl
use warnings;
use strict;
my %items;
my @faces;
my @facesup;
my $device = '';
my $option;
my $debug = 0;
my $dhcp = 'dhcpcd';
sub FindFaces() {
my @f = split(/\s+/,`ls /sys/class/net`);
my $i = 0;
foreach (@f) {
$faces[$i++] = $_ if ($_ ne "lo");
}
$i = 0;
foreach (@faces) {
$facesup[$i++]=$_ if (!-B "/sys/class/net/$_/carrier" and `cat /sys/class/net/$_/carrier`=="1");
}
}
sub LoadConfig() {
my @CONF = split(/\n/,`cat /etc/qlan.conf`);
my %items;
my $state = 0;
# 0: wait for next block :: WORD {
# 1: read single line statements wait for multiline block until } :: WORD {
# WORD VALUE
# WORD
# 2: read multiline stuff until }
my $name;
my $name2;
foreach(@CONF) {
if($state==1) {
if(/}/) {
$state--;
$name = '';
} elsif(/^\s*([^\s]+)\s*{\s*$/) {
$state++;
$name2 = $1;
} else {
if(/^\s*([^\s]+)\s+(\S.*)$/) {
$items{$name}{$1} = $2;
}
if(/^\s*([^\s]+)\s*$/) {
$items{$name}{$1} = $1;
}
}
} elsif($state==2) {
if(/[^\\]}/) {
$state--;
$name2 = '';
} else {
$items{$name}{$name2} .= $_."\n";
}
}
if($state==0 && /^ *([^ ]+) *\{ *$/) {
$name = $1;
$state++;
}
}
return %items;
}
sub Help() {
print "qlan [net] action\n\n";
print "net: { ";
my @ks=keys(%items);
foreach (@ks) {
print $_." ";
}
print "}\n";
print "action: [ up (down) (info) (scan) (avail) ]\n\n";
print "see also: /etc/qlan.conf\n\n";
exit;
}
sub Message {
my $s = shift;
print "$s\n";
}
sub Debug {
if($debug==1) {
my $s = shift;
print "\n*****************\n$s";
}
}
sub doordie {
my $exec = shift;
my $step = shift;
my $substep = shift;
test($step, $substep) if($step);
$exec = "$exec 2>&1";
my $r = qx($exec);
if($? == -1) {
failtest("failed to execute: $!");
} elsif($? & 127) {
failtest("$! died with signal ".($? & 127).", ".($? & 128) ? 'with' : 'without'." coredump, message:\n$r");
} elsif($? >> 8) {
failtest("$! exits with code $?, message:\n$r");
}
ok() if($step);
}
sub test {
my $step = shift;
my $substep = shift;
print("[$step] $substep");
}
sub ok {
print(" DONE\n");
}
sub failtest {
my $msg = shift;
print " FAIL\n ** $msg\n";
exit 1;
}
sub fail {
my $msg = shift;
print " ** $msg\n";
exit 1;
}
sub up() {
my $act = `cat /var/run/quicklan` if (-T "/var/run/quicklan");
my $exec = '';
$act =~ s/\n//g if(defined $act);
if($act and $items{$act}{'face'} and $items{$act}{'face'} eq $items{$device}{'face'}) {
Message(" +++ $act is already up");
exit;
}
Message(" ** Up $items{$device}{'face'}");
my $x = $items{$device}{'face'};
`echo $device >> /var/run/quicklan`;
# Vorbedingungen
if(defined $items{$device}{'preexec'}) {
$exec = $items{$device}{'preexec'};
Message("preexec $exec");
$x = `$exec`;
Debug("[Preexec] '$exec' returns: $?\n$x");
}
# usb_modeswitch stuff
if(defined $items{$device}{'modeswitch_default'}) {
$x = 0;
if($items{$device}{'modeswitch_target'} ne "") {
$exec = "lsusb -d $items{$device}{'modeswitch_target'}";
Debug("PPP (USB MODESWITCH CHECK) '$exec' returns: $?\n$x");
$x = system($exec);
}
if($x!=0) {
my $dp = $items{$device}{'modeswitch_default'};
$dp =~ s/(.*)://g;
my $dv = $1;
my $tp = $items{$device}{'modeswitch_target'};
$tp =~ s/(.*)://g;
my $tv = $1;
$exec = "usb_modeswitch -v $dv -p $dp -V $tv -P $tp $items{$device}{'modeswitch_optional'}";
Message("[PPP] mode switch ($dv:$dp -> $tv:$tp)");
$x = `$exec`;
Debug("PPP (USB MODESWITCH) '$exec' returns\n$x");
if(not $x =~ /Device is gone/) {
Message("+++ mode switch failed (device is gone)");
exit;
}
sleep 3; # Wait a bit, maybe the tty's need some time to appear
} else {
Debug('PPP (USB MODESWITCH) Target allready exists, doing nothin!');
}
}
# PIN
if(defined $items{$device}{'pin'}) {
my $modem = "/dev/ttyUSB0";
Message("[PPP] setting PIN (on $modem)");
open(MODEM, "+<", $modem) or die("+++ Setting PIN failed (can't open modem $modem)");
print(MODEM "AT+CPIN=\"".$items{$device}{'pin'}."\"\n\r");
while (<MODEM>) {
if (m/OK/) {
close(MODEM);
}
if (m/ERROR/) {
close(MODEM);
Message("+++ Setting PIN failed (rejected)");
exit(1);
}
}
}
# WLAN "per Hand" starten
if(defined $items{$device}{'essid'}) {
$exec = "/usr/sbin/iwconfig $items{$device}{'face'} essid \"$items{$device}{'essid'}\"";
$exec .= " key s:$items{$device}{'key'}" if (defined $items{$device}{'key'});
$exec .= " key $items{$device}{'hkey'}" if (defined $items{$device}{'hkey'});
doordie($exec, "WIFI", "iwconfig");
}
# WLAN mit wpa_suplicant starten
if(defined $items{$device}{'module'}) {
my $wpaconff;
if($items{$device}{'psk'}) {
$items{$device}{'wpa'} = "psk=\"".$items{$device}{'psk'}."\"\nssid=\"".$items{$device}{'essid'}."\"\n";
}
if($items{$device}{'wpa'}) {
$wpaconff = "/tmp/qlan_wpa_supplicant_$$.conf";
open (FILE, ">$wpaconff") or die $!;
print FILE "ctrl_interface=/var/run/wpa_supplicant\nctrl_interface_group=0\nap_scan=1\nnetwork={\n".$items{$device}{'wpa'}."}\n";
close (FILE);
} elsif($items{$device}{'conf'}) {
$wpaconff = $items{$device}{'conf'};
} else {
fail("Incomplete WPA Configuration.");
}
doordie("/usr/sbin/wpa_supplicant -D$items{$device}{'module'} -i$items{$device}{'face'} -c$wpaconff -B", "WIFI", "wpa_supplicant");
system("rm $wpaconff");
test("WIFI", "wait for connection");
my $wpa = `wpa_cli status`;
my $c = 0;
while(not $wpa =~ /wpa_state=COMPLETED/ and $c<20) {
sleep 1;
$wpa = `wpa_cli status`;
$c++;
}
if($c>=20) {
failtest("FAIL\n ** timed out");
}
ok();
}
# PPP mit pon starten
if(defined $items{$device}{'ppp'}) {
$exec = "/usr/bin/pon $items{$device}{'ppp'}";
doordie($exec, "PPP")
my $c = 0;
my $ppp;
my $ok = 0;
while($ok !=1 and $c<80 ) {
$ppp = `ifconfig $items{$device}{'face'} 2>&1`;
sleep 4;
$ok=1 if (not ($ppp =~ /Device not found/ or `ifconfig $items{$device}{'face'} 2>&1` =~ /Device not found/));
$c++;
}
if($c>=80) {
faltest('timed out');
down();
exit;
}
}
# IP "per Hand" setzen
if(defined $items{$device}{'ip'}) {
$exec = "/sbin/ifconfig $items{$device}{'face'} $items{$device}{'ip'}";
Message("Setting IP '$items{$device}{'ip'}' on '$items{$device}{'face'}'");
$x = `$exec`;
Debug("ifconfig '$exec' returns\n$x", '/usr/share/icons/gnome/24x24/devices/gnome-dev-ethernet.png');
}
# DHCP
if(defined $items{$device}{'dhcp'}) {
$exec = "$dhcp $items{$device}{'face'}".(($items{$device}{'dhcp'} ne "dhcp")?" ".$items{$device}{'dhcp'}:"");
Message("Starting DHCP on '$items{$device}{'face'}'", '/usr/share/icons/gnome/24x24/devices/gnome-dev-ethernet.png');
Debug("DHCP $exec");
if(system($exec." &> /dev/null")) {
Message('+++ DHCP +++', '/usr/share/icons/gnome/24x24/status/gnome-netstatus-error.png');
down();
exit;
}
}
# SSH authenfication
if(defined $items{$device}{'auth'}) {
$exec = "shssh '$items{$device}{'auth'}'";
Message("SSH authentificate");
$x = `$exec`;
Debug("ssh authentificate '$exec' returns\n$x");
sleep (10);
}
# OpenVPN
if(defined $items{$device}{'openvpn'}) {
my $dev = `cat $items{$device}{'openvpn'} | grep dev | head -n 1 | sed "s/^.* //g"`;
my $devc = `ifconfig | egrep "${dev}[0-9]" | wc -l`;
my $exec = "/usr/sbin/openvpn --daemon --script-security 3 system --config $items{$device}{'openvpn'}";
print "openvpn: $exec\n";
Message("OpenVPN $dev on $devc ($items{$device}{'openvpn'})", '/usr/share/icons/gnome/24x24/devices/gnome-dev-ethernet.png');
if(system("$exec &> /dev/null")) {
Message('+++ OpenVPN +++', '/usr/share/icons/gnome/24x24/status/gnome-netstatus-error.png');
Debug("openvpn fails to '$exec'");
exit;
}
my $c = 0;
while(`ifconfig | egrep "${dev}[0-9]" | wc -l`==$devc and $c<120) {
sleep 1;
$c++;
}
if ($c>=120 or `ifconfig | egrep "${dev}[0-9]" | wc -l` < $devc) {
Message('+++ OpenVPN +++', '/usr/share/icons/gnome/24x24/status/gnome-netstatus-error.png');
Debug("openvpn '$exec' fails to create device");
down();
exit;
}
Debug("openvpn '$exec' win");
sleep 2;
}
# Nachbedingungen
if(defined $items{$device}{'postexec'}) {
$exec = "$items{$device}{'postexec'}";
Message("Executing Postconditions\n");
$x = `$exec`;
Debug("Preexec '$exec' returns: $?\n$x");
}
Message("done '".`ifconfig | egrep "(Link e)|(inet ad)" | sed -r "s/( +)|(inet )/ /g" | cut -d " " -f 1-3`."'", '/usr/share/icons/gnome/24x24/devices/gnome-dev-ethernet.png');
}
sub down() {
my $act;
if (-T "/var/run/quicklan") {
$act = `cat /var/run/quicklan`;
$act =~ s/\n//g if(defined $act);
} else {
Message("Nothing up...");
exit;
}
my $b = 0;
my $i = 0;
my $x = '';
my $exec = '';
foreach (@facesup) {
$b = 1 if ($_ eq $items{$act}{'face'});
$i++ if ($_ ne "lo" && $_ ne $items{$act}{'face'});
}
print " -- Warning: $act is down\n" if ($b==0);
print " -- Warning: there are Interfaces up ...\n" if ($i>0);
if($act eq "" && $device eq "") {
print " +++ Error: No Interface given and non found in /var/run/quicklan";
exit;
}
$device = $act if ($device eq "");
print " ** NotThatStupidDown(TM) $items{$device}{'face'}\n";
# Vorbedingungen
if(defined $items{$device}{'preexecdown'}) {
my $exec = $items{$device}{'preexecdown'};
print "preexec: $exec\n";
$x = `$exec`;
}
# openvpn auf die dreckige Art killen
if(defined $items{$device}{'openvpn'}) {
my $exec = "/usr/bin/killall -9 openvpn";
print "openvpn: $exec\n";
$x = `$exec`;
}
# wpa_suplicant auf die dreckige Art killen
if(defined $items{$device}{'module'}) {
my $exec = "/usr/bin/killall wpa_supplicant";
print "wpa_supplicant: $exec\n";
$x = `$exec`;
}
# ppp down
if(defined $items{$device}{'ppp'}) {
my $exec = "/usr/bin/poff $items{$device}{'ppp'}";
print "poff: $exec\n";
$x = `$exec`;
}
# auth killen
if(defined $items{$device}{'auth'}) {
my $exec = "killall -9 shssh";
print "auth: $exec\n";
$x = `$exec`;
}
# dhcp killen
if(defined $items{$device}{'dhcp'}) {
my $exec = "killall -9 $dhcp";
print "dhcp: $exec\n";
$x = `$exec`;
}
# Interface down
$exec = "/sbin/ifconfig $items{$device}{'face'} down";
print "ifconfig: $exec\n";
$x = `$exec`;
# Nachbedingungen
if(defined $items{$device}{'downpostexec'}) {
my $exec = "$items{$device}{'downpostexec'}";
print "postexec: ".$exec."\n";
$x = `$exec`;
}
`rm /var/run/quicklan`;
}
sub info() {
print " ** Info\n";
my $x='';
foreach (@facesup) {
print "$_ -------------\n";
if (/wlan/) {
my $exec="/sbin/iwconfig $_";
print "iwconfig: ".$exec."\n";
print $x=`$exec`;
print "\n\n";
}
my $exec="/sbin/ifconfig $_";
print "ifconfig: ".$exec."\n";
print $x=`$exec`;
print "\n\n";
}
}
sub scan() {
my $x='';
print " ** Scanning\n";
my $exec="iwlist scanning";
print "iwlist: ".$exec."\n";
print $x=`$exec`;
print "\n\n";
}
%items=LoadConfig();
my $action='';
# parse commandline
foreach(@ARGV) {
if($_=~/up|down|info|scan|avail/) {
$action=$_;
} elsif($items{$_} ne '') {
$device=$_;
} else {
$option=$_;
}
}
if ($action eq "up" || $action eq "") {
Help() if ($device eq "");
up();
} elsif ($action eq "down") {
FindFaces();
down();
} elsif ($action eq "info") {
$device=$device;
FindFaces();
info();
} elsif ($action eq "scan") {
scan();
} elsif ($action eq "avail") {
FindFaces();
my @keys = keys(%items);
my $akeys = "";
foreach(@keys) {
my $k=$_;
my $b=0;
if ($items{$k}{'ppp'} ne '') {
$b=1;
} else {
foreach(@faces) {
$b=1 if ($items{$k}{'face'} eq $_);
}
}
$akeys.=$k."\n" if ($b==1);
}
use IPC::Open2;
my $RDR;
my $WRTR;
my $pid=open2($RDR, $WRTR, "dmenu \$DMENUSETTINGS") || die "Mäh";
print $WRTR $akeys;
close($WRTR);
my @val = <$RDR>;
close($RDR);
exit if ($val[0] eq "");
$device=$val[0];
$action="up";
up();
}
exit;
#!/usr/bin/perl
use Expect;
use POSIX 'setsid';
daemonize();
my $timeout=10;
my $user=shift();
my $passwd=shift();
my $host=shift();
my $options=shift();
`logger -t shssh "firing up ssh $user@$host $options ..."`;
$ssh=Expect->spawn("/usr/bin/ssh", $user."@".$host,$options);
$r=$ssh->expect($timeout, 'assword');
if (!defined $r) {
`logger -t shssh "No Prompt ..."`;
die "No Prompt";
}
$ssh->send_slow(0, "$passwd\n");
`logger -t shssh "hopefully logged in, now just hanging around"`;
while(true) {sleep 10};
sub daemonize {
print "deamonizing...\n\n";
chdir '/' or die "Can't chdir to /: $!";
open STDIN, '/dev/null' or die "Can't read /dev/null: $!";
open STDOUT, '>/dev/null' or die "Can't write to /dev/null: $!";
defined(my $pid = fork) or die "Can't fork: $!";
exit if $pid;
setsid or die "Can't start a new session: $!";
open STDERR, '>&STDOUT' or die "Can't dup stdout: $!";
}
#$r = $ssh->expect($timeout, -re => 'Zum Beenden der Internetbenutzung');
#die "Not logged in" unless defined $r;
#print "Logged in\n";
#$r = $ssh->expect(-1, -re => 'Connection to 10.1.1.10 closed.');
#print "Connection closed oO\n";
#$ssh->send_slow(0, "$passwd\n");
# Unix-Prompt
#$r = $ssh->expect($timeout, '\$');
#die "No unix prompt (\$)" unless defined $r;
#$ssh->interact(); # In interaktiven # Modus schalten
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment