gpt4 book ai didi

linux - 模块 cwd 帮助

转载 作者:太空宇宙 更新时间:2023-11-04 12:20:41 24 4
gpt4 key购买 nike

我创建了一个 Perl 模块,用于许多 Perl 脚本以使用 Net::SSH::Expect进行登录。

package myRoutines;
#
use v5.22;
use strict;
use warnings;

use Net::SSH::Expect;
use Exporter qw(import);
our @EXPORT_OK = qw(my_login);

sub my_login {
my $user = 'xxxx';
my $port = '10000';
my $passwd = 'XYZ';
my $adminServer = 'myServer';
my $rootpassword = 'ABCDEF';

my ( $pName, $vName ) = @_;

our $ssh = Net::SSH::Expect->new(
host => "$adminServer",
ssh_option => "-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null",
user => "$user",
password => "$passwd",
port => "$port",
raw_pty => 1,
restart_timeout_upon_receive => 1,
log_file => "/var/tmp/clilog_$pName$vName"
);

eval {

my $login_output = $ssh->login();

if ( $login_output !~ />/ ) {
die "Login has failed.
Login output was $login_output";
}
};

return $ssh;
}

1;

脚本将做:

use myRoutines qw(my_login);

our ( $ssh, $pName, $vName );

$pName = 'abc';
$vName = '123';

$ssh = my_login( $pName, $vName );

$ssh->send( "some command\r" );

如果我在脚本和模块所在的目录中,这一切都有效。如果我在任何其他目录中,new 调用有效,但调用 $ssh ->send 什么都不做。

我已经尝试添加到我的脚本中:

use lib '/some/dir'; 

(.pm 文件所在的位置)强制它找到模块,当我不在 pm 文件所在的目录中时,这似乎有效。

我尝试过:

use File::chdir;
$CWD = '/some/dir';

再次,登录似乎有效,但下一次发送没有任何作用。所以我对可能发生的事情一头雾水,希望得到一些建议。

更新 20170908:

在进一步播放并按照提出的建议进行操作后,我完成了以下操作并且现在可以运行了:

删除了 eval,因为它是不必要的。删除我们的并使其成为我的。删除了“”的

在脚本中设置以下内容:

use File::Basename;
use Cwd qw( abs_path );
chdir "/some/dir";
use lib dirname(abs_path($0));
my $scriptName = basename($0);
use myRoutines qw(ovm_login);
my $pName = substr($scriptName,0,-3); (cutting off the .pl from the end of the script name to pass the scriptname as the pName)

使用 chdir 将目录更改为我的 pl 脚本和 pm 文件所在的目录,然后设置 lib 似乎可以正常工作。

Borodin,当你说要面向对象模块时,我不确定我是否理解你的意思......但我想听更多以便更好地理解。

最佳答案

如果你不想硬编码目录,你可以使用

use FindBin qw( $RealBin );
use lib $RealBin;

($RealBin 是脚本的路径。如果 myRoutines.pm 在子目录中,请根据需要进行调整。)

关于linux - 模块 cwd 帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46103513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com