Read hostname from config file


53 posts   Page 1 of 3   1, 2, 3
by simplesi » Tue Oct 30, 2012 5:51 pm
I want to be able to setup and SD card and then clone it for a set of 6 for primary classroom use.
Because I'm VNCing into each one, I need to change the hostname on each image and I am thinking of just changing a value in say a config file e.g /boot/nameofrpi.txt
Code: Select all
rpi_name=porkpi04

so I can just simply edit this file from a card reader on a PC and then just stick into an RPi and be able to VNC into it based on the name.

At what point in the boot sequence (e.g which file) should I add code to to read in the value and write it to /etc/hostname before the RPi has read it in and used it?

regards
Simon
Seeking help with Scratch and I/O stuff for Primary age children
http://cymplecy.wordpress.com/ @cymplecy on twitter
Posts: 2041
Joined: Fri Feb 24, 2012 6:19 pm
Location: Euxton, Lancashire, UK
by Sander » Tue Oct 30, 2012 9:33 pm
User avatar
Posts: 174
Joined: Wed Aug 31, 2011 1:01 pm
by simplesi » Tue Oct 30, 2012 9:55 pm
Well - its going to save me some work :)
Ta :)

But its where to put the code in the "food chain" so its executed BEFORE the hostname is read or used by any networking services that I need to know

Simon
Seeking help with Scratch and I/O stuff for Primary age children
http://cymplecy.wordpress.com/ @cymplecy on twitter
Posts: 2041
Joined: Fri Feb 24, 2012 6:19 pm
Location: Euxton, Lancashire, UK
by Wendo » Thu Nov 01, 2012 7:22 am
You could edit /etc/init.d/hostname.sh and make that point to /boot/hostname rather than /etc/hostname.

No idea if it would in fact work, but I can't see why it woulnd't
Posts: 142
Joined: Sun Jun 10, 2012 8:27 pm
by Dweeber » Thu Nov 01, 2012 7:51 am
I do this all the time for anything that I need to be able to access when loading in a Winbox...

In this case.... (done as root, or add sudo in front of the commands)

Code: Select all
mv /etc/hostname /boot/hostname
mv /etc/hosts /boot/hosts

ln -s /boot/hostname /etc/hostname
ln -s /boot/hosts /etc/hosts


Now the active files are in the /boot directory which is accessible when mounted in a winbox... change to your hearts desire, though you will normally only do it once per unit.

I do the same with /etc/interfaces and /etc/wpa_supplicant/wpa_supplicant.conf

I work off of a master copy and simply make copies of that on to MicroSDHC cards and use SDcard adapters in all of my headless RPi units.

OR...

Just create a replacement hostname.sh init script that looks for a special file like /boot/newhost

If the file exists, it uses whatever name is in that file
Code: Select all
cat /boot/newhost
Hippo123

and changes the /etc/hosts and /etc/hostname files before bringing the service up.

I should remove the /boot/newhost file so that it only makes the change once.

Would be very easy to write.

To change the hostname, you could either SSH into the running RPi and add the /boot/newhost file and reboot... or mount the SDcard in a win box and create the file and put it back into the RPi to boot.
Dweeber A.K.A. Kevin...
My RPI Info Pages including Current Setup - http://rpi.tnet.com
User avatar
Posts: 606
Joined: Fri Aug 17, 2012 3:35 am
Location: Mesa, AZ
by simplesi » Thu Nov 01, 2012 9:44 am
@Dweeber - thanks for all the info :)

My ultimate aim is to use the RPi serial number and lookup a hostname so I'll probably try the replacement hostname.sh route.

I love the idea of linking the config files into /boot though as that couid certainly help when things go pear shaped and action needed at start of lesson :)

Simon
Seeking help with Scratch and I/O stuff for Primary age children
http://cymplecy.wordpress.com/ @cymplecy on twitter
Posts: 2041
Joined: Fri Feb 24, 2012 6:19 pm
Location: Euxton, Lancashire, UK
by jaromanda » Thu Nov 01, 2012 9:52 am
Dweeber wrote:To change the hostname, you could either SSH into the running RPi and add the /boot/newhost file and reboot... or mount the SDcard in a win box and create the file and put it back into the RPi to boot.

the idea of linking to /boot is a good one

the method to change this info is overcomplicated....if you're going to ssh into the pi, just edit the file (wherever it is) and reboot - why have the added complication of checking if a file exists at boot, doing swanky things with it, then continue on with booting
I now own 2 RPi - does that mean I own a circumference?
Posts: 93
Joined: Wed Sep 12, 2012 12:33 pm
by bredman » Thu Nov 01, 2012 10:08 am
There is a fundamental question which has been overlooked, do you want to set the hostname per RPi or per SD card?

