1

我想从另一个 EC2 实例在远程 EC2 实例上创建一个文件夹,然后也将一些数据复制到其中。

我尝试使用 JSch 并传递命令来创建文件夹,sudo mkdir /data但我得到的错误是sudo: sorry, you must have a tty to run sudo。如果没有 sudo,我也无法创建文件夹。我尝试使用((ChannelExec) channel).setPty(true)并通过使用它可以创建文件夹,但之后我无法复制任何数据,甚至无法从命令行 SSH EC2 实例。(如果我手动创建文件夹,则复制数据成功完成)。有人可以指导我应该怎么做。谢谢

4

2 回答 2

0

I am not familiar with JSch. But if you have root access, you can update your sudoers configuration file to get around this. Add the following line to /etc/sudoers

Defaults:USERNAME_HERE !requiretty

Maybe someone else can elaborate on whether this is a bad idea or not, that's beyond the scope of my knowledge, but I'd love to know more?

I only use this approcah in one specific situation. We have a cronjob that backs up a cluster of remote servers via rsync, but for rsync to run successfully, it needs sudo privileges.

To get around this I did the following-

  1. Created a user "backupuser" - On both servers local & remote
  2. Added the following two lines to /etc/sudoers - Only needed on the server you want to grant sudo privileges to the user on. In our case, only on the remote server.

    backupuser ALL = NOPASSWD: /usr/bin/rsync
    DEFAULTS:backupuser !requiretty
    

Adding these two lines grants the user, 'backupuser' sudo privileges for rsync command without the need to enter a password and without the required tty connection.

Here's how it works-

The first line breaks down into two parts.

USER SPECIFICATION OPTION_TAG (: CONDITIONS(opt))
  1. USER SPECIFICATION - this sets the user that these options apply(s) too.

    backupuser
    
  2. OPTION_TAG - the tag for the option you what to grant. In this case, the user is granted sudo privileges without having the enter a password. (see man sudoers for a list of tags available)

    ALL = NOPASSWD
    
  3. CONDITIONS - You also have the option to place conditions on when to grant sudo privileges. In this case, the user only has sudo privileges to run the rsync command.

    : /usr/bin/rsync
    

The second line, overrides the default requirement of the sudo command that you need a terminal connection to run sudo (tty requirement). And it grants this privilege only to the user account 'backupuser'. (See man sudoers for the other DEFAULTS)

DEFAULTS:backupuser !requiretty

Hope this helps answer your question. I know it went on a bit of a tangent, but I wanted to give a full explanation. For more info you can also checkout man sudo

于 2012-08-13T17:11:47.460 回答
0

下面的例子怎么样?

http://www.jcraft.com/jsch/examples/Sudo.java.html
于 2012-08-13T13:13:08.320 回答