Script Kerberos Ktutil to make keytabs

With GNU bash:

user="PRINCIPAL"
pass="topsecret"

printf "%b" "addent -password -p $user -k 1 -e aes256-cts-hmac-sha1-96\n$pass\nwrite_kt $user.keytab" | ktutil

printf "%b" "read_kt $user.keytab\nlist" | ktutil

Output:

slot KVNO Principal
---- ---- ---------------------------------------------------------------------
   1    1                          PRINCIPAL@YOURDOMAIN

To create the multiple orgs keytabs and default hbase,pipe,hdfs keytab at the same time you can run the below script, which i have just created:

#!/bin/bash
read -p "Please enter space-delimited list of ORGS to create: " NEW_ORGS

clear
#echo "#################  CREATE KEYTABS  ############################"
#echo ""
kdestroy

for i in $NEW_ORGS
do
     printf "%b" "addent -password -p ${i} -k 1 -e aes256-cts-hmac-sha1-96\n${i}\nwrite_kt ${i}.keytab" | ktutil

     printf "%b" "read_kt ${i}.keytab\nlist" | ktutil

done
echo ""


if [ ! -e /home/eip/.keytabs/hbase.keytab ]
then
        printf "%b" "addent -password -p hbase -k 1 -e aes256-cts-hmac-sha1-96\nhbase\nwrite_kt hbase.keytab" | ktutil

        printf "%b" "read_kt hbase.keytab\nlist" | ktutil
fi

exit 0

Use expect to keep the password out of the process list:

expect << EOF
    set timeout 10
    spawn /usr/bin/ktutil
    expect {
       "ktutil: " { send "addent -password -p $PRINCIPAL -k 1 -e $METHOD\r" }
       timeout { puts "Timeout waiting for ktutil prompt."; exit 1; }
    }
    expect {
       -re "Password for \\\\S+: " { send "$PASSWORD\r" }
       timeout { puts "Timeout waiting for password prompt."; exit 1; }
    }
    expect {
       "ktutil: " { send "wkt $KEYTAB_TMP\r" }
    }
    expect {
       "ktutil: " { send "q\r" }
    }
EOF

Or use a <<HERE document to provide stdin, but if addent fails to prompt, you may end up with the password in your stdout:

/usr/bin/ktutil <<EOF
addent -password -p $PRINCIPAL -k 1 -e $METHOD
$PASSWORD
wkt $KEYTAB_TMP
q
EOF

A version in Python

https://github.com/Tagar/stuff/blob/master/keytab.py

piping password to ktutil in shell is not secure as password will be visible in list of processes.

Since this Python scripts just interacts with ktutil using pexpect library, it's possible to implement the same as a pure shell script using expect.

Hope this helps.