简体   繁体   English

通过ssh运行sudo命令

[英]Run sudo command via ssh

I'm trying to run command sudo -u [USER] [COMMAND] from java code on remote Linux machine and nothing happened. 我正在尝试从远程Linux机器上的Java代码运行命令sudo -u [USER] [COMMAND] ,但没有任何反应。 I use the ganymed-ssh2 jar . 我使用ganymed-ssh2 jar When I run the command without sudo its work perfect. 当我在不使用sudo的情况下运行命令时,它的工作非常完美。

Also if I run sudo -u [USER] [COMMAND] from Linux machine it works perfect. 另外,如果我从Linux机器上运行sudo -u [USER] [COMMAND] ,它也可以正常运行。 How I can run this command from java? 我如何从Java运行此命令?

Connection conn= SshConnection.GetConnection(hostname, username, password)

Session sess= conn.openSession(); 

sess.execCommand(command);

You need to get the secured stream and pass the password. 您需要获取安全的流并通过密码。

Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand("sudo -S -p '' " + command);
channel.setInputStream(null);
OutputStream out = channel.getOutputStream();
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
((ChannelExec) channel).setPty(true);
channel.connect();
out.write((password + "\n").getBytes());
out.flush();;

Taken from here: http://codeflex.co/java-run-sudo-command-on-remote-linux-host/ 从这里获取: http : //codeflex.co/java-run-sudo-command-on-remote-linux-host/

You can only run this remotely if the sudoers configuration on the server allows this specific command executed by the given user in the name of the other user to run w/o asking for password (ie NOPASSWD option). 仅当服务器上的sudoers配置允许该给定用户以其他用户的名义执行的特定命令运行而NOPASSWD输入密码(即NOPASSWD选项)时,才可以远程运行此命令。 Password entry for sudo can only be keyboard interactive which you cannot do remotely. sudo密码输入只能是键盘交互的,不能远程进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM