only use the slice's public IP if NAT is enabled
smbaker [Mon, 21 Jan 2013 23:27:14 +0000 (15:27 -0800)]
scripts/init.py

index 894f7c4..f680a3f 100755 (executable)
@@ -4,6 +4,7 @@ import sys
 import os
 import signal
 import socket
+import struct
 import fcntl
 import pdb
 import getpass
@@ -66,6 +67,13 @@ def fetch_output_nofail(inpath,outpath):
 
     return output
 
+def get_ip(ifname):
+    # http://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib
+    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+    return socket.inet_ntoa(fcntl.ioctl(
+        s.fileno(),\r
+        0x8915,  # SIOCGIFADDR\r
+        struct.pack('256s', ifname[:15]))[20:24])
 
 ### main()
 
@@ -117,10 +125,23 @@ try:
         print "Could not connect to Vsys. Giving up."
         exit(1)
 
+    print "successfully retrieved vsys output"
+
+    try:
+        eth0_ip = get_ip("eth0")
+    except:
+        print "Failed to get local ip"
+        eth0_ip = None
+
     # get the ip address of the host, we'll need it when setting up sshd
     hostname = socket.gethostname()
     hostipaddr = socket.gethostbyname(hostname)
-    print "found hostname", hostname, "and ip", hostipaddr
+
+    # See if we're behind a nat. If we are, then we want to use the public ip
+    # for ssh.
+    use_public_ip = (eth0_ip is not None) and eth0_ip.startswith("192.168")
+
+    print "hostname:", hostname, "public_ip:", hostipaddr, "eth0_ip:", eth0_ip
 
     wholestring = output.split("\n")
     seenSSHKey = False
@@ -161,7 +182,8 @@ try:
         h.close()
         os.system("sudo rm /etc/ssh/sshd_config")
         os.system("sudo cat /tmp/sshd_config /tmp/portFile > /tmp/newsshd_config")
-        os.system('sudo echo "ListenAddress ' + hostipaddr + '" >> /tmp/newsshd_config')
+        if use_public_ip:
+            os.system('sudo echo "ListenAddress ' + hostipaddr + '" >> /tmp/newsshd_config')
         os.system("sudo mv /tmp/newsshd_config /etc/ssh/sshd_config")
       elif line[0] == "vsys_sshKey.pub:":
         pathname = homedir + "/.ssh/id_rsa.pub"
@@ -190,7 +212,12 @@ try:
 
     # /etc/profile isn't working for noninteractive ssh sessions, so set the mpi
     # paths in .bashrc
-    open(homedir+"/.bashrc","w").write("export PATH=/usr/local/mpifix:$PATH:/usr/lib64/openmpi/bin\nexport LD_LIBRARY_PATH=/usr/lib64/openmpi/lib:$LD_LIBRARY_PATH\n")
+    if use_public_ip:
+        # If we're behind a NAT, then we need to play tricks with rewriting the IP
+        # addresses.
+        open(homedir+"/.bashrc","w").write("export PATH=/usr/local/mpifix:$PATH:/usr/lib64/openmpi/bin\nexport LD_LIBRARY_PATH=/usr/lib64/openmpi/lib:$LD_LIBRARY_PATH\n")
+    else:
+        open(homedir+"/.bashrc","w").write("export PATH=$PATH:/usr/lib64/openmpi/bin\nexport LD_LIBRARY_PATH=/usr/lib64/openmpi/lib:$LD_LIBRARY_PATH\n")
 
     os.system("chmod og-rw " + homedir + "/.ssh/id_rsa")
     os.system("chmod og-rw " + homedir + "/.ssh/id_rsa.pub")