0

I'm looking at if I can have a bash/python script that triggers a command based on the IP address Linux has received via DHCP.

e.g.

  • DHCP received: 10.50.10.51 /24 runs command XYZ
  • DHCP received: 10.50.20.84 /24 run command XYZ02

Is this possible to do and what would the command be. I'm thinking it prob basic with a variable on reading IP address, but not sure.

Thanks

1

It depends on your DHCP client.

For example, dhclient has the option -sf:

-sf script-file
Path to the network configuration script invoked by dhclient when it gets a lease.

Many other DHCP clients also have options to call scripts. There you can examine the address and do what you want.

  • my DHCP client is a raspberry Pi running Debian. – Roa872 Jul 20 at 16:09
  • @Roa872: No it's not. Raspberry pi is hardware and Debian is a linux distribution. Neither are DHCP clients. – Jesse_b Jul 20 at 16:28
0
#!/usr/bin/env perl 

$result = `dhclient -v 2>&1 | grep bound | cut -d' ' -f3`;
chomp($result);

if ($result eq '10.50.10.51') {
    `echo doing XYZ`;
}   
elsif ($result eq '10.50.20.84') {
    `echo doing XYZ02`;
}   
else {
    print "[$result]\n";
}   

You must run the script with sudo because dhclient requires elevated permission

sudo perl script.pl

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.