비밀번호가 필요한 명령을 사용하여 Linux에서 인증하는 방법은 무엇입니까?

비밀번호가 필요한 명령을 사용하여 Linux에서 인증하는 방법은 무엇입니까?

어떤 이유로 서버에서 nohup을 실행하면 서버에서 로그아웃할 때 권한이 변경되고 충돌이 발생하는 문제가 있습니다.

그래서 나는 이것을 실행하라는 조언을 받았습니다.

/afs/cs/software/bin/reauth

tmux/스크린에서. 하지만 tmux를 사용하고 싶습니다. 그래서 해당 명령을 main.sh스크립트 에 넣고 싶지만 암호를 묻는 메시지가 나타납니다. main.sh스크립트 내부에 있고 실행할 때 사용자 상호 작용 없이 실행되도록 명령에 암호를 제공/입력하는 방법이 있습니까 ?

현재 나는 이렇게 합니다:

/afs/cs/software/bin/reauth

내 상호 작용을 요청합니다

(metalearning_gpu) brando9~/diversity-for-predictive-success-of-meta-learning $ /afs/cs/software/bin/reauth
Password for brando9: 

하지만 비밀번호를 한 번 입력하여 작동/확인하기를 원합니다.

서버 위키의 세부정보:

Long-running jobs

Problem
You start a screen session on one of our servers. Everything runs fine, you detach the screen and log out. You log back into the server, reattach the screen and realize that things are failing left and right because you lost file system permissions.

Solution
Use krbscreen and reauth.

How to use krbscreen and reauth
Below are the steps you need to take to successfully run a long-lived session on our machines:

kill all the existing reauth processes that you might be running
ssh to the relevant host: ssh [email protected]
run krbscreen on the host: /afs/cs/software/bin/krbscreen; run krbtmux on the host: /afs/cs/software/bin/krbtmux
run reauth: /afs/cs/software/bin/reauth
your commands inside krbscreen
detach the screen as you would normally
When you decide to re-attach your screen session you can use the regular screen command:

ssh to the relevant host: ssh [email protected]
re-attach your screen session: screen -x
krbscreen is just a wrapper around regular screen that runs aklog and makes copies of your current kerberos tickets.

경우 링크https://ilwiki.stanford.edu/doku.php?id=hints:long-jobs작동하지 않습니다.

콘텐츠 rauth:

(metalearning_gpu) brando9~ $ cat /afs/cs/software/bin/reauth
#!/usr/bin/perl
# $Id: reauth 2737 2011-06-20 18:14:05Z miles $
#
# Original version (C) Martin Schulz, 2'2002
# University Karlsruhe
#
# Modifications by Miles Davis <[email protected]>
#  Super minimal -- call programs rather than functions to reduce dependence
#  on extra perl modules.
#
# Heimdal patches thanks to Georgios Asimenos <[email protected]>
#

# General:
##########

# This little script aims at maintaining a valid AFS token from a
# users password for long running jobs.

# As everybody knows (or should know) Kerberos tickets and AFS tokens
# only have a limited lifetime. This is so by design and is usually
# reasonable. After 12 hours, it is no more obvious that it is really
# that user sitting in front of the computer that once typed the
# correct password in. Furthermore the damage caused by compromized
# AFS tokens is limited to the lifetime of that ticket.

# However, there are situations when users want to use long running
# jobs that will write to AFS filespace for several days. Renewable
# tickets are not so much of help here, since they can only be renewed
# if ....

# Therefore the secret has somehow deposited on the local computer
# that will run the long time job. This can be eiter done by storing a
# keytab on the local disk, maybe with a cron(*) principal with
# reduces priviledges. The approach taken here is to work with the
# original password and keep it in RAM only.

# When starting this program, the user is asked for his principal and
# the corresponding password. Then the TGT and AFS token is obtained
# and displayed, afterwards, a background process is forked and the
# main process will return to the system prompt. The workload program
# can now be started.

# The background process will periodically attempt to obtain krb
# tickets and AFS tokens. If this fails for some reason (Kerberos
# server not available or anything, the program aborts.

# aklog does not create a new pag if not told so. If you want your
# background process have a separate pag, create it beforehand.

# The reauth.pl program will work until eternity if is not stopped
# somehow. The canonical way is kill it by "kill $pid", where $pid is
# the process id printed before the return of the initial call to
# reauth.pl or found in the output of "ps".


# (*) Cron jobs are another issue. Our institute introduced
# user.cron-style principals to enable cron to obtain a token and then
# work on restricted parts of the users home directories.


# Security issues:
##################

# reauth.pl will run forever if you do not stop it, so don't forget that!

# The password is kept in RAM (of the child process). AFAIK, this can
# only be recovered by local root (who you need to trust anyway). It
# will not survive a reboot of the local machine.

# The password is not kept on any disk. Therefore any bootfloppy
# (reboot to single user mode..)  or screwdriver (take disk away..)
# attacks are not promising.

# Be aware that your NSA-, FBI-, MI5-, KGB-, ElQaida-, or (*insert
# your favorite opponent or competitor here*)-sponsored cleaning
# personnel or coworkers might have even more elaborate means... :-)


# BUGS:
#######

# Only mildly tested only on Linux and Solaris.

# Uses kinit, aklog, klist and tokens programs for a KerberosV/ Ken
# Hornstein's migration kit centered AFS setup. Please adjust to your
# config.




###########################################################################
# Configs:


# kinit program, add path if necessary
if ( -e "/usr/kerberos/bin/kinit" ) {
    $kinit="/usr/kerberos/bin/kinit";
} elsif ( -e "/usr/lib/heimdal/bin/kinit" ) {
    $kinit = "/usr/lib/heimdal/bin/kinit";
} elsif ( -e "/usr/bin/kinit" ) {
    $kinit="/usr/bin/kinit";
} else {
    die("Couln't find kinit.\n");
}


# aklog program, add path if necessary
if ( -e "/usr/bin/aklog" ) {
    $aklog="/usr/bin/aklog";
} elsif ( -e "/usr/lib/heimdal/bin/afslog" ) {
    # or, afslog, for heimdal weirdos
    $aklog="/usr/lib/heimdal/bin/afslog";
} else {
    die("Couln't find aklog or afslog.\n");
}

# klist program, add path if necessary
$klist="/usr/kerberos/bin/klist";

# tokens program, add path if necessary
$tokens="/usr/bin/tokens";


#################################################################
# Program:

use Getopt::Long;
use POSIX qw(setuid);
use POSIX qw(setgid);
use POSIX qw(setsid);

# Defaults for command line options.
my $keytab = '';
my $command = '';
my $username = '';
my $debug = 0;
my $verbose = 0;
my $interval=15000; # time interval in seconds: 4+ hours:

my %opts = (
    # Keytab
    'k=s' => sub {
                    $keytab = @_[1];
                    $kinit_opts .= "-k -t $keytab ";
                },
    # Run command
    'c=s' => sub {
                    $command = @_[1];
                },
    # Run command as user
    'u=s' => sub {
                    $username = @_[1];
                },
    # Time interval to sleep
    'i=i' => sub {
                    $interval = @_[1];
                },
    # Debug
    'd'   => sub {
                    $debug++;
                },
    # Be versbose
    'v'   => sub {
                    $verbose++;
                },
);


GetOptions(%opts) or die "Usage: reauth [ -k=keytab ] [ -u user ] [ -i <sleep_interval ] [ -v ] [ -c <command> ]\n";




if(@ARGV) {
    $princ = $ARGV[0];
    debug_print(2, "Principal name provided by argument = $princ");
} else {
   # Assume we want the login name as the principal name
    $princ = getpwuid($<);
    debug_print(2, "Principal name provided by argument = $princ");
}

