In my working environment, I have two computers, one desktop machine and one laptop. Usually I run Windows on my laptop and Linux on my desktop. Our company use the Windows Domain to manage the computers, so when I login to the domain, the system will correlate the IP of the laptop to some DNS name; but for the Linux-running desktop, I cannot access it through DNS name. Every time I restart the desktop, it may change IP (due to the DHCP in the company), so I don’t know how to access it if I don’t check manually.

There’s one scenario that I want to use the desktop remotely: when I work at home, I use VPN to connect to the company’s intranet, then if i know the IP of my desktop machine, I can access via SSH.

Today I wrote a simple shell script on my machine. This script does one very simple work: it reads the IP of the local machine, writes this in some file, and then upload the file onto some ftp server.  Then I can get the IP address of my desktop via the ftp server. I set the script to run when the computer starts.

This is a very simple script contains about only 5~6 line of code, only two knowledge spots:

  1. Get the IP address of the current machine
    • the code is:
      ifconfig eth0 |grep ‘inet addr:’|cut –d: –f2 | awk ‘{print $1}’
      this line of code will return the IP address assigned to the eth0 interface.
    • Put the file onto some ftp server
      • in normal situation, ftp will read user name and password from the console input, but when using ftp in scripts, it cannot account on the user to input password manually, so we need to do it this way:

        ftp -n $HOST <<END_SCRIPT
        quote USER $USER
        quote PASS $PASSWD
        put $FILE
        quit
        END_SCRIPT
        exit 0



        There are two tricks here:




        1. Using the -n option on the ftp client program to prevent the ftp client from trying to log in immediately. That way, the ftp client does not ask for a user ID and password. No use of /dev/tty.


        2. Use the ftp client program command quote to send user ID and password to the ftp server.






    • Combining these two together, I have this script to do the work:





        #!/bin/sh
        HOST='10.32.105.126'
        USER='ftpuser'
        PASS='adv@nc3d'
        FILE='ip.txt'
        ifconfig eth0 |grep 'inet addr:'|cut -d: -f2|awk '{print $1}' >$FILE
        ftp -n $HOST <<END_SCRIPT
        quote USER $USER
        quote PASS $PASS
        cd Users/shid
        put $FILE
        bye
        END_SCRIPT
        rm -f $FILE
        exit 0