script

Mininet: Set Interface MTU

1
2
3
4
5
6
import subprocess
MTU = 9000
net = Mininet( ... )
for intf in [intf for sw in net.switches for intf in sw.intfNames()]:
subprocess.call(['ifconfig', intf, 'mtu', str(MTU)])

Wait for a Local TCP Port with Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/usr/bin/env python
import time
def waitForTcpPort(port, timeout=20, poll=0.1):
start = time.time()
with open('/proc/net/tcp','r') as f4, open(
'/proc/net/tcp6', 'r') as f6:
while True:
f4.seek(0)
f6.seek(0)
lines = f4.readlines()[1:] + f6.readlines()[1:]
sockets = map(str.split, lines)
listeners = [l for l in sockets if l[3] == '0A']
ports = [int(l[1].split(':')[1], 16) for l in listeners]
if port in ports:
break
time.sleep(poll)
if time.time() - start > timeout:
raise Exception("Timed out waiting (>%gs) for TCP port %d"
% (timeout, port))
if __name__ == '__main__':
import argparse
p = argparse.ArgumentParser()
p.add_argument('port', help='port to wait for', type=int)
args = p.parse_args()
waitForTcpPort(args.port)

Calculate the Size of SQL Tables Using SQLite

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash
TMP_DB=$(mktemp)
cat $1 | sqlite3 $TMP_DB
for t in $(sqlite3 $TMP_DB .tables)
do
#echo -e "\n$t"; sqlite3 $TMP_DB "PRAGMA table_info($t)"
echo -n "$t: "
sqlite3 $TMP_DB "PRAGMA table_info($t)" | cut -d'|' -f3 |tr '[:lower:]' '[:upper:]' | \
sed -e 's/^DEC\(IMAL\)\?.*$/8/' -e 's/.*(\(.\+\)).*/\1/' \
-e 's/^TEXT$/1/' \
-e 's/^TIMESTAMP$/8/' -e 's/^DATETIME$/8/' \
-e 's/^INT\(INTEGER\)\?$/4/' -e 's/^.*BIGINT$/8/' -e 's/^FLOAT$/8/' \
-e 's/^TINYINT$/1/' -e 's/^SMALLINT$/2/' | \
paste -s -d+ | bc
done
rm -f $TMP_DB

Automating FTP with a Non-Interactive FTP Client

Sometimes FTP has to be used to transfer files instead of one of the more secure alternatives, like SCP. Since the FTP client ftp only supports interactive mode, it can be hard to automate when being called from a script.

The script below is used — almost — the same way as a the scp command is. Its first arguments are files to be copied, and the final argument is the FTP address to send them to, similar to the URI used with scp.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/bin/bash
if [ $# -lt 2 ]; then
echo Usage: $(basename $0) SOURCE... USERNAME:PASSWORD@HOST:DEST_DIR
exit 1
fi
from=${@: 1:$(($#-1))}
dest=${@: -1:1}
read user password host path <<< $(echo $dest | sed -n 's/^\([^:]*\)\(:\(.*\)\)\?@\([^:]*\)\(:\(.*\)\)\?$/\1 \3 \4 \6/p')
[ "$path" == "" ] && path=.
[ "$user" == "" ] && user=anonymous && password=none
put_commands=""
for f in $from; do
[ ! -f $f ] && echo File does not exist: $f && exit 1
put_commands=$put_commands$'\nput '$f' '$(basename $f)
done
ftp -inv <<EOF
open $host
user $user $password
binary
cd $path
$put_commands
bye
<<EOF