if ($keytab) {
    # Don't ask for password, a keytab was provided.
    debug_print(1, "Keytab provided = $keytab");
} else {
    # read password, but turn off echo before:
    print "Password for $princ: ";
    system "stty -echo";
    $passwd = <STDIN>;
    system "stty echo";
    printf "\n";
    chomp $passwd;
    # Actually get the tickets/tokens
    if(obtain_tokens()!=0) {
        die "Can't obtain kerberos tickets\n";
    }
    if ($verbose) {
        show_tokens();
    }
}

# fork to go into background:
# a) the parent will exit
# b) the child will work on
$pid = fork();
if ($pid) {
    # I am the parent.
    printf "Background process pid is: $pid\n";
    if ($command) {
        debug_print(1,"Waiting for child to die.");
        wait;
        debug_print(1,"Child is dead.");
    }
    exit 0;
} else {
    # I am the child.
    debug_print(2,"I am process $$");
    print "Can't set session id\n" unless setsid();

    debug_print(2,"KRB5CCNAME: " . $ENV{KRB5CCNAME});
    #if ($ENV{KRB5CCNAME}) {
        #$ENV{KRB5CCNAME} =  $ENV{KRB5CCNAME} . "_reauth_$$";
    #} else {
        #$ENV{KRB5CCNAME} =  "/tmp/krb5cc_reauth_$$";
    #}

    #debug_print(2,"Creating " . $ENV{KRB5CCNAME});
    #system "touch $ENV{KRB5CCNAME}";


    if ($username) {
        debug_print(1, "Looking up UID for $username");
        ($name,$passwd,$UID,$GID, @junk) = getpwnam($username);
        debug_print(1, "Changing to UID $UID, GID $GID");
        print "Can't set group id\n" unless setgid($GID);
        print "Can't set user id\n" unless setuid($UID);
        if ($ENV{KRB5CCNAME}) {
            $ENV{KRB5CCNAME} =  $ENV{KRB5CCNAME} . "_reauth_$$";
        } else {
            $ENV{KRB5CCNAME} =  "/tmp/krb5cc_reauth_$$";
        }
    }

    debug_print(2, "Running as uid " . $<);
    # Actually get the tickets/tokens
    if(obtain_tokens()!=0) {
        die "Can't obtain kerberos tickets\n";
    }

    if ($verbose) {
        show_tokens();
    }

    # If I was told to run a command, do it.
    if ($command) {
        debug_print(1,"About to exec $command");
        exec($command) or die "Can't execute '$command'.\n";
        exit
    }

    debug_print(2,"Going into auth loop (interval is $interval).");

    #close(STDOUT);
    #close(STDERR);

    # Otherwise, work until killed:
    while (1) {
        debug_print(2,"Waking up to obtain new tokens.");
        obtain_tokens();
        if ($verbose) {
            show_tokens();
        }
        sleep $interval;
    };
}

#################################################################


sub obtain_tokens() {

  # ignore sigpipes' (according to perlopentut)
  $SIG{PIPE} = 'IGNORE';

    #debug_print(1,"Running: | $kinit -f $kinit_opts -p $princ 1>/dev/null 2>&1");

  # run kinit
  open(KINIT, "| $kinit -f $kinit_opts -p $princ 1>/dev/null 2>&1");

  # pass password to stdin, password does not show up on command line
  if (! $keytab) {
      print(KINIT "${passwd}\n");
  }

  # close pipe and get status
  close(KINIT); $status=$?;

    debug_print(1,"kinit exited with status $status\n");
  # act on status..
  if($status == 256) {
        if ($verbose) {
            print "WARNING: kinit is not able to obtain Kerberos ticket ($status).\n";
            print "         Possible DNS or network problem. Continuing anyway...\n";
        }
        return 1;
  } elsif($status!=0) {
    print "kinit is not able to obtain Kerberos ticket: $status\n";
     return 2;
  };

    debug_print(1,"Running $aklog...\n");
  $status = system "$aklog >/dev/null" ;
    debug_print(1,"aklog exited with status $status\n");
  if($status!=0) {
    print "aklog is not able to obtain AFS token: $status\n";
     return 3;
  };

  return 0;

};

