Determining default gateway with Tcl - network-programming

I have a Tcl/Tk script, and I need to find the default gateway of the computer it's running on to establish a connection to the router. Is there any way (preferably cross-platform) to find out what the computer's default gateway is set to?
I imagine that for Linux (Ubuntu, specifically -- the platform I'm targeting) I could call the "route" command and parse that, but I'm not sure that would work on Windows, and I'd like to avoid making system calls if possible, on principle.

The way to get information about the network routing is to ask the OS. This is also an operation that isn't very cross-platform. On Windows, the simplest way to do this is to parse the output of ipconfig /all.
set output [exec {*}[auto_execok ipconfig] /all]
if {[regexp -line {Default Gateway[ .]*: (.+)} $output -> gw]} {
puts "The default gateway is $gw"
} else {
puts "No default gateway found"
}
On Linux, you need to do this:
# Note, might not be on your PATH by default
set output [exec /sbin/route -n]
if {[regexp -line {^0\.0\.0\.0\s+([0-9.]+)} $output -> gw]} {
puts "The default gateway is $gw"
} else {
puts "No default gateway found"
}
On OSX (and other BSD derivatives), you need a different incantation:
set output [exec /sbin/route -n get 0.0.0.0]
if {[regexp -line {gateway: ([0-9.]+)} $output -> gw]} {
puts "The default gateway is $gw"
} else {
puts "No default gateway found"
}
As you can see, this is frustratingly difficult! Let's wrap it up in a procedure that uses tcl_platform to decide what to do.
proc gateway {varName} {
upvar 1 $varName gw
global tcl_platform
if {$tcl_platform(platform) eq "windows"} {
set output [exec {*}[auto_execok ipconfig] /all]
set RE {Default Gateway[ .]*: (.+)}
} elseif {$tcl_platform(os) eq "Linux"} {
set output [exec /sbin/route -n]
set RE {^0\.0\.0\.0\s+([0-9.]+)}
} else {
# Assume we're OSX or BSD
set output [exec /sbin/route -n get 0.0.0.0]
set RE {gateway: ([0-9.]+)}
}
return [regexp -line $RE $output -> gw]
}
Now you'll be able to do this on all platforms:
if {[gateway gw]} {
puts "The default gateway is $gw"
} else {
puts "No default gateway found"
}
The underlying code isn't portable, but your code can be. Easy!

Related

How evaluate external command to a Nix value?

I want to parse a file to a Nix list value inside flake.nix.
I have a shell script which does that
perl -007 -nE 'say for m{[(]use-package \s* ([a-z-0-9]+) \s* (?!:nodep)}xsgm' init.el
How can I execute external command while evaluating flake.nix?
programs.emacs = {
enable = true;
extraConfig = builtins.readFile ./init.el;
extraPackages = elpa: (shellCommandToParseFile ./init.el); # Runs shell script
};
You can run ./init.el by the same way you perform any other impure step in Nix: With a derivation.
This might look something vaguely like:
programs.emacs = {
enable = true;
extraConfig = ../init.el;
extraPackages = elpa:
let
packageListNix =
pkgs.runCommand "init-packages.nix" { input = ../init.el; } ''
${pkgs.perl}/bin/perl -007 -nE '
BEGIN {
say "{elpa, ...}: with elpa; [";
say "use-package";
};
END { say "]" };
while (m{[(]use-package \s* ([a-z-0-9]+) \s* (;\S+)?}xsgm) {
next if $2 eq ";builtin";
say $1;
}' "$input" >"$out"
'';
in (import "${packageListNix}" { inherit elpa; });
};
...assuming that, given the contents of your ./init.el, the contents of your resulting el-pkgs.nix is actually valid nix source code.
That said, note that like any other derivation (that isn't either fixed-output or explicitly impure), this happens inside a sandbox with no network access. If the goal of init.el is to connect to a network resource, you should be committing its output to your repository. A major design goal of flakes is to remove impurities; they're not suitable for impure derivations.

nomad multiline environment variable

Is there a way to have a multiline environment variable in a nomad template? Trying it directly gives an error about not being able to find the closing quote.
In the docs the only function that's mentioned is | toJSON, but that translates the line feeds into \n so the receiving end needs to do a search-and-replace or some "unJSON" function.
I tried using HEREDOC syntax in the template, but that didn't seem to work either.
Using a here document works fine:
job "example" {
datacenters = ["dc1"]
type = "service"
group "cache" {
task "redis" {
driver = "docker"
config {
image = "redis:7"
}
env {
EXAMPLE = <<EOF
multiline
varibale
is
here
EOF
}
}
}
}

Send email everytime php generates a fatal error

How would I write a PHP code that would send me an email everytime I get a
Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 14373306 bytes) in on line <b>443</b><br />.
I'm running a script wherein a user has this URL and it will be process by my code, but the problem here is that sometimes it results to a Fatal error Allowed memory size exhausted. I want an email to be sent to me that tells me that there has this error at the same time what URL is causing that error.
So the logic is something like this.
if( error == "Fatal Error Allowed memory Size" ) {
mail("myemail#email.com", "Fatal Error - URL: http://google.com");
}
I hope the instruction is pretty clear. Your help would be greatly appreciated and rewarded!
Thanks! :-)
You can look at using register_shutdown_function(). It can be used to execute on E_ERROR(fatal error)
register_shutdown_function('shutdown');
function shutdown()
{
if(!is_null($e = error_get_last()))
{
mail("myemail#email.com", "Fatal Error - ". var_export($e, true));
}
}
I would however echo thoughts in the comments above that this is best handled using log monitoring.
Init following function inside your php file.
register_shutdown_function('mail_on_error'); //inside your php script
/** If any file having any kind of fatal error, sln team will be notified when cron will
become fail : following is the name of handler and its type
E_ERROR: 1 | E_WARNING: 2 | E_PARSE: 4 | E_NOTICE: 8
*/
function mail_on_error() {
global $objSettings;
$error = error_get_last();
//print_r($error);
if ($error['type'] == 1) {
// update file path into db
$objSettings->update_records($id=1,array('fatal_error' => json_encode($error)));
$exception_in_file_path = __FILE__;
fatal_error_structure($exception_in_file_path);
}// end if
}// end mail_on_error
fatal_error_structure should be defined on some global location. like function.inc.php. This will send an email to registered user.
function fatal_error_structure($exception_in_file_path){
$subject = "FATAL: Cron Daemon has failed";
sln_send_mail(nl2br("Please check $exception_in_file_path, This cron having FATAL error."),
$subject, 'email#address.com',$name_reciever='', 'text/plain');
}// end fatal_error_structure
vKj

stsadm supports just a few parameters

I try to use the "editssp" command of stsadm, but for some strange reason the stsadm command supports less parameters on our live Sharepoint server than my local Sharepoint installation. Compare the first screenshot with the second:
Both have the same file version: 12.0.6421.0
I really need the "indexlocation" parameter. Does someone have an idea why there is only a small amount of parameters supported?
Are you sure that both servers have the same search configuration? I believe, not.
This command is implemented by Microsoft.Office.Server.CommandLine.EditSsp class in Microsoft.Office.Server.dll.
If you look at the implementation of this class in IlSpy, you can see that it checks if "search service is installed" and adjusts both the help messages and also - what the command actually does.
Excerpt from code:
// Microsoft.Office.Server.CommandLine.EditSsp
public override string HelpMessage
{
get
{
string str = "-title <SSP name>\r\n [-newtitle <new SSP name>]\r\n [-sspadminsite <administration site url>]\r\n [-ssplogin <username>]\r\n [-ssppassword <password>]";
if (base.IsSearchInstalled)
{
str += "\r\n [-indexserver <index server>]\r\n [-indexlocation <index file path>]";
}
return str + "\r\n [-setaccounts <process accounts (domain\\username)>]\r\n [-ssl <yes|no>]";
}
}

SharpSSh: RunCommand in SshExec is always returning an empty string

When Using SharpSSh and the SshExec class, I can't get the RunCommand to work, it always returns an empty string. When I debug the SharpSsh library it returns -1 when it tries to read the command from a stream. It works when I use the sftp class in the same library, but that class doesn't support all the ftp commands I need.
Here is a standard example, I can't get this to produce a correct result either
SshConnectionInfo input = Util.GetInput();
SshExec exec = new SshExec(input.Host, input.User);
if(input.Pass != null) exec.Password = input.Pass;
if(input.IdentityFile != null) exec.AddIdentityFile( input.IdentityFile );
Console.Write("Connecting...");
exec.Connect();
Console.WriteLine("OK");
while(true)
{
Console.Write("Enter a command to execute ['Enter' to cancel]: ");
string command = Console.ReadLine();
if(command=="")break;
string output = exec.RunCommand(command);
Console.WriteLine(output);
}
Console.Write("Disconnecting...");
exec.Close();
Console.WriteLine("OK");
Any ideas on how I can get the RunCommand function to run some commands?
Thanks for any help :)
To get the standard output and error streams from .RunCommand,
I'll repeat the answer I posted to: SharpSSH - SSHExec, run command, and wait 5 seconds for data!
You may want to try the following overload:
SshExec exec = new SshExec("192.168.0.1", "admin", "haha");
exec.Connect();
string stdOut = null;
string stdError = null;
exec.RunCommand("interface wireless scan wlan1 duration=5", ref stdOut, ref stdError);
Console.WriteLine(stdOut);
exec.Close();
If their API does what the name implies, it should put the standard output of your command in stdOut and the standard error in stdError.
For more information about standard streams, check this out: http://en.wikipedia.org/wiki/Standard_streams

Resources