[英]NET::SSH2 with sudo
I'm trying to run various commands with net:ssh2 however the commands need to be run as root. 我正在尝试使用net:ssh2运行各种命令,但是这些命令需要以root用户身份运行。 I have root logins disabled over SSH and I have keys setup, so I can ssh and use 'sudo su - root' to get root access without a password.
我通过SSH禁用了root登录,并且设置了密钥,因此我可以ssh并使用'sudo su-root'来获得没有密码的root访问权限。 The problem is that I need to run multiple commands so I was wondering if it's possible to connect, then sudo to root, then run all the commands I need without having to pipe an echo to sudo or use expect.
问题是我需要运行多个命令,所以我想知道是否可以连接,然后将sudo连接到root,然后运行我需要的所有命令,而不必将回显传递给sudo或使用Expect。
The relevant section of my code I'm working with is the following, I'd preferably like to sudo before the exec($commands[0]) if possible. 我正在处理的代码的相关部分如下,我希望尽可能在exec($ commands [0])之前sudo。
EDIT: I can't login directly to root with or without a password as it's against policy unfortunately. 编辑:我无法使用或不使用密码直接登录到root用户,这很遗憾违反了政策。 I have to connect with my user first.
我必须先与用户联系。
my $ssh2 = Net::SSH2->new();
$ssh2->connect($server) or die "$!\n";
if ($ssh2->auth_publickey($user,"/home/$user/.ssh/id_rsa.pub", "/home/$user/.ssh/id_rsa"))
{
my $chan = $ssh2->channel();
$chan->blocking(1);
$chan->exec($commands[0]);
my @users;
while(<$chan>) {push(@users,$_);}
my $stdout=join("",@users);
print $stdout;
}
I didn't try this, but su
has the -c
argument, which passes a single command to the shell to execute, and then finishes the shell. 我没有尝试过,但是
su
具有-c
参数,该参数将单个命令传递给Shell以执行,然后完成Shell。 This most likely corresponds to the -c
argument of your shell, which in fact happily accepts compound commands here, eg a list of commands separated by ;
这很可能对应于您的shell的
-c
参数,实际上它在这里很高兴地接受复合命令,例如,用;
分隔的命令列表;
. 。
Thus executing 这样执行
sudo su -c 'command1 ; command2 ; command3 ' - root
could work here. 可以在这里工作。 (Or even only one of those commands, and then repeatedly call these.)
(或什至只有这些命令之一,然后重复调用它们。)
(But I think there might be something wrong with the settings if they allow a passwordless sudo su - root
, but not normal sudo
command executing.) (但我认为,如果设置允许无密码的
sudo su - root
,但不允许执行普通的sudo
命令,则设置可能有问题。)
Instead of using sudo su -
just proceed each command with sudo
. 而不是使用
sudo su -
刚刚入手的每个命令sudo
。 If you are allowed to sudo without a password it should work just fine: 如果允许您在没有密码的情况下进行sudo,则应该可以正常工作:
$chan->exec("sudo $commands[0]");
If your command needs root's path just specify the full path to it. 如果您的命令需要root的路径,只需指定它的完整路径即可。 (Can't tell since you aren't showing what the command is.)
(由于您未显示命令的内容,所以无法判断。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.