If each student has their own personal RPi, the question is redundant. But in a situation where the RPi is bolted to the table and the student owns their personal SD card, there are two ways that you could set the hostnames...
1. By RPi, for example hostname is "desk7"
2. By SD card/student, for example hostname is "john_smith"

For option 1, the hostname needs to be rebuilt at every reboot and will be based on the serial number of the RPi because you cannot predict which SD card will be placed in which RPi.

For option 2, the hostname needs to be set once on each SD card and does not need to be changed at every reboot.
Posts: 1413
Joined: Tue Jan 17, 2012 2:38 pm
by daveg » Thu Nov 01, 2012 12:02 pm
Id be interested in finding out how to script a solution to option 1.
User avatar
Posts: 128
Joined: Thu Dec 01, 2011 9:36 am
by simplesi » Thu Nov 01, 2012 12:05 pm
Just to let everyone know what the working situation is/planned to be.

I have a set of 6 RPi that I'm going to be taking around 7 schools for after school/clubs ICT Lessons.

I want to be able to set up stuff on 1 card and then copy that image to the others.

The RPis have a wifi dongle and a battery PSU and I'll be VNCing into them using school laptops.

So if each RPi is marked with a name and I can allocate that name to the hostname from a lookup table of all my RPi serial numbers then I plan on being able to VNC in using the hostname.

regards

Simon
Seeking help with Scratch and I/O stuff for Primary age children
http://cymplecy.wordpress.com/ @cymplecy on twitter
Posts: 2041
Joined: Fri Feb 24, 2012 6:19 pm
Location: Euxton, Lancashire, UK
by simplesi » Thu Nov 01, 2012 12:14 pm
Having said all of this, it would still be nice to know if there is a place in the boot chain to simply add a bit of script in that will be run automatically by the boot process before hostname.sh is executed as its nice to be non-invasive when adding extras. :)

regards

Simon
Seeking help with Scratch and I/O stuff for Primary age children
http://cymplecy.wordpress.com/ @cymplecy on twitter
Posts: 2041
Joined: Fri Feb 24, 2012 6:19 pm
Location: Euxton, Lancashire, UK
by Dweeber » Thu Nov 01, 2012 12:35 pm
To the OP....

Just for giggles I thought I'd give this a shot...

First I tried to create a init.d script that would execute before hostname.sh did... Not as easy as I thought... it would require modifying other init.d scripts... and I didn't want to go that far....

So instead, I modified the original /etc/init.d/hostname.sh script by adding a new section in the do_start () section.

The section I added looks like:
Code: Select all
        if [ -f /boot/newhost ]
        then
          OLDHOST=`cat /etc/hostname`
          NEWHOST=`cat /boot/newhost`
          echo "Changing $OLDHOST to $NEWHOST..."
          echo $NEWHOST > /etc/hostname
          sed -i "s/127.0.1.1.*$OLDHOST/127.0.1.1\t$NEWHOST/g" /etc/hosts
          rm /boot/newhost
        fi

I did a couple tests and it worked great.

Source Code
Source of Changed /etc/init.d/hostname.sh
https://gist.github.com/3993105
I put it there rather than in this posting so that updates can be made if necessary... Can't change the posting here after it is posted (very annoying)...

Installing it...
MAKE A BACKUP OF THE ORIGINAL SCRIPT! I just copied the original to /boot/hostname.sh.original

Then just copy the entire contents of the source in the link above (use raw to display just the source) and replace the contents of the original hostname.sh script.

It should have the same permissions as before which would be
Code: Select all
sudo chmod 0755 /etc/init.d/hostname.sh

You should not need to do anything else as it is already setup by the system using the original filename

Then it is ready to rumble...

How it works
Create a /boot/newhost file with just the new hostname you want in it... for this test I made it look like:

/boot/newhost
Code: Select all
hippo123

Note that I just typed in the hippo123 and didn't even use a newline... just saved it.

Before rebooting... the contents of the two files it will modify were:

/etc/hostname
Code: Select all
raspi01


/etc/hosts
Code: Select all
127.0.0.1       localhost
::1             localhost ip6-localhost ip6-loopback
fe00::0         ip6-localnet
ff00::0         ip6-mcastprefix
ff02::1         ip6-allnodes
ff02::2         ip6-allrouters

127.0.1.1       raspi01


I then just rebooted the RPi... I was doing this headless..

When it came up the contents of the two files were:

/etc/hostname
Code: Select all
hippo123


