how to parse password during the find command in linux? - 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.

Related

SSH Create Directory In Remote Site Using Perl Script

Previously I have asked a question here on how to determine whether a path is a directory or not in remote site using SSH. I wish to create the directory if the path is not a directory. I have tried following code with two ways but it seem not to be working. Thanks for everyone that helps here.
use File::Path;
my $destination_path = "<path>";
my $ssh = "usr/bin/ssh";
my $user_id = getpwuid( $< );
my $site = "<site_name>";
my $host = "rsync.$site.com";
if (system("$ssh $user_id\#$host [ -d $destination_path ]") == 0) {
print "It is a directory.\n";
} else {
print "It is not a directory.\n";
#First Way
if(system("$ssh $user_id\#$host [ make_path ($d_path_full) ]") == 0{
#Second Way
if(system("$ssh $user_id\#$host [ mkdir -p $d_path_full ]") == 0{
print "Create directory successfully.\n";
} else {
print "Create directory fail.\n";
}
}
The bracket(s), single [ or the pair [ ], is a builtin in bash which is a test operator (see man test), and the last use of it is incorrect. But you don't need it to make a directory
use warnings;
use strict;
use feature 'say';
my $ssh = '/usr/bin/ssh';
my $user_id = ...
my $host = ...
my $to = quotemeta $user_id.'#'.$host;
my $cmd = 'mkdir -p TEST_MKDIR_OVER_SSH';
system("$ssh $to $cmd") == 0 or die "Can't mkdir: $!";
The mkdir is quiet with -p if a directory already exists, and it returns succes what also defeats the purpose of [ ] (if that was the intent). But an actual error -- a file with that name exists, no permissions on the path, etc -- does make its way back to the script, as you'd want, and a string with the error message is in $! so please test for this.
If you simply wish to know whether the directory existed please put back your test branch, or just omit -p and analyze the $! for what that message is on your system.
As for the second attempt: the command to be executed runs on the remote system and has nothing to do with this script anymore (apart from interpolated variables). So Perl functions or libraries from this script make no sense in that command.
For the next step I suggest to look into modules for (preparing and) running external commands, that are much more helpful than the bare system.
Some, from simple to more capable: IPC::System::Simple, Capture::Tiny, IPC::Run3, IPC::Run. Also see String::ShellQuote, to prepare commands and avoid quoting issues, shell injection bugs, and other problems. This recent post is a good example, and there's a lot more out there.
I would recommend using a proper module to do SSH, namely Net::OpenSSH, a SSH client built upon OpenSSH.
While being implemented in pure Perl, it is fast and stable, and has no mandatory dependency (apart of course, OpenSSH binaries).
As explained in the docs, it will, under certain conditions, automatically quote any shell metacharacters in the command lists.
The following codes demonstrates how it can respond to your use case. It relies on the same shortcut explained by #zdim, using mkdir -p :
if the directory does not exists, it gets created (if that fails, an error happends)
if it already exists, nothing happens
if a file exists with the target name, an error happens
Code :
use warnings;
use strict;
use Net::OpenSSH;
my $host = ...;
my $user_id = ...;
my $destination_path = ...;
# connect
my $ssh = Net::OpenSSH->new($host, user => $user_id);
$ssh->error and die "Can't ssh to $host: " . $ssh->error;
# try to create the directory
if ( $ssh->system('mkdir', '-p', $destination_path) ) {
print "dir created !\n";
} else {
print "can't mkdir $dir on $host : " . $ssh->error . "\n";
}
# disconnect
undef $ssh;

plink in PowerShell to run commands on Linux machine (SuSE)

I am trying to automate the process of adding extra storage in a linux machine. I'm using plink in PowerShell installed on my Windows machine.
Below is the code:
$plinkpath = "C:\Users\mydrive\Modules\plink.exe"
if (Test-Path $plinkpath) {
Set-Alias plink $plinkpath
} else {
throw "Plink.exe is reqruied"
}
$passw = "linuxadmin$123"
$commands = #(
"sudo su;",
"pvcreate /dev/sde;",
"vgcreate test_vog /dev/sde",
"lvcreate -l 100%FREE -n test_lev test_vog;",
"mkfs.ext3 /dev/test_vog/test_lev;",
"mkdir /azurenew;",
"echo ""/dev/test_vog/test_lev /azurenew/ ext3 defaults 1 1"" >> /etc/fstab;",
"mount /azurenew/;"
)
Approach 1: Using .ppk file
plink -ssh -i "C:\Users\amurthy\Documents\WindowsPowerShell\Modules\sshprivate.ppk" linuxadmin#xx.xx.xx.xxx $commands
In the above situation PowerShell hangs and no response on the console. Not sure what's happening.
Approach 2: using direct log in
plink -P "22" -v "linuxadmin#xx.xx.xx.xxx" -pw "linuxadmin$123" $commands
Here, I get below response on console
Using username "linuxadmin".
Sent password
Password authentication failed
I do not understand why the passoword authentication failed though I am able to login using putty.exe with that password.
Can anyone please help me here to solve my above automation problem? If you have any better solution altogether really welcome.
The password login attempt fails because you defined the password in a double-quoted string. PowerShell tries to expand the (undefined) variable $123 in linuxadmin$123, so you're actually passing just linuxadmin as the password. You could use a single-quoted string to avoid this, but public key authentication (your first approach) is the better approach anyway, so I recommend sticking with that.
I'm not sure why your first approach causes the console to hang, though. If the key were password-protected you should be prompted for the password. There's a semicolon missing at the end of "vgcreate test_vog /dev/sde", but if that caused an issue I'd expect to see an error message.
Try running plink with the parameter -v (verbose messages) to get a better picture of what's going on.

how to run command on telnet command prompt in perl script

i am executing telnet command in perl script as below.
$telnetOutput = `telnet localhost 4505`;
print "\n telnet command output: $telnetOutput \n";
$clients = `clients`;
print"\n $clients\n";
$clientNumber_or_anyOtherKey = `1`;
print "\n $clientNumber_or_anyOtherKey \n";
$pollers = `pollers`;
print "\n $pollers\n";`
but after running $telnetOutput = `telnet localhost 4505`; command, as we know it will open telnet command prompt but all other commands are still executing in same old command prmopt so it's saying clients or 1 or pollers are not recognized as internal or external commands.
can any 1 help me out pls?
thanks in advanch
Communicating with external processes like telnet is more complicated than you might imagine, as you have to correctly handle buffering, waiting for input, and so on.
The canonical way to approach this is to use Expect ( https://metacpan.org/module/RGIERSIG/Expect-1.21/Expect.pod ) if you really need full interaction.
If you don't actually need interaction then a remote command runner like ssh or rsh (which you can call from perl of course) is sufficient.
this is working example for telnet connection to d-link des-1228 router and executing 2 commands. change it if you want:
#!/usr/bin/perl
use strict;
use warnings;
use Net::Telnet;
my $params;
$params{'login'}='root';
$params{'password'}='hardpass';
$params{'default_prompt'}='/DES-[^:]+:.#/'; #change it to regexp matching your prompt
my $host = '192.168.1.20';
my $t=new Net::Telnet(Timeout=>5, Prompt=>$params{'default_prompt'}, Errmode=>sub{next;});
$t->open(Host=>$host, Timeout=>2);
my $res=$t->login($params{'login'}, $params{'password'});
return if $res!=1;
$t->cmd('disable clipaging');
my #lines=$t->cmd('show fdb'); #output here
$t->close();
install TCL (ActiveTcl8.5.13.0.296436-win32-ix86-threaded.exe for windows) in system.
Then install Expect Package from Command from as teacup install Expect
run below script after modification for requirement
#!/usr/bin/expect -f
#!usr/bin/expect
package require Expect
# Test expect script to telnet.
spawn telnet localhost portnumber
expect "TradeAggregator>"
send "3\r"
expect "Client:"
send "1\r"
expect "1-Client>"
send "2\r"
expect "Client Pollers"
send "2\r"
expect "1-NYMEX UTBAPI"
send "1\r"
expect "2-NYMEX UTBAPI"
send "Test_123\r"
expect "Are"
send "n\r"
send "exit\r"
send "exit\r"
send "exit\r"
# end of expect script.

How can I connect to sftp using linux command from Perl

#!/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.

Linux returns "select: Bad file descriptor" error after using "cat"

I am running a Perl script to read from multiple files on a remote machine. My code looks something like this:
open HANDLE, "/usr/bin/ssh $host cat /home/log_1.log /home/log_2.log 2>>./errorLog.log |"
Basically I am storing the file contents into HANDLE and all errors go into the errorLog.log file. But in my errorLog.log file I keep seeing "select: Bad file descriptor". I am not sure what's causing this and Google searching did not help very much. So my questions are: what does this error mean and how can I resolve it?
EDIT: In the above command, log_2.log may not exist in the remote machine. In that case, I wanted to output the error message into errorLog.log. So when my script finds that the log_2.log file does not exist in the machine, it should log "cat: /home/log_2.log: No such file or directory" but sometimes I see "cat: /home/log_2.log: No such file or directoryselect: Bad file descriptor" (two error messages without a newline).
I see three things wrong with your code:
you aren't checking the return value of open
you are using the two argument version of open
and you are using a bareword filehandle
The first will probably tell you what is going wrong, the other two are not wrong per se, but are not Modern Perl. I would write the code like this
open my $fh, "-|", "/usr/bin/ssh $host cat /home/log_[12].log 2>>./errorLog.log"
or die "could not run remote command: $!";
Or better yet
use IPC::Open3;
use Symbol 'gensym';
my $err = gensym; #deal with stupidity in the IPC::Open3 interface
my $pid = open3 my $in, my $out, $err,
"/usr/bin/ssh", $host, "cat", "/home/log_[12].log";
while (<$out>) {
#do stuff with the stdout of ssh
}
While (<$err>) {
#do stuff with the stderr of ssh
}

Resources