##################################################################

sub show_tokens() {
    system $klist ;
    system $tokens ;
};

##################################################################

sub debug_print($$) {
    my $level = shift;
    my $message = shift;

    if ($debug >= $level) {
        print "DEBUG$debug: $message\n";
    }
}

##################################################################

관련된:이미 실행 중인 nohup 프로세스에 새 명령을 보내거나 nohup에서 두 명령을 함께/동시에 실행하는 방법은 무엇입니까?다른 명령과 함께 nohup 명령에서 reauth(kerberos 티켓 업데이트)를 실행해 보세요.

답변1

자세한 내용을 모르면 reauth귀하의 사건을 어떻게 해결할 수 있을지 추측하기 어렵지만 비밀번호를 어디에도 전달할 필요는 없다고 생각합니다.

상황은 다음과 같습니다. 액세스 중인 시스템은 인증을 위해 Kerberos를 사용합니다. 이는 귀하가 로그인할 때 귀하의 비밀번호(또는 기타 인증 방법)가 요청에 사용된다는 것을 의미합니다.티켓. 티켓은 본질적으로 액세스 코드입니다. 로그인 시 요청한 티켓이 호출됩니다.티켓 부여 티켓, 액세스해야 하는 소프트웨어의 다른 부분에 대한 티켓을 제공할 수 있습니다. 특히 NFS(네트워크 파일 시스템)를 통해 디렉터리에 액세스할 수 있습니다.

이 티켓 부여 티켓은 주기적으로 만료되어 klist만료되는 시점을 확인합니다. 또한 "갱신 기한"이라는 줄이 표시됩니다. 인증 비밀(비밀번호)을 알고 있음을 증명할 필요 없이 해당 기간 내에 해당 티켓을 갱신할 수 있습니다. 기간은대개일주일.

따라서 "갱신 기한" 이후에 실행되는 작업이 없는 경우 비밀번호 없이 티켓 부여 티켓을 갱신할 수 있으며 필요한 모든 파일에 계속 액세스할 수 있습니다.

kinit -R티켓이 "만료"되기 전에 실행하세요. 대부분의 시스템에서 티켓은 10시간 후에 만료되지만 시스템은 다를 수 있습니다. 어쨌든 티켓이 4시간 후에 만료된다는 가정하에 1시간 30분마다 티켓을 업데이트하는 것은 매우 합리적인(그리고 너무 짜증나지 않는) 방법입니다. 별도의 tmux 창에서 실행되는 작은 while 루프로 문제를 간단히 해결할 수 있습니다.

while true; do kinit -R; sleep $((60 * 60 * 3 / 2)); done

이제 작업이 "갱신 기한"보다 오래 지속되면 운이 없게 됩니다.어떤 시점에서는 비밀번호가 포함된 새로운 티켓 부여 티켓을 받아야 합니다.. 다행히도 kinit비밀번호를 어디서 얻을 수 있는지는 까다롭지 않습니다. 따라서 kinit다음과 같이 비밀번호를 입력할 수 있습니다 .

echo 'totally secret password' | kinit [email protected]

[email protected]"Default Body"에서 보는 것과 동일한 작업을 수행합니다 .klist

귀하의 컴퓨터에서 실행되는 스크립트는 reauth귀하의 비밀번호를 알 수 있는 방법이 없기 때문에 물어볼 필요가 있지만 결국에는 대부분 다음과 같은 작업을 수행할 것입니다. 비밀번호 없이 재생 가능한 티켓 부여 티켓을 가능한 한 오랫동안 업데이트된 상태로 유지합니다. 일주일에 시작 시 필요한 비밀번호를 사용하여 새 티켓 부여 티켓을 요청하세요.

관련 정보