/etc/hosts
Code: Select all
127.0.0.1       localhost
::1             localhost ip6-localhost ip6-loopback
fe00::0         ip6-localnet
ff00::0         ip6-mcastprefix
ff02::1         ip6-allnodes
ff02::2         ip6-allrouters

127.0.1.1       hippo123


And the system was using it.

The usual precautions should be taken.... act as if you will lose your disk... so you don't lose anything important if something goes terribly wrong, but this should be fine.
Dweeber A.K.A. Kevin...
My RPI Info Pages including Current Setup - http://rpi.tnet.com
User avatar
Posts: 606
Joined: Fri Aug 17, 2012 3:35 am
Location: Mesa, AZ
by SN » Thu Nov 01, 2012 12:51 pm
you need to write a script which overwrites /etc/hostname with what you need (e.g. by reading /proc/cpuinfo) and then you just need to drop that script into the /etc/rcS.d directory named S01something.sh where 'something' is alphabetically earlier than 'hostname' (because there is a script S01hostname.sh which is what actually sets the pi's hostname from /etc/hostname

Code: Select all
#! /bin/sh
### BEGIN INIT INFO
# Provides:          hostname
# Required-Start:
# Required-Stop:
# Should-Start:      glibc
# Default-Start:     S
# Default-Stop:
# Short-Description: Set hostname based on /etc/hostname
# Description:       Read the machines hostname from /etc/hostname, and
#                    update the kernel value with this value.  If
#                    /etc/hostname is empty, the current kernel value
#                    for hostname is used.  If the kernel value is
#                    empty, the value 'localhost' is used.
### END INIT INFO

PATH=/sbin:/bin

. /lib/init/vars.sh
. /lib/lsb/init-functions

do_start () {
        [ -f /etc/hostname ] && HOSTNAME="$(cat /etc/hostname)"

        # Keep current name if /etc/hostname is missing.
        [ -z "$HOSTNAME" ] && HOSTNAME="$(hostname)"

        # And set it to 'localhost' if no setting was found
        [ -z "$HOSTNAME" ] && HOSTNAME=localhost

        [ "$VERBOSE" != no ] && log_action_begin_msg "Setting hostname to '$HOST
NAME'"
        hostname "$HOSTNAME"
        ES=$?
        [ "$VERBOSE" != no ] && log_action_end_msg $ES
        exit $ES
}

do_status () {
        HOSTNAME=$(hostname)
        if [ "$HOSTNAME" ] ; then
                return 0
        else
                return 4
        fi
}

case "$1" in
  start|"")
        do_start
        ;;
  restart|reload|force-reload)
        echo "Error: argument '$1' not supported" >&2
        exit 3
        ;;
  stop)
        # No-op
        ;;
  status)
        do_status
        exit $?
        ;;
  *)
        echo "Usage: hostname.sh [start|stop]" >&2
        exit 3
        ;;
esac

:


What the previous poster missed is that /etc/init.d/hostname.sh is symlinked from /etc/rcS.d/S01hostname.sh and it is the symlinked one that is accessed and run because the odd naming convention (S01.....) allows the order of startup scripts to be determined
Steve N – binatone mk4->intellivision->zx81->spectrum->cbm64->cpc6128->520stfm->pc->raspi ?
User avatar
Posts: 1008
Joined: Mon Feb 13, 2012 8:06 pm
Location: Romiley, UK
by Dweeber » Thu Nov 01, 2012 12:58 pm
Actually I do get that part... the problem is that I am trying to conform to the use of update-rc.d which will complain if you just drop a script into place like that. ...

Debian is a bit different from what I am used to where the this automatic generations of scripts using update-rc.d didn't exist. You just created your own order if you needed to slip something in.

update-rc.d is the script that is managing the symbolic links to the various /etc/rc* directories and which orders to use based on the header sections of the varioud init.d scripts.
Dweeber A.K.A. Kevin...
My RPI Info Pages including Current Setup - http://rpi.tnet.com
User avatar
Posts: 606
Joined: Fri Aug 17, 2012 3:35 am
Location: Mesa, AZ
by SN » Thu Nov 01, 2012 1:17 pm
there should be no need to hack the standard hostname.sh - thats bad practise

looking at the manpage for update-rc.d suggest that you should drop the 'additional' script (e.g. alterhostname) into /etc/init.d and then use

update-rc.d alterhostname start 01 S

to get it the symlinks made
Steve N – binatone mk4->intellivision->zx81->spectrum->cbm64->cpc6128->520stfm->pc->raspi ?
User avatar
Posts: 1008
Joined: Mon Feb 13, 2012 8:06 pm
Location: Romiley, UK
by Dweeber » Thu Nov 01, 2012 8:01 pm
I will give that a shot when I get back home. I did give something similar to that a try and it was ignored. I agree... hacking the hostname.sh is not the best idea... I actually created another script that just makes the change...
Dweeber A.K.A. Kevin...
My RPI Info Pages including Current Setup - http://rpi.tnet.com
User avatar
Posts: 606
Joined: Fri Aug 17, 2012 3:35 am
Location: Mesa, AZ
by simplesi » Fri Nov 02, 2012 9:07 pm
Well, I think I've tried every possible instruction that google can find and

1. I can't get my script to run as part of the init.d sequence

2. I can't find any log of the init.d sequence to see if the RPi even attempts to run it

Last Script attempt was
Code: Select all
#! /bin/sh
### BEGIN INIT INFO
# Provides:          cy_hostname
# Required-Start:
# Required-Stop:
# X-Start-Before:    hostname
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Set hostname based on /boot/cy_hostname.txt
# Description:       Read the machines hostname from /boot/cy_hostname.txt, and
#                    updates /etc/hostname
### END INIT INFO

. /lib/lsb/init-functions

log_daemon_msg "Starting cy_hostname"

if [ -f /boot/cy_hostname.txt ]
        then
          OLDHOST=`cat /etc/hostname`
          NEWHOST=`cat /boot/cy_hostname.txt`
          echo "Changing $OLDHOST to $NEWHOST..."
          echo $NEWHOST > /etc/hostname
          sed -i "s/127.0.1.1.*/127.0.1.1\t$NEWHOST/g" /etc/hosts
          #rm /boot/newhost
          log_daemon_msg "cy_hostname complete"
        fi
exit 0


Simon
Seeking help with Scratch and I/O stuff for Primary age children
http://cymplecy.wordpress.com/ @cymplecy on twitter
Posts: 2041
Joined: Fri Feb 24, 2012 6:19 pm
Location: Euxton, Lancashire, UK
by simplesi » Fri Nov 02, 2012 10:01 pm
Ah - at last
http://wiki.debian.org/LSBInitScripts/DependencyBasedBoot

Seems all this update-rc.d is old hat !


so put this script
Code: Select all
#! /bin/sh
### BEGIN INIT INFO
# Provides:          cy_hostname
# Required-Start:
# Required-Stop:
# X-Start-Before     hostname
# Default-Start:     
# Default-Stop:     
# Short-Description: Set hostname based on /boot/cy_hostname.txt
# Description:       Read the machines hostname from /boot/cy_hostname.txt, and
#                    updates /etc/hostname
### END INIT INFO

. /lib/lsb/init-functions

log_daemon_msg "Starting cy_hostname"

if [ -f /boot/cy_hostname.txt ]
        then
          OLDHOST=`cat /etc/hostname`
          NEWHOST=`cat /boot/cy_hostname.txt`
          echo "Changing $OLDHOST to $NEWHOST..."
          echo $NEWHOST > /etc/hostname
          sed -i "s/127.0.1.1.*/127.0.1.1\t$NEWHOST/g" /etc/hosts
          #rm /boot/newhost
          log_daemon_msg "cy_hostname complete"
        fi
exit 0

/etc/init.d/cy_hostname.sh

did an
sudo insserv cy_hostname.sh and rebooted and my new hostname was copied into /etc/hostname and /etc/hosts :)

and Robert seems to be a close relation of your Mother :)

