Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A simple code runs at cmdline, but not in cron job

Status
Not open for further replies.

whn

Programmer
Oct 14, 2007
265
US
A simple code just like this:
Code:
my $cmd = "gwsh root\@$ip \"uname -r\"";
my $ret = `$cmd`;

When I ran the code at cmd prompt, it's fine.

But when it's run in a cron job, $cmd returns nothing.

What did I miss here?

Many thanks.
 
In addition, while the code is executed at cmd prompt, following three variables are the same as my own login ID:
$ENV{ LOGNAME }, getpwuid( $< ), & $ENV{ USER }.

However, while it's executed by the cron job, then $ENV{ USER } is undefined. But both $ENV{ LOGNAME } and getpwuid( $< ) are still the same as my own login ID.

Thanks.
 
I got the solution. I need to set up two ENVs to make cron job run. Basically calling setEnv() before invoke gwsh. My sample code is listed below:
Code:
sub setEnv {
	my $sshPid = getSshPid(user=>$ENV{LOGNAME}, psName=>'ssh-agent');
	my $sshAuthSock = getSshAuthSock(sshPid=>$sshPid);

	my %newEnvs = (
		'SSH_AGENT_PID', $sshPid,
		'SSH_AUTH_SOCK', $sshAuthSock,
	);

	foreach my $k (keys(%newEnvs)) {
		if(!exists($ENV{$k}) || !$ENV{$k}) {
			$ENV{$k} = $newEnvs{$k};
		}
	}
}

sub getSshAuthSock {
	my %args = (@_);

	my $FPID = $args{sshPid} - 1;

	my $cmd = "find /tmp -path \"*ssh*\" -type s -iname \"agent.$FPID\"";
	my $sshAuthSock = `$cmd`;
	chomp($sshAuthSock);

	return $sshAuthSock;
}

sub getSshPid {
	my %args = (@_);

	my $cmd = "ps -ef | grep $args{user} | grep $args{psName} | grep -v grep";
	my $ret = `$cmd`;
	my $pid = (split(/\s+/, $ret))[1];

	return $pid;
}

Question:
I used shell cmd in my perl code. Could someone show me how to implement this in PURE perl code?

Thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top