Simon
Now - just need code to do a lookup match of serial numbers to hostnames :)
Seeking help with Scratch and I/O stuff for Primary age children
http://cymplecy.wordpress.com/ @cymplecy on twitter
Posts: 2041
Joined: Fri Feb 24, 2012 6:19 pm
Location: Euxton, Lancashire, UK
by simplesi » Sat Nov 03, 2012 11:21 pm
:(

Didn't work second time I tried it :(

Simon
Seeking help with Scratch and I/O stuff for Primary age children
http://cymplecy.wordpress.com/ @cymplecy on twitter
Posts: 2041
Joined: Fri Feb 24, 2012 6:19 pm
Location: Euxton, Lancashire, UK
by SN » Sun Nov 04, 2012 12:08 am
in the spirit of do as I say not as I do :roll:

I already had a small script called whichpi which outputs R1, R2, R3 or R4 depending on what it found in /proc/cpuinfo

(and is used in this page http://sn.ickl.in/cgi-bin/about )

So I just hacked /etc/init.d/hostname.sh as follows so that /etc/hostname is overwritten as my pi's boot up...

...

do_start () {

# ADD THIS LINE IN HERE TO SET PI HOSTNAME BASED ON CPU ID TO R1/R2/R3/R4
/usr/bin/whichpi > /etc/hostname

[ -f /etc/hostname ] && HOSTNAME="$(cat /etc/hostname)"

...
Steve N – binatone mk4->intellivision->zx81->spectrum->cbm64->cpc6128->520stfm->pc->raspi ?
User avatar
Posts: 1008
Joined: Mon Feb 13, 2012 8:06 pm
Location: Romiley, UK
by chrisbr » Sun Nov 04, 2012 2:38 am
Can you get control over the DHCP server that gives out the IP addresses? I guess this is easier if you're planning on running a dedicated pi network rather than if you're trying to use existing network infrastructure, run by someone else. Please ignore the following if you can't...

If you can, you could assign the IP addresses based on the MAC address of each pi's wireless network card (as an alternative to the serial number). Couple this with DNS and you get all the functionality you're looking for without having to hack together scripts.

Something like dnsmasq, which is a dual DHCP and DNS server, would be perfect for this kind of setup. You could run it on a server pi.

Just a thought.

Chris
Posts: 6
Joined: Sat Nov 03, 2012 10:22 pm
by simplesi » Sun Nov 04, 2012 9:20 am
@SN
yep - I decided I'd spent too much on this and need a working solution for tomorrow so simply did
cat /boot/cy_config.txt > /etc/hostname
at start of hostname.sh and now I have a RPi with no name at all!!!! :(
(Somethings with computers you just can't win on! - I'm missing something fundemental here!!!)

@chrisbr
This is for Ages 9-10 to use in primaries so trying to make it come up with simple names like pi2,pi3 rather than using ip addresses with VNC.

I started this off a few days ago thinking it wouldn't be that hard to achieve but the Linux IT Gods have decided to have a bit of laugh with me! :(

Simon
Seeking help with Scratch and I/O stuff for Primary age children
http://cymplecy.wordpress.com/ @cymplecy on twitter
Posts: 2041
Joined: Fri Feb 24, 2012 6:19 pm
Location: Euxton, Lancashire, UK
by chrisbr » Sun Nov 04, 2012 12:34 pm
The names you assign e.g. pi1,pi2,pi3 must resolve to an IP address. If you can somehow always give an individual pi the same IP address you can control the names -- e.g. by adding entries to the /etc/hosts file on the SD card image or by using DNS. The trick is to assign the same IP address to a pi each time it boots.

How are you assigning the addresses? If it is being done through the school's wifi network (which will be doing the DHCP and DNS updates for you), then you probably don't have this level of control. If you're setting up your own wireless network (e.g. through a small home wireless router) there is probably an easy way to achieve what you're after.
Posts: 6
Joined: Sat Nov 03, 2012 10:22 pm
by simplesi » Sun Nov 04, 2012 3:49 pm
@chrisbr
Unfortunqtely - I AM the schools IT Network Manager :lol:

I explained what I'm after further up the thread
http://www.raspberrypi.org/phpBB3/posting.php?mode=reply&f=66&t=21623#pr206833

Basically I want to be able to take them into any of my schools and just simply VNC into them using a simple name without having to do any reservations in the DHCP server. :) (E.g 1xthis effort should have been << than DHCP reservations x7) :)

So my idea is - do the effort to get each PI to auto assign its name from a simple text file - the idea is easy - its just implementing it that's the problem.
I can get at the RPi serial number - I can look it up in a text file
Code: Select all
grep -Po '^Serial\s*:\s*\K[[:xdigit:]]{16}' /proc/cpuinfo | grep -f - /boot/cy_hostname.txt | awk -F"=" '{print $2}'


I just can't get it all working in a simple /etc/init.d script that autoruns before hostname.sh :(

Simon
Seeking help with Scratch and I/O stuff for Primary age children
http://cymplecy.wordpress.com/ @cymplecy on twitter
Posts: 2041
Joined: Fri Feb 24, 2012 6:19 pm
Location: Euxton, Lancashire, UK
by rurwin » Sun Nov 04, 2012 4:44 pm
In that case, I think you are going about it the wrong way. You can set the hostname and use SAMBA to propagate it to the network, but in my experience, just using Windows machines, that can take a long time after boot.

If the schools are using networks with class A non-routable addresses, 10.x.x.x, then there is an easier way. Reserve 16 bits of address space for the RaspPis, say 10.255.x.x, then give each Pi a static IP address either using a /boot config file or by making a 16-bit CRC of the serial number. Then provide a hosts file with all the 65536 pi addresses in and distribute that to all the machines that need to access them.
User avatar
Forum Moderator
Forum Moderator
Posts: 2903
Joined: Mon Jan 09, 2012 3